diff --git a/.changeset/aws-device-farm-plugin.md b/.changeset/aws-device-farm-plugin.md new file mode 100644 index 0000000000..e49ef1fde8 --- /dev/null +++ b/.changeset/aws-device-farm-plugin.md @@ -0,0 +1,5 @@ +--- +'agent-device': minor +--- + +AWS Device Farm moves to a private, unpublished plugin. After publication, CLI hosts can install it with `agent-device plugins add @agent-device/aws-device-farm`; finish sessions, stop the detached daemon for its matching state directory, and retry. Embedded hosts import the factory, pass it to `startAgentDevice({ plugins: [awsDeviceFarm()] })`, and close and recreate the runtime after changes. diff --git a/.changeset/browserstack-provider-plugin.md b/.changeset/browserstack-provider-plugin.md new file mode 100644 index 0000000000..9d5cd75dc2 --- /dev/null +++ b/.changeset/browserstack-provider-plugin.md @@ -0,0 +1,5 @@ +--- +'agent-device': minor +--- + +Extract BrowserStack out of the bundled WebDriver provider into the new `@agent-device/browserstack` plugin package. Install it with `agent-device plugins add @agent-device/browserstack`, then close your sessions and run `agent-device daemon stop --state-dir ` for your daemon before reconnecting. Commands for a saved BrowserStack connection keep working while the plugin is installed; without it, `connect browserstack` explains how to install the plugin. diff --git a/.changeset/explicit-sdk-hosts.md b/.changeset/explicit-sdk-hosts.md new file mode 100644 index 0000000000..fe5fde90e4 --- /dev/null +++ b/.changeset/explicit-sdk-hosts.md @@ -0,0 +1,11 @@ +--- +'agent-device': minor +--- + +Require explicit SDK host dependencies in 0.22. Part of #3759 section 3. + +Pass `{ env, cwd }` to `runAndroidShell(device, words, host, options?)`, `runAndroidExecOut(device, words, host, options?)`, `resolveAndroidArchivePackageName(archivePath, host, signal?)`, `prepareMetroRuntime(options, host)`, and `new LimrunRuntime(options, host)`. For example, capture `const host = { env: { ...process.env }, cwd: process.cwd() }` in your entry point, then call `await prepareMetroRuntime(options, host)`. + +`resolveRemoteConfigProfile({ configPath, cwd, env })` requires `env`, and `createLocalArtifactAdapter({ cwd })` requires `cwd`. Archive inspection resolves relative paths from the supplied host and no longer shares a cached SDK tool across hosts. The internal contracts, host-kit, remote, and platform-android packages are bundled into `agent-device`; this changeset covers their affected public APIs. + +Executable captures and `startAgentDevice`'s optional-host capture remain available. See [Build an integration](/docs/build-an-integration#migrate-sdk-hosts-to-022) for migration examples. diff --git a/.changeset/managed-plugin-artifact.md b/.changeset/managed-plugin-artifact.md new file mode 100644 index 0000000000..8e402f650e --- /dev/null +++ b/.changeset/managed-plugin-artifact.md @@ -0,0 +1,5 @@ +--- +'agent-device': minor +--- + +Install local plugin tarballs with `plugins add` or the plugin manager API. Artifact selections record their version and SHA-512 integrity. To replace one, run `plugins remove ` and then `plugins add ./plugin.tgz`. Close active sessions and restart the daemon to apply the changed selection. diff --git a/.changeset/optional-maestro-engine.md b/.changeset/optional-maestro-engine.md new file mode 100644 index 0000000000..18d4c6ff90 --- /dev/null +++ b/.changeset/optional-maestro-engine.md @@ -0,0 +1,7 @@ +--- +'agent-device': minor +--- + +Release prerequisite: the plugin remains private and unavailable from npm until a usable package is published through the configured release workflow. + +Maestro YAML replay, suites, and export now require the optional `@agent-device/maestro` plugin. After publication, install it on each CLI and store-backed daemon host that uses these flows. Finish sessions and stop the matching daemon. Embedded hosts supply the factory through `startAgentDevice({ plugins })` and close/recreate the returned runtime; they do not use the CLI store or daemon stop command. Retry your original command to start a daemon with the updated plugin set; flow syntax and arguments stay the same. Native `.ad` replay remains available without this plugin. diff --git a/.changeset/optional-native-replay.md b/.changeset/optional-native-replay.md new file mode 100644 index 0000000000..5625e2b66d --- /dev/null +++ b/.changeset/optional-native-replay.md @@ -0,0 +1,8 @@ +--- +'agent-device': minor +'@agent-device/replay': minor +--- + +Release prerequisite: the replay plugin remains private and unpublished. Its npm installation command below is unavailable until a usable package is published through the configured release workflow. + +Native `.ad` replay and all test suites require the optional `@agent-device/replay` plugin on the daemon host. Run `agent-device plugins add @agent-device/replay`, finish your sessions and restart that daemon, then retry the original invocation with all its arguments. Remote hosts need their own installation. Embedded hosts supply the version 2 factory through `startAgentDevice({ plugins: [replay()] })` and own runtime replacement. Existing scripts, resume and repair syntax stay the same. Ordinary script recording remains in core. diff --git a/.changeset/remove-managed-client-lifecycle.md b/.changeset/remove-managed-client-lifecycle.md new file mode 100644 index 0000000000..8e67fa56e4 --- /dev/null +++ b/.changeset/remove-managed-client-lifecycle.md @@ -0,0 +1,5 @@ +--- +'agent-device': minor +--- + +Clients attach to an existing daemon and no longer start, replace, or retire it on timeout. This also applies to `client.replay.run()` and `client.replay.test()`; they no longer start a private daemon. Remove `daemonLifecycle: 'managed'` and call `ensureDaemon({ stateDir })` before creating a client for a detached daemon. To own a daemon in your process, call `startAgentDevice({ stateDir })` from `agent-device` and close its returned handle. CLI and MCP commands continue to ensure their daemon, including private one-shot replay/test startup and cleanup. diff --git a/.changeset/remove-provider-plugin-v1.md b/.changeset/remove-provider-plugin-v1.md new file mode 100644 index 0000000000..a18f09fb30 --- /dev/null +++ b/.changeset/remove-provider-plugin-v1.md @@ -0,0 +1,9 @@ +--- +'agent-device': minor +'@agent-device/testmu': minor +'@agent-device/revyl': minor +--- + +Remove the version 1 provider plugin contract. A store package is now discovered only through its exports: `./agent-device`, or the package root when that subpath is absent. The host no longer reads an `agentDevicePlugin` manifest to choose an entry or to declare a provider, connection capabilities, or credential variables, and `agent-device plugins add` no longer refuses a package for a provider another manifest claims — the registry settles a duplicate provider id when the daemon next composes its plugins, as the first claim wins. + +Migrate a plugin by exporting its factory from `./agent-device` and returning the manifest's values from the factory: `provider`, `credentials: { variables: [...] }`, an optional `connection`, and `setup(host)` that returns `{ runtime, platformModule }` or `{ webDriver }`, with `apiVersion: 2`. See [Provider plugins](/docs/plugins) for the full migration. A plugin object with an `apiVersion` other than 2 is listed as `failed` with `incompatible_plugin`, and a default export that is not a plugin factory with `invalid_plugin`; the daemon starts without either. diff --git a/.fallowrc.json b/.fallowrc.json index c1d92c5396..eb98ee2f06 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -5,12 +5,25 @@ "tools/depgraph-view/app.js", "scripts/check-provider-plugin.mjs", "scripts/check-affected/command.ts", + "packages/provider-aws-device-farm/test/package-smoke.mjs", + "packages/provider-browserstack/test/package-smoke.mjs", + "packages/provider-browserstack/tsdown.config.ts", "packages/provider-testmu/test/package-smoke.mjs", + "packages/maestro/test/package-artifact.test.mjs", + "packages/maestro/test/packed-clickability.mjs", + "packages/maestro/test/packed-screen-origin.mjs", + "packages/maestro/test/package-test-support.mjs", + "packages/maestro/test/package-smoke.mjs", + "packages/replay/test/package-smoke.mjs", + "packages/replay/test/packed-runtime.mjs", + "packages/maestro/test/packed-runtime.mjs", + "packages/maestro/tsdown.config.ts", + "packages/maestro/src/plugin.ts", + "packages/replay/src/plugin.ts", + "packages/replay/tsdown.config.ts", "packages/provider-testmu/tsdown.config.ts", - "packages/provider-testmu/src/plugin.ts", "packages/provider-revyl/test/package-smoke.mjs", "packages/provider-revyl/tsdown.config.ts", - "packages/provider-revyl/src/plugin.ts", "packages/provider-webos/test/package-smoke.mjs", "packages/provider-webos/tsdown.config.ts", "packages/provider-tizen/test/package-smoke.mjs", @@ -100,9 +113,9 @@ // @agent-device/provider-limrun owns the source import, while the published // root build externalizes @limrun/api and retains runtime imports in packed chunks. "@limrun/api", - // @agent-device/testmu imports agent-device type-only, and its tsconfig maps those specifiers - // through this workspace link to core source so typecheck needs no build; Fallow then credits - // the source files rather than the package. + // @agent-device/browserstack and @agent-device/testmu import agent-device type-only, and their + // tsconfigs map those specifiers through this workspace link to core source so typecheck needs + // no build; Fallow then credits the source files rather than the package. "agent-device", // Nothing in the root imports the TV plugins or the tv-cdp package they bundle, but layering // requires the root manifest to declare every workspace package. @@ -152,13 +165,8 @@ "exports": ["*"] }, { - // A published provider package's default export is its plugin contract; packages/plugins/src/load.ts imports the package by name at runtime and reads `default`. - "file": "packages/provider-*/src/index.ts", - "exports": ["default"] - }, - { - // The version 1 entry a provider package's `agentDevicePlugin.entry` names; hosts without the version 2 contract import the built file and read `default`. - "file": "packages/provider-*/src/plugin.ts", + // A published plugin's default export is its contract; the plugin loader imports the installed package's resolved entry at runtime and reads `default`. + "file": "packages/{provider-*/src/index,maestro/src/plugin,replay/src/plugin}.ts", "exports": ["default"] }, { @@ -288,7 +296,7 @@ }, { // Tool config default exports, loaded by the tool rather than imported. - "file": "{oxlint.config.ts,tsdown.config.ts,packages/provider-*/tsdown.config.ts,packages/proxy/tsdown.config.ts,vitest.mutation.config.ts}", + "file": "{oxlint.config.ts,tsdown.config.ts,packages/provider-*/tsdown.config.ts,packages/maestro/tsdown.config.ts,packages/replay/tsdown.config.ts,packages/proxy/tsdown.config.ts,vitest.mutation.config.ts}", "exports": ["default"] }, { diff --git a/.github/actions/run-gate/action.yml b/.github/actions/run-gate/action.yml index d387926703..05927133fe 100644 --- a/.github/actions/run-gate/action.yml +++ b/.github/actions/run-gate/action.yml @@ -15,6 +15,15 @@ outputs: runs: using: composite steps: + - name: Install first-party replay plugins for execution gates + if: contains(fromJSON('["unit", "unit-ci", "provider-integration", "integration-node", "macos-coverage", "web-smoke", "mutation", "fuzz-parsers", "maestro-differential", "replay-ios", "replay-ios-device", "replay-macos", "replay-linux", "replay-android", "linux-command-evidence", "concurrency-torture"]'), inputs.gate) + shell: bash + run: | + set -euo pipefail + pnpm --filter @agent-device/maestro --filter @agent-device/replay build + export AGENT_DEVICE_HOME="${AGENT_DEVICE_HOME:-$RUNNER_TEMP/agent-device-replay-plugins}" + node --experimental-strip-types scripts/install-workspace-replay-plugins.ts + echo "AGENT_DEVICE_HOME=$AGENT_DEVICE_HOME" >> "$GITHUB_ENV" - id: run shell: bash env: diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 01e594915e..be1d037ae9 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -30,6 +30,8 @@ jobs: if: ${{ !github.event.pull_request.draft }} runs-on: blacksmith-4vcpu-ubuntu-2404 timeout-minutes: 80 + env: + AGENT_DEVICE_HOME: ${{ github.workspace }}/.tmp/agent-device-android-smoke-home steps: - name: Checkout uses: useblacksmith/checkout@2b9fe87d796feea153b455ec2f3125b471a7b0e7 # v1.8.2 @@ -91,6 +93,7 @@ jobs: ANDROID_SERIAL="$(adb devices | awk 'NR > 1 && $2 == "device" { print $1; exit }')" test -n "$ANDROID_SERIAL" pnpm gate build + node --experimental-strip-types scripts/install-workspace-replay-plugins.ts pnpm clean:daemon AGENT_DEVICE_ANDROID_E2E=1 AGENT_DEVICE_ANDROID_E2E_TIER=smoke AGENT_DEVICE_ANDROID_SERIAL="$ANDROID_SERIAL" AGENT_DEVICE_FIXTURE_APP_PATH="${{ steps.fixture-app.outputs.apk-path }}" AGENT_DEVICE_FIXTURE_APP_ID="${{ steps.fixture-app.outputs.app-id }}" node --experimental-strip-types scripts/node-test-tmpdir.ts --test test/integration/smoke-android-emulator.test.ts node --experimental-strip-types src/bin.ts test test/integration/replays/android/emulator/01-settings.ad --retries 2 --report-junit test/artifacts/replays-android-smoke.junit.xml diff --git a/.github/workflows/apple.yml b/.github/workflows/apple.yml index df10a2ef56..c59ec2cded 100644 --- a/.github/workflows/apple.yml +++ b/.github/workflows/apple.yml @@ -36,6 +36,7 @@ jobs: runs-on: blacksmith-6vcpu-macos-26 timeout-minutes: 90 env: + AGENT_DEVICE_HOME: ${{ github.workspace }}/.tmp/agent-device-apple-smoke-home BASE_SHA: ${{ github.event.pull_request.base.sha }} IOS_STATE_DIR: ${{ github.workspace }}/.tmp/ios-agent-device-state MACOS_STATE_DIR: ${{ github.workspace }}/.tmp/macos-agent-device-state @@ -83,6 +84,8 @@ jobs: uses: ./.github/actions/run-gate with: gate: build + - if: matrix.platform == 'ios' && steps.build.outcome == 'success' + run: node --experimental-strip-types scripts/install-workspace-replay-plugins.ts - name: iOS smoke tests id: ios uses: ./.github/actions/smoke-ios-run diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 809d22b3ed..6fd1cb7a56 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,12 +14,13 @@ on: push: branches: - main + - '0.22' permissions: contents: read -# Release and nightly publishing require green CI on the exact main commit, so a -# main push never cancels or replaces another commit's run. +# Release and nightly publishing require green CI on the exact source commit, so a +# push never cancels or replaces another commit's run. concurrency: group: >- ci-${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }} @@ -101,11 +102,28 @@ jobs: uses: ./.github/actions/run-gate with: { gate: build } + - name: Verify the core and standalone Maestro packages + uses: ./.github/actions/run-gate + with: { gate: package } + - name: Verify emitted chunk ownership uses: ./.github/actions/run-gate with: { gate: bundle-owner-files } - # The build runs on the default toolchain Node and the package is verified on the minimum + - name: Setup Node.js 22.13 + uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0 + with: + node-version: '22.13.0' + + - name: Verify the repository build on Node.js 22.13 + uses: ./.github/actions/run-gate + with: { gate: build } + + - name: Verify development packaging on Node.js 22.13 + uses: ./.github/actions/run-gate + with: { gate: package } + + # The build runs on the development floor and the package is verified on the minimum # supported Node, so this job covers what a user on `engines.node` floor actually installs. - name: Setup Node.js 22.12 uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0 @@ -117,7 +135,7 @@ jobs: # # Runs the script directly rather than through `pnpm check:package`: the repo's pinned pnpm # requires Node >= 22.13 and refuses to start on the 22.12 floor this job exists to cover. The - # gate itself only needs `node` and `npm`, so it is the package.json script minus the launcher. + # root-package probe only needs `node` and `npm`. The full package gate runs above. - name: Verify the published package on Node.js 22.12 run: node --experimental-strip-types scripts/check-package.ts diff --git a/.github/workflows/conformance-differential.yml b/.github/workflows/conformance-differential.yml index fd04fe7c74..8d3bbec263 100644 --- a/.github/workflows/conformance-differential.yml +++ b/.github/workflows/conformance-differential.yml @@ -64,6 +64,14 @@ jobs: - name: Setup toolchain uses: ./.github/actions/setup-node-pnpm + - name: Build and install the workspace Maestro plugin + run: | + pnpm --filter @agent-device/maestro build + pnpm --filter @agent-device/replay build + export AGENT_DEVICE_HOME="$RUNNER_TEMP/agent-device-maestro-home" + node --experimental-strip-types scripts/install-workspace-replay-plugins.ts + echo "AGENT_DEVICE_HOME=$AGENT_DEVICE_HOME" >> "$GITHUB_ENV" + - name: Restore and build iOS XCTest runner uses: ./.github/actions/setup-apple-runner-build with: diff --git a/README.md b/README.md index 17c0c4a8f7..58f076319e 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Works with Claude Code, Codex, Cursor, Windsurf, Cline, Goose, and any agent tha Install the CLI and check setup. It requires Node.js 22.12 or newer; web automation requires Node.js 24 or newer. See [Installation](https://agent-device.dev/docs/installation) for target requirements. ```bash -npm install -g agent-device@latest +npm install -g agent-device@nightly-0.22 agent-device doctor agent-device help workflow ``` @@ -101,8 +101,9 @@ See [AI agent setup](https://agent-device.dev/docs/agent-setup) for per-client s `createAgentDeviceClient()` gives Node.js code typed access to the same commands, as model tools in your own agent or from orchestration code: ```ts -import { createAgentDeviceClient } from 'agent-device'; +import { createAgentDeviceClient, ensureDaemon, isAgentDeviceError } from 'agent-device'; +await ensureDaemon(); const client = createAgentDeviceClient({ session: 'qa-run' }); try { await client.apps.open({ app: 'com.apple.Preferences', platform: 'ios' }); @@ -110,7 +111,11 @@ try { const button = snapshot.nodes.find((node) => node.role === 'button'); if (button) await client.interactions.press({ ref: button.ref }); } finally { - await client.sessions.close(); + await client.sessions.close().catch((error) => { + if (isAgentDeviceError(error) && error.code === 'SESSION_NOT_FOUND') return; + console.error('Session cleanup failed:', error); + process.exitCode = 1; + }); } ``` @@ -151,7 +156,7 @@ The same session and evidence model works at every step: the agent explores the | --- | --- | --- | | Local | Trying commands and debugging apps on simulators, emulators, physical devices, macOS, and Linux. | Follow the Quick Start. | | CI/CD | Automated pull request and merge validation with replay scripts and captured artifacts. | Try the [EAS workflow template](https://github.com/callstackincubator/eas-agent-device/blob/main/.eas/workflows/agent-qa-mobile.yml). | -| Cloud / remote | Linux runners, managed devices, and remote jobs. | Set up a [remote proxy](https://agent-device.dev/docs/remote-proxy), connect a [device cloud](https://agent-device.dev/docs/device-clouds) (BrowserStack, AWS Device Farm, TestMu AI, Limrun), or [contact Callstack](mailto:hello@callstack.com) for team QA. | +| Cloud / remote | Linux runners, managed devices, and remote jobs. | Set up a [remote proxy](https://agent-device.dev/docs/remote-proxy), connect a [device cloud](https://agent-device.dev/docs/device-clouds) (BrowserStack, AWS Device Farm, and TestMu AI through `agent-device plugins add`, or Limrun), or [contact Callstack](mailto:hello@callstack.com) for team QA. | ## How it works diff --git a/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/ActionabilityPolicyTests.swift b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/ActionabilityPolicyTests.swift index 47d018dd96..70cae68246 100644 --- a/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/ActionabilityPolicyTests.swift +++ b/apple/snapshot-presentation/Tests/AgentDeviceSnapshotPresentationTests/ActionabilityPolicyTests.swift @@ -5,7 +5,7 @@ import Foundation import XCTest /// Replays `contracts/fixtures/snapshot-actionability-policy.json` against the Swift predicate. The -/// TypeScript twin replays the same rows in `scripts/ios-snapshot-differential.test.ts`. +/// TypeScript twin replays the same rows in `packages/capture-kit/test/ios-snapshot-differential.test.ts`. final class ActionabilityPolicyTests: XCTestCase { private struct Table: Decodable { let cases: [PolicyCase] diff --git a/contracts/fixtures/snapshot-actionability-policy.json b/contracts/fixtures/snapshot-actionability-policy.json index 69306fe038..4323d7dc46 100644 --- a/contracts/fixtures/snapshot-actionability-policy.json +++ b/contracts/fixtures/snapshot-actionability-policy.json @@ -1,5 +1,5 @@ { - "description": "Golden vector table for the shared `hittable` predicate (#1933, #2891), for input shapes the fixed 320x240 fold fixture in ios-snapshot-engine-conformance.json cannot reach. RULE: a node is actionable when it is enabled, its own rect passes the box guard below, and its center falls inside the viewport box, half-open on the right and bottom edges. BOX GUARD: a box is usable when all four components are finite, both extents (x+width, y+height) are finite, the size is positive, and it is not CGRect.infinite — whose components and extents are all finite, so only identity refuses it. SnapshotGeometry.isPositiveFinite (Swift) and isPositiveFiniteRect in packages/kernel/src/rect.ts are the twins that enforce exactly this, one per language. Implementations of the predicate: SnapshotGeometry.isGeometricallyActionable (Swift, replayed by ActionabilityPolicyTests) and isGeometricallyActionable in packages/kernel/src/rect.ts (replayed by scripts/ios-snapshot-differential.test.ts). The viewport is the declared fact `reported`, `derived`, or `missing` (IosViewportEvidence); a box the guard refuses never becomes `reported`. `hittable: null` is the absent bit: with no viewport box, containment is undecided, while a disabled or degenerate node is still a declared `false` because that half of the rule needs no box. Every row declares `swift` and `typescript` and at least one must run it; a row one side skips carries `asymmetry`.", + "description": "Golden vector table for the shared `hittable` predicate (#1933, #2891), for input shapes the fixed 320x240 fold fixture in ios-snapshot-engine-conformance.json cannot reach. RULE: a node is actionable when it is enabled, its own rect passes the box guard below, and its center falls inside the viewport box, half-open on the right and bottom edges. BOX GUARD: a box is usable when all four components are finite, both extents (x+width, y+height) are finite, the size is positive, and it is not CGRect.infinite — whose components and extents are all finite, so only identity refuses it. SnapshotGeometry.isPositiveFinite (Swift) and isPositiveFiniteRect in packages/kernel/src/rect.ts are the twins that enforce exactly this, one per language. Implementations of the predicate: SnapshotGeometry.isGeometricallyActionable (Swift, replayed by ActionabilityPolicyTests) and isGeometricallyActionable in packages/kernel/src/rect.ts (replayed by packages/capture-kit/test/ios-snapshot-differential.test.ts). The viewport is the declared fact `reported`, `derived`, or `missing` (IosViewportEvidence); a box the guard refuses never becomes `reported`. `hittable: null` is the absent bit: with no viewport box, containment is undecided, while a disabled or degenerate node is still a declared `false` because that half of the rule needs no box. Every row declares `swift` and `typescript` and at least one must run it; a row one side skips carries `asymmetry`.", "cases": [ { "name": "a center strictly inside the reported box is actionable", diff --git a/docs/adr/0012-interactive-replay.md b/docs/adr/0012-interactive-replay.md index b7beb86c10..18b0affcad 100644 --- a/docs/adr/0012-interactive-replay.md +++ b/docs/adr/0012-interactive-replay.md @@ -18,6 +18,10 @@ At acceptance, replay had three gaps: ## Decision +### Optional execution boundary (0.22) + +Native `.ad` execution and test-suite scheduling require the first-party `@agent-device/replay` version 2 plugin. Maestro suites additionally require `@agent-device/maestro`. The managed registry owns loading, backend claims, failure isolation and disposal. Core keeps session and repair-transaction authority, device dispatch, selectors, refs, recording, cancellation and cleanup. The existing explicit step and suite ports cross the package boundary without a second session store or request context. Shared `.ad` data and divergence wire functions remain in core. This extraction changes installation requirements, not the identity, divergence, resume or repair decisions below. A missing plugin is refused before device binding. A stale daemon requires an explicit host restart, never automatic installation or session termination. + ### 1. Retire `--update` healing as an actor; repurpose its candidate machinery as ranked suggestions `--update`/`-u` does not rewrite `.ad` files. diff --git a/docs/adr/0015-direct-maestro-engine.md b/docs/adr/0015-direct-maestro-engine.md index 1fd2ad4c02..55ebd036ab 100644 --- a/docs/adr/0015-direct-maestro-engine.md +++ b/docs/adr/0015-direct-maestro-engine.md @@ -6,6 +6,7 @@ Accepted ## Rules at a glance +- Load the optional `@agent-device/maestro` engine through the managed version 2 replay-backend plugin contract. Keep help declarations in core. Keep session authority, request cancellation, sensitive-value registration, and device dispatch with the host. - Parse supported Maestro YAML into a source-preserving typed program. Execute it directly through a narrow compatibility runtime port. - Do not lower the program through `SessionAction`, private command names, positional JSON, or a recursive replay dispatcher. - One explicit execution context owns variables and the current observation generation. diff --git a/docs/adr/0016-active-session-script-publication.md b/docs/adr/0016-active-session-script-publication.md index 9e448469ad..10f213302e 100644 --- a/docs/adr/0016-active-session-script-publication.md +++ b/docs/adr/0016-active-session-script-publication.md @@ -10,6 +10,8 @@ Remote delivery (#4511 amendment) is owned by `packages/daemon/src/core/session- ## Rules at a glance +Ordinary recording and publication remain core capabilities without the replay plugin. Native `.ad` replay/test execution or replay repair requires `@agent-device/replay` on the daemon host. + This section is a normative summary. [Decision](#decision) contains the binding contracts and refusal cases. diff --git a/docs/adr/0033-collocation-decision-table.md b/docs/adr/0033-collocation-decision-table.md index 5f017920fd..31045e6943 100644 --- a/docs/adr/0033-collocation-decision-table.md +++ b/docs/adr/0033-collocation-decision-table.md @@ -54,7 +54,7 @@ Their ownership rationale follows. | daemon-contracts | Shared daemon/client contracts belong below both sides. Keep the owner-scoped claim reconciler there because daemon open/startup and daemonless stale release both run it. Runtime recovery may reside there only when both sides run it and root composition supplies only the gateway. Capture-kit cannot depend back on daemon-contracts because that creates a project-reference cycle. | | root composition | Keep the daemon bundle entry at the root. Retain the Apple runner-owner, daemon lifecycle, device boot, and resource-cleanup platform-runtime seams for this batch: relocation requires coordinated changes to R13 and R76. Keep Limrun runtime composition at the root because moving it into the provider package would pull root composition across the boundary. | | command-runtime | The command binding and runtime factory moved into command-runtime. The binding retains the three-family daemon load shape. | -| SDK | Keep the published Limrun facade at the public boundary, because a published facade cannot reside in a private workspace package. Keep its public session-type refinement there: moving it into the provider package requires renamed or dual-exported internal types. | +| SDK | The published Limrun facade was removed with the `agent-device/limrun` export, so the provider package owns the runtime and its session types. | Daemon credential composition remains at the root. The daemon credential type belongs in daemon-contracts, and credential fingerprinting belongs with plugin manifest lookup. diff --git a/docs/adr/0034-provider-plugin-registry.md b/docs/adr/0034-provider-plugin-registry.md index 6c3d1bc277..3544f0c3fc 100644 --- a/docs/adr/0034-provider-plugin-registry.md +++ b/docs/adr/0034-provider-plugin-registry.md @@ -7,10 +7,12 @@ Status: accepted. Umbrella #3747; contract and registry #3755. - One contract. A provider plugin is a factory that returns `{ apiVersion: 2, provider, credentials, connection?, setup(host) }`. `setup` returns `{ runtime, platformModule, dispose? }` or `{ webDriver, dispose? }`. A `{ webDriver }` result stays a data descriptor the host interprets. +- A replay plugin uses the same version 2 factory with `kind: 'replay-backend'`, `backend`, and `setup(host)`. Setup returns `{ replayBackend: { create(host) }, dispose? }` for a format backend. Provider and backend ids have separate claim sets in this registry. A replay plugin registers no provider runtime. - One registry. Composition selects built-in, store, or embedder sources. Built-in providers use the same shape as an installed plugin, and one function validates what every factory returns. -- Plugins import only types from agent-device. The type-only contract is `agent-device/plugins`; - there is no runtime helper, and the contract does not depend on a plugin's module URL. +- Plugins import only types from `agent-device/plugins`. The factory contract has no runtime + helper and does not depend on a plugin's module URL. The entry also exports the host-side manager + operation `addPluginArtifact(path, { env, cwd })`, which shares the CLI's managed store. - The first registration of a provider id claims it, even when that registration fails. Later ones are recorded as failed. `cloud` and `proxy` are routing identities no plugin can claim. - A plugin that fails to enumerate, load, validate or set up is recorded and skipped. The daemon @@ -22,11 +24,13 @@ Status: accepted. Umbrella #3747; contract and registry #3755. - The registry receives candidates. Composition chooses the sources. - `daemon.json` has one reader. Its states are `absent`, `unreadable`, and `invalid`. A missing or stale record reads as a stopped daemon; an unreadable or invalid one never does. +- Keep replay setup engine-free. Load the engine only when its backend is selected. The runtime's registry memoizes creation and owns disposal after requests drain. Client-side source collection and export close their scoped registry. +- Engine-free vetted declarations supply help and missing-plugin installation commands. They do not establish whether an engine is installed or working. Unknown names produce no inferred package. +- Missing replay execution returns `plugin-not-installed` before device binding. A selected package retains its load, validation, compatibility or setup reason. A package added after daemon startup returns `daemon-plugin-set-stale`; the caller finishes sessions and restarts that host. An embedded registry never consults the store for recovery. - The plugin set is fixed for a daemon's lifetime. A plugin change takes effect on the next daemon. -- v1 plugins (`agentDevicePlugin.apiVersion: 1`) without a `./agent-device` export are dispatched by - their manifest before any code runs and load through an adapter until 0.22 removes them (#3759). - A package that keeps the manifest and also exports `./agent-device` loads as v2; hosts without - v2 still read the manifest. +- A store package is discovered through its package targets: the `./agent-device` export, else the + root export, which is `main` for a package that declares no `exports`. Nothing is read from + `package.json` to declare a provider, connection capabilities, or credential variables (#3759). ## Context @@ -44,25 +48,25 @@ had to fake the store to load a plugin from its own dependencies (#3747). fingerprint. - **A package exports its entry as `./agent-device`.** The host resolves it with import conditions and falls back to the package root only when the subpath is absent. A subpath whose - import or setup throws never falls back. A v2 package needs no manifest. + import or setup throws never falls back. A plugin package needs no manifest. - **The registry owns identity, not the retired lists.** Duplicate ids and bundled ids are one question answered by claim order. Credential variables, per-backend narrowing and connect - capabilities are read from the registry's plugins, not from manifests. A v1 manifest still - supplies them for a v1 plugin. + capabilities are read from the registry's plugins, not from manifests. - **Failure is data.** A failed plugin is an inventory entry, not an exception. Behavior keys on `error.reason`, never on the message. - **A client reads a daemon's inventory from `daemon.json`.** The client credential fingerprint - takes variable names from it and falls back to v1 manifests. A v2 plugin declares its connect - capabilities in code, so a client loads the store, without setting up a runtime, before it reads - them. + takes variable names from it. A v2 plugin declares its connect capabilities in code, so a client + loads the store, without setting up a runtime, before it reads them. + +Decision history (2026-11-17): the public artifact manager API in [#4615](https://github.com/callstack/agent-device/pull/4615) narrows the entry's type-only restriction to plugin factories. Hosts can use the shared manager without adding a runtime helper dependency to plugins. ## Daemon ownership -Clients retain managed and attach lifecycles. Managed clients may start a daemon; attach clients cannot start or replace one. An embedder calls `startAgentDevice({ stateDir, plugins?, host? })` from `agent-device` to own a runtime in its process. The main entry loads the runtime when called. The returned client and serializable `clientConfig` identify that exact instance. Attaching checks normal version and code compatibility before checking the instance pin. `close()` in the host process is the only way to shut an embedded runtime down, and returns its `ShutdownReport`. `daemon stop` refuses live embedded ownership with `daemon-owner-embedded` and live unrecognized ownership with `daemon-owner-unrecognized`, without a request or signal. The embedded-ownership refusal names the host PID and directs the caller to close the runtime there. Stop may retire an embedded or unrecognized registration when its recorded host lifetime has provably exited. The CLI cannot replace a live embedded runtime. Registration and its lock remain held while requests or platform owners are unfinished. +Clients attach to an existing daemon and cannot start or replace one. Call `ensureDaemon()` to start or replace a detached daemon explicitly. An embedder calls `startAgentDevice({ stateDir, plugins?, host? })` from `agent-device` to own a runtime in its process. The main entry loads the runtime when called. The returned client and serializable `clientConfig` identify that exact instance. Attaching checks normal version and code compatibility before checking the instance pin. `close()` in the host process is the only way to shut an embedded runtime down, and returns its `ShutdownReport`. `daemon stop` refuses live embedded ownership with `daemon-owner-embedded` and live unrecognized ownership with `daemon-owner-unrecognized`, without a request or signal. The embedded-ownership refusal names the host PID and directs the caller to close the runtime there. Stop may retire an embedded or unrecognized registration when its recorded host lifetime has provably exited. The CLI cannot replace a live embedded runtime. Registration and its lock remain held while requests or platform owners are unfinished. The embedder supplies plugin objects directly. They follow the built-ins through the same registry validation; this runtime does not read the plugin store. Plugin failures remain inventory data. Logging adapters, a separate package entry, and disposal protocols are not required to own a daemon: the library exposes the client, its attach configuration, and `close()`. -Decision history: owner-only close replaces external embedded shutdown so the CLI cannot end work its host owns; a proven host exit permits registration retirement. The former explicit-start target is dropped; the client lifecycle continues to choose startup behavior. The main-entry API replaces the proposed host subpath and optional host controls, keeping ownership and attachment on the existing runtime and client paths (#3757). +Decision history: owner-only close replaces external embedded shutdown so the CLI cannot end work its host owns; a proven host exit permits registration retirement. The former client-managed startup path was removed in 0.22; explicit ensuring keeps daemon replacement separate from attachment (#3759). The main-entry API replaces the proposed host subpath and optional host controls, keeping ownership and attachment on the existing runtime and client paths (#3757). ## Alternatives refused diff --git a/docs/agents/code-ownership.md b/docs/agents/code-ownership.md index e9b65ea372..f446a0cbb5 100644 --- a/docs/agents/code-ownership.md +++ b/docs/agents/code-ownership.md @@ -6,6 +6,7 @@ Before you edit a module with many callers, run `pnpm depgraph affected `. | Question | Owner | | --- | --- | +| Shared bundler policy | `packages/build-config/src/index.ts` | | Command names | `packages/command-registry/src/catalog.ts` | | Command descriptors | `packages/command-registry/src/`: `registry.ts`, `descriptor-*.ts`, `descriptors/` | | Daemon request-policy predicates | `packages/daemon/src/core/daemon-command-registry.ts` | @@ -15,11 +16,10 @@ Before you edit a module with many callers, run `pnpm depgraph affected `. | Output formatters | `packages/command-output/src/` | | Help and progress | `src/commands/` | | Input fields and audiences | `packages/command-surface/src/common-input-fields.ts`, `packages/command-surface/src/input-audience.ts` | -| Released SDK default hosts | `src/sdk/host.ts` | +| Released SDK command-host scopes | `src/sdk/host.ts` | | Apple runner host port and binding | `packages/apple-runner/src/host.ts`, `packages/platform-apple/src/core/runner-client.ts` | -For SDK entries `android-adb`, `artifacts`, `limrun`, `metro`, and `remote-config`, use `captureSdkHost` for defaults. -For command-host readers, use `withSdkHost`. +For SDK command-host readers, pass the supplied host to `withSdkHost`. Keep provider callbacks on their supplied host. Request cancellation and progress belong in `@agent-device/host-kit/request`. Per-call abort guards belong beside transports in `packages/daemon-client/src/daemon-client-transport.ts`. diff --git a/examples/sdk/client-session.ts b/examples/sdk/client-session.ts index d1a3f9261a..c8924b9f66 100644 --- a/examples/sdk/client-session.ts +++ b/examples/sdk/client-session.ts @@ -3,7 +3,7 @@ * a node, then close the session — with typed error handling via the * exported error helpers. * - * Demonstrates: `createAgentDeviceClient`, `AppError`, `isAgentDeviceError`, + * Demonstrates: `ensureDaemon`, `createAgentDeviceClient`, `AppError`, `isAgentDeviceError`, * and `normalizeAgentDeviceError` from the `agent-device` root export. * * Prerequisites: an `agent-device` daemon target (a booted iOS simulator). @@ -15,6 +15,7 @@ import { AppError, createAgentDeviceClient, + ensureDaemon, isAgentDeviceError, normalizeAgentDeviceError, } from 'agent-device'; @@ -47,6 +48,13 @@ function reportAgentDeviceError(error: unknown): void { } async function main(): Promise { + try { + await ensureDaemon(); + } catch (error) { + if (!isAgentDeviceError(error)) throw error; + reportAgentDeviceError(error); + return; + } const client = createAgentDeviceClient({ session: 'sdk-example', lockPolicy: 'reject', @@ -72,7 +80,13 @@ async function main(): Promise { if (!isAgentDeviceError(error)) throw error; reportAgentDeviceError(error); } finally { - await client.sessions.close(); + try { + await client.sessions.close(); + } catch (error) { + if (!isAgentDeviceError(error) || error.code !== 'SESSION_NOT_FOUND') { + reportAgentDeviceError(error); + } + } } } diff --git a/examples/sdk/contracts-result.ts b/examples/sdk/contracts-result.ts index ef3d28594a..7590ed379b 100644 --- a/examples/sdk/contracts-result.ts +++ b/examples/sdk/contracts-result.ts @@ -6,7 +6,8 @@ * Demonstrates: `centerOfRect` from `agent-device/contracts`, consumed * against the `CaptureSnapshotResult` shape returned by the root client. * - * Prerequisites: an `agent-device` daemon target with an app already open. + * Prerequisites: call `ensureDaemon()` to start the daemon, then open an app + * in the `sdk-example` session. * This file typechecks without one. * * Run: node --experimental-strip-types examples/sdk/contracts-result.ts diff --git a/examples/sdk/tsconfig.json b/examples/sdk/tsconfig.json index a65fe38443..31a3f137ea 100644 --- a/examples/sdk/tsconfig.json +++ b/examples/sdk/tsconfig.json @@ -13,7 +13,6 @@ "agent-device/remote-config": ["../../src/sdk/remote-config.ts"], "agent-device/install-source": ["../../src/sdk/install-source.ts"], "agent-device/android-adb": ["../../src/sdk/android-adb.ts"], - "agent-device/limrun": ["../../src/sdk/limrun.ts"], "agent-device/plugins": ["../../src/sdk/plugins.ts"], "agent-device/plugins/webdriver": ["../../src/sdk/plugin-webdriver.ts"], "agent-device/contracts": ["../../src/sdk/contracts.ts"], @@ -37,6 +36,7 @@ "include": [".", "../../src/**/*", "../../packages/command-registry/src/global.d.ts"], "exclude": ["../../src/**/*.test.ts", "../../src/**/__tests__/**", "../../src/**/*.fixtures.ts"], "references": [ + { "path": "../../packages/build-config" }, { "path": "../../packages/ad-replay" }, { "path": "../../packages/ad-script" }, { "path": "../../packages/apple-runner" }, @@ -64,6 +64,8 @@ { "path": "../../packages/provider-limrun" }, { "path": "../../packages/provider-revyl" }, { "path": "../../packages/provider-testmu" }, + { "path": "../../packages/provider-aws-device-farm" }, + { "path": "../../packages/provider-browserstack" }, { "path": "../../packages/provider-webos" }, { "path": "../../packages/provider-tizen" }, { "path": "../../packages/provider-webdriver" }, @@ -71,6 +73,7 @@ { "path": "../../packages/proxy" }, { "path": "../../packages/react-native" }, { "path": "../../packages/remote" }, + { "path": "../../packages/replay" }, { "path": "../../packages/replay-port" }, { "path": "../../packages/replay-test" }, { "path": "../../packages/selectors" }, diff --git a/package.json b/package.json index 4b4977c97e..508af7b560 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "agent-device", - "version": "0.21.39-dev", + "version": "0.22.0-dev", "description": "Open source device layer for AI coding agents: a CLI, MCP server, and typed Node.js API to control mobile, web, TV, and desktop apps on devices and simulators, locally or in the cloud.", "mcpName": "io.github.callstack/agent-device", "license": "MIT", @@ -50,10 +50,6 @@ "types": "./dist/src/android-adb.d.ts", "import": "./dist/src/android-adb.js" }, - "./limrun": { - "types": "./dist/src/limrun.d.ts", - "import": "./dist/src/limrun.js" - }, "./contracts": { "types": "./dist/src/contracts.d.ts", "import": "./dist/src/contracts.js" @@ -86,7 +82,7 @@ "agent-device": "bin/agent-device.mjs" }, "scripts": { - "build": "tsdown", + "build": "pnpm --filter @agent-device/maestro build && pnpm --filter @agent-device/replay build && tsdown", "clean:daemon": "node --experimental-strip-types scripts/clean-daemon.ts", "daemon:state-dir": "node --experimental-strip-types scripts/print-daemon-state-dir.ts", "explain:command": "node --experimental-strip-types scripts/explain-command.ts", @@ -128,7 +124,7 @@ "maestro:conformance": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/maestro-conformance/format-generated-json.test.mjs scripts/maestro-conformance/verify-cli-version.test.mjs packages/maestro/test/conformance/verify.test.ts packages/maestro/test/conformance/differential/engine-process.test.ts packages/maestro/test/conformance/differential/report-output.test.ts packages/maestro/test/conformance/differential/run.test.ts packages/maestro/test/conformance/differential/invariants.test.ts", "maestro:conformance:regenerate": "node --experimental-strip-types scripts/maestro-conformance/regenerate.mjs", "maestro:conformance:differential": "node --experimental-strip-types packages/maestro/test/conformance/differential/run.ts", - "test:ios-snapshot-differential": "node --experimental-strip-types scripts/swift-toolchain-tmpdir.ts swift test --package-path apple/snapshot-presentation && node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/ios-snapshot-differential.test.ts", + "test:ios-snapshot-differential": "node --experimental-strip-types scripts/swift-toolchain-tmpdir.ts swift test --package-path apple/snapshot-presentation && node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/capture-kit/test/ios-snapshot-differential.test.ts", "size": "node scripts/size-report.mjs", "perf": "node --experimental-strip-types scripts/perf/run.ts", "perf:compare": "node --experimental-strip-types scripts/perf/compare-cli.ts", @@ -165,7 +161,7 @@ "depgraph:test": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/depgraph/model.test.ts scripts/depgraph/entries.test.ts scripts/depgraph/import-graph.test.ts scripts/depgraph/affected.test.ts scripts/depgraph/structure-summary.test.ts tools/depgraph-view/*.test.mjs", "check:production-exports": "fallow dead-code --config fallow-production-exports.json --production --unused-exports --fail-on-issues", "check:bundle-owner-files": "node --experimental-strip-types scripts/check-bundle-owner-files.ts", - "check:package": "node --experimental-strip-types scripts/check-package.ts", + "check:package": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs packages/maestro/test/package-smoke.mjs packages/replay/test/package-smoke.mjs && node --experimental-strip-types scripts/check-package.ts", "check:command-docs": "vitest run --project unit-core test/repo-guards/command-doc-coverage.test.ts", "check:adr-citations": "vitest run --project unit-core test/repo-guards/adr-citations.test.ts", "check:capabilities-matrix": "vitest run --project unit-core test/repo-guards/capability-matrix.test.ts", @@ -301,7 +297,6 @@ } }, "devDependencies": { - "@agent-device/ad-replay": "workspace:*", "@agent-device/ad-script": "workspace:*", "@agent-device/apple-runner": "workspace:*", "@agent-device/capture-kit": "workspace:*", @@ -317,7 +312,6 @@ "@agent-device/device-selection": "workspace:*", "@agent-device/host-kit": "workspace:*", "@agent-device/kernel": "workspace:*", - "@agent-device/maestro": "workspace:*", "@agent-device/platform-android": "workspace:*", "@agent-device/platform-apple": "workspace:*", "@agent-device/platform-harmonyos": "workspace:*", @@ -332,7 +326,6 @@ "@agent-device/react-native": "workspace:*", "@agent-device/remote": "workspace:*", "@agent-device/replay-port": "workspace:*", - "@agent-device/replay-test": "workspace:*", "@agent-device/selectors": "workspace:*", "@agent-device/session-journal": "workspace:*", "@agent-device/test-kit": "workspace:*", @@ -373,11 +366,14 @@ "tsdown": "^0.22.14", "typescript": "^7.0.2", "undici": "7.30.1", + "unrun": "0.3.1", "vite": "^8.3.5", "vitest": "5.0.4", "yaml": "^2.9.0", "yauzl": "^3.4.0", "@agent-device/testmu": "workspace:*", + "@agent-device/aws-device-farm": "workspace:*", + "@agent-device/browserstack": "workspace:*", "@agent-device/revyl": "workspace:*", "@agent-device/webos": "workspace:*", "@agent-device/tizen": "workspace:*" diff --git a/packages/ad-replay/package.json b/packages/ad-replay/package.json index 48ff8c1fb6..2b3bcdadb5 100644 --- a/packages/ad-replay/package.json +++ b/packages/ad-replay/package.json @@ -15,10 +15,6 @@ ".": { "types": "./src/index.ts", "default": "./src/index.ts" - }, - "./divergence": { - "types": "./src/replay-divergence.ts", - "default": "./src/replay-divergence.ts" } } } diff --git a/packages/ad-replay/src/index.ts b/packages/ad-replay/src/index.ts index 2f533795f9..0e7bdf31a6 100644 --- a/packages/ad-replay/src/index.ts +++ b/packages/ad-replay/src/index.ts @@ -1,104 +1,3 @@ -/** - * The `ad-replay` package façade (#1478 P5 stage D — narrowed; report-action/ - * suggestion-ranking/vars/identity-vocabulary further narrowed by the P5 - * review pass; plan-digest/resume and `classifyTargetBindingMatch` further - * narrowed by the #1555 review pass, "complete the binding façade instead of - * documenting deviations"; the target-verification policy functions further - * narrowed by the #1555 review's R3 pass, "target verification must happen - * INSIDE the engine"). `scripts/layering/package-boundaries.test.ts` asserts - * this file's exact export list — see "the real tree parses, declares, and - * passes R11" — so a stray export (including one this parser cannot - * enumerate a name for, like `export *`) fails that gate, not just a comment - * mismatch. - * - * The binding design (issue comment 5156017698) is two value entrypoints — - * `inspectAdReplay` + `runAdReplay` — plus the neutral vocabulary their - * signatures are built from, exported by name (#1555 structural-quality - * review, "typed façade replaces the zero-type rule"): a package a root - * consumer must integrate against through hand-derived `Parameters<...>`/ - * `ReturnType<...>` gymnastics in a SINGLE allowed root module - * (`src/daemon/ad-replay-facade-types.ts`, since deleted) is a shim tax, not - * an isolation win — every derived name still had to be re-exported from that - * one file for every other root module to use, and every daemon-side type - * that shadowed an engine type by hand (`TargetVerificationEntry`, - * `TargetClassificationOutcome`, `TargetBindingFailureEvidence`, - * `ReplayVerifiedTargetGuard`, plus a `toDaemonEvidence` copy translator - * between mutable and readonly array shapes) was a duplicate definition that - * could silently drift from the type it mirrored. `packages/maestro`'s - * façade (`facade-execution.ts`/`facade-runtime-port.ts`/…) is the precedent: - * a package boundary is enforced by an exact, gate-pinned export LIST, not by - * exporting zero types. The gate below now pins values AND types together, - * so a stray widening — a type accidentally exported, or one accidentally - * dropped that a root file was still deriving by hand — fails loudly either - * way. - * - * `inspectAdReplay` is the read-only `.ad` manifest reader — the plan-digest - * hash (`plan-digest.ts`, `computeReplayPlanDigest`) and the `--from`/ - * `--plan-digest` resume-point math (`resume.ts`, `resolveReplayEntryIndex`) - * are internal-only; the manifest carries the digest as `planDigest` and the - * resume math as a `resolveEntryIndex` closure instead, so - * `session-replay-runtime-plan.ts`'s `prepareReplayPlan` and - * `request-router-repair-expired.test.ts` read them off the manifest rather - * than importing the underlying functions. `AdReplayManifest` is its return - * type and `AdReplayVarSources` is `runAdReplay`'s `${VAR}` scope-input - * shape — both named here since `session-replay-runtime-plan.ts` threads them - * by name across its own helper signatures. - * - * `runAdReplay` is the `.ad` step loop; `AdReplayStepRuntime` is the runtime - * capability bag the daemon adapter - * (`session-replay-runtime-engine-adapter.ts`) implements to thread it, - * including selector resolution through the direct `@agent-device/selectors` - * package engine. Selector parsing and matching stay behind that package's - * string-only façade; no adapter value crosses this boundary. - * - * `./internal/target-verification.ts`'s four policy functions - * (`planPostResolutionTargetVerification`, `planPreDispatchTargetVerification`, - * `deriveReplayTargetGuardMismatchEvidence`, `deriveWaitLandmarkMismatchEvidence`) - * stay engine-private — they are called only from `./internal/verify-dispatch.ts`'s - * `verifyAndDispatchStep`, never the daemon — but the TYPED evidence shapes - * they consume (`AdReplayGuardMismatchEvidence`, `AdReplayLandmarkMismatchEvidence`) - * and the classification/guard/binding-evidence/verification-routing shapes - * `verifyAndDispatchStep` exchanges with the daemon's `AdReplayStepRuntime` - * implementation (`AdReplayVerificationEntry`, `AdReplayTargetClassification`, - * `AdReplayTargetObservation`, `AdReplayTargetBindingEvidence`, `AdReplayDispatchGuard`, - * `AdReplayDispatchOutcome`) ARE named here: the - * daemon builds/reads real values of these shapes directly now (routing in - * `session-replay-target-verification.ts`, wire-narrowing in - * `session-replay-runtime-engine-adapter.ts`) rather than re-declaring a - * structurally-identical twin per module. - * - * `${VAR}` scope/planning: the engine builds the `${VAR}` scope (via - * `@agent-device/ad-script`) from the request's `varSources` and resolves - * each action exactly once per step, handing the daemon's `dispatchStep`/ - * `beginTargetVerification` capabilities the RESOLVED action — never a raw - * action plus a scope for the daemon to interpolate itself (#1555 review P1, - * "move variable semantics/planning behind the replay entrypoint"). The - * `${VAR}`-scrub values a divergence report redacts (`AdReplayScrubValue`) - * are threaded the same direction, as an explicit argument on each - * build*Failure/handleActionFailure capability, computed ONCE per run from - * the engine's own live scope — never recomputed daemon-side from a second - * scope object, and never re-collected per call site. - */ - +/** Native inspection and execution implement the shared contracts-owned ports. */ export { inspectAdReplay } from './internal/inspect.ts'; -export type { AdReplayManifest } from './internal/inspect.ts'; - export { runAdReplay } from './internal/step-loop.ts'; - -export type { - AdReplayDispatchGuard, - AdReplayDispatchOutcome, - AdReplayScrubValue, - AdReplayStepFailure, - AdReplayStepRuntime, - AdReplayTargetBindingEvidence, - AdReplayTargetClassification, - AdReplayTargetObservation, - AdReplayVarSources, - AdReplayVerificationEntry, -} from './internal/runtime-port-types.ts'; - -export type { - AdReplayGuardMismatchEvidence, - AdReplayLandmarkMismatchEvidence, -} from './internal/target-verification.ts'; diff --git a/packages/ad-replay/src/internal/__tests__/resume.test.ts b/packages/ad-replay/src/internal/__tests__/resume.test.ts index 9d6a682785..ffc8341bbd 100644 --- a/packages/ad-replay/src/internal/__tests__/resume.test.ts +++ b/packages/ad-replay/src/internal/__tests__/resume.test.ts @@ -1,10 +1,10 @@ +import type { + AdReplayEntryIndexParams, + PendingRecordAndHeal, +} from '@agent-device/contracts/ad-replay-execution'; import assert from 'node:assert/strict'; import { test } from 'vitest'; -import { - resolveReplayEntryIndex, - type AdReplayEntryIndexParams, - type PendingRecordAndHeal, -} from '../resume.ts'; +import { resolveReplayEntryIndex } from '../resume.ts'; /** * #1555 structural-quality review ("package-local tests... resume.ts and diff --git a/packages/ad-replay/src/internal/__tests__/step-loop.test.ts b/packages/ad-replay/src/internal/__tests__/step-loop.test.ts index aa5d1e394c..6e004f0b64 100644 --- a/packages/ad-replay/src/internal/__tests__/step-loop.test.ts +++ b/packages/ad-replay/src/internal/__tests__/step-loop.test.ts @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import { runAdReplay } from '../step-loop.ts'; -import type { AdReplayStepRuntime } from '../runtime-port-types.ts'; +import type { AdReplayStepRuntime } from '@agent-device/contracts/ad-replay-execution'; import type { SessionAction } from '@agent-device/contracts/session'; import type { TargetAnnotationV1 } from '@agent-device/contracts/replay'; diff --git a/packages/ad-replay/src/internal/__tests__/target-verification.test.ts b/packages/ad-replay/src/internal/__tests__/target-verification.test.ts index 9a4775b63f..344fda8a90 100644 --- a/packages/ad-replay/src/internal/__tests__/target-verification.test.ts +++ b/packages/ad-replay/src/internal/__tests__/target-verification.test.ts @@ -1,3 +1,7 @@ +import type { + AdReplayGuardMismatchEvidence, + AdReplayLandmarkMismatchEvidence, +} from '@agent-device/contracts/ad-replay-execution'; import assert from 'node:assert/strict'; import { test } from 'vitest'; import type { TargetAnnotationV1 } from '@agent-device/contracts/replay'; @@ -6,8 +10,6 @@ import { deriveWaitLandmarkMismatchEvidence, planPostResolutionTargetVerification, planPreDispatchTargetVerification, - type AdReplayGuardMismatchEvidence, - type AdReplayLandmarkMismatchEvidence, } from '../target-verification.ts'; /** diff --git a/packages/ad-replay/src/internal/inspect.ts b/packages/ad-replay/src/internal/inspect.ts index f86baa7685..2bd38ddabc 100644 --- a/packages/ad-replay/src/internal/inspect.ts +++ b/packages/ad-replay/src/internal/inspect.ts @@ -1,13 +1,11 @@ import { AppError } from '@agent-device/kernel/errors'; -import type { SessionAction } from '@agent-device/contracts/session'; import { parseReplayScriptDetailed, readReplayScriptMetadata, resolveDeclaredScriptPlatform, - type ReplayScriptMetadata, } from '@agent-device/ad-script'; import { computeReplayPlanDigest } from './plan-digest.ts'; -import { resolveReplayEntryIndex, type PendingRecordAndHeal } from './resume.ts'; +import { resolveReplayEntryIndex } from './resume.ts'; /** * #1478 P5 stage C2b: the read-only `.ad` inspection façade. Moved out of @@ -29,23 +27,10 @@ import { resolveReplayEntryIndex, type PendingRecordAndHeal } from './resume.ts' * new top-level façade export — they are plain data/a closure hanging off * the manifest object `inspectAdReplay` already returns. */ -export type AdReplayManifest = Readonly<{ - actions: SessionAction[]; - actionLines: number[]; - metadata: ReplayScriptMetadata; - /** SHA-256 digest of the canonical plan (`digestFlags` binds the same platform/target the replay invokes with). */ - planDigest: string; - /** The `--from`/`--plan-digest` resume-point math, closed over this manifest's own `actions`/`planDigest`. */ - resolveEntryIndex(params: { - from: number | undefined; - digest: string | undefined; - pendingRecordAndHeal: PendingRecordAndHeal | undefined; - sessionActionsLength: number; - }): { ok: true; value: number } | { ok: false; message: string }; -}>; - -/** The request-level `--platform`/`--target` override the plan digest binds (raw flags, before any metadata merge). */ -export type AdReplayDigestFlags = Readonly<{ platform?: string; target?: string }>; +import type { + AdReplayManifest, + AdReplayDigestFlags, +} from '@agent-device/contracts/ad-replay-execution'; /** * Parses one `.ad` script's TEXT and returns its actions/line table, header diff --git a/packages/ad-replay/src/internal/resume.ts b/packages/ad-replay/src/internal/resume.ts index 9e2dcb7789..dfff7f96db 100644 --- a/packages/ad-replay/src/internal/resume.ts +++ b/packages/ad-replay/src/internal/resume.ts @@ -17,27 +17,11 @@ * notes for why that reordering was judged out of scope here. */ -/** - * The session-side state that gates an EMPTY-TAIL resume (`--from actionCount - * + 1`). Stamped for `record-and-heal`, and per #1262 also for - * `caution`/`manual`'s record-and-heal-shaped alternate repair (their own - * unshifted `resume.from` is unaffected by this watermark). - */ -export type PendingRecordAndHeal = Readonly<{ - expectedFrom: number; - actionsCountAtDivergence: number; -}>; - -export type AdReplayEntryIndexParams = Readonly<{ - from: number | undefined; - digest: string | undefined; - pendingRecordAndHeal: PendingRecordAndHeal | undefined; - sessionActionsLength: number; -}>; - -export type AdReplayEntryIndexResult = - | Readonly<{ readonly ok: true; readonly value: number }> - | Readonly<{ readonly ok: false; readonly message: string }>; +import type { + PendingRecordAndHeal, + AdReplayEntryIndexParams, + AdReplayEntryIndexResult, +} from '@agent-device/contracts/ad-replay-execution'; /** * Resolves `--from`/`--plan-digest` into a 0-based loop entry index before diff --git a/packages/ad-replay/src/internal/step-loop.ts b/packages/ad-replay/src/internal/step-loop.ts index 619a20583c..6820039e5d 100644 --- a/packages/ad-replay/src/internal/step-loop.ts +++ b/packages/ad-replay/src/internal/step-loop.ts @@ -11,7 +11,7 @@ import type { AdReplayRunOutcome, AdReplayRunRequest, AdReplayStepRuntime, -} from './runtime-port-types.ts'; +} from '@agent-device/contracts/ad-replay-execution'; /** * #1478 P5 stage C2b: the `.ad` step-loop ENGINE policy, split out of @@ -19,7 +19,7 @@ import type { * `resolveReplayStepResponse` / `buildReplayActionFailure`. Everything that * touches a real device, a snapshot, `SessionStore`, or the P4b repair * coordinator is daemon authority and stays behind the narrow - * `AdReplayStepRuntime` capabilities (`./runtime-port-types.ts`) — this + * `AdReplayStepRuntime` capabilities (`@agent-device/contracts/ad-replay-execution`) — this * module only decides which action to run next, when to skip one, and when * to stop. * @@ -28,7 +28,7 @@ import type { * vocabulary and the verify-then-dispatch orchestrator — both extracted out, * following `packages/maestro`'s own three-way split * (`runtime-port-types.ts` for the vocabulary, its engine files for the - * orchestration logic). `./runtime-port-types.ts` now owns every + * orchestration logic). `@agent-device/contracts/ad-replay-execution` now owns every * `AdReplayStepRuntime`-adjacent type; `./verify-dispatch.ts` owns * `verifyAndDispatchStep` and its two dispatch helpers. This file is left * with exactly the loop (`runAdReplay`) and the terminal-close/executable- diff --git a/packages/ad-replay/src/internal/target-verification.ts b/packages/ad-replay/src/internal/target-verification.ts index 0d3264e4fa..e431c573ce 100644 --- a/packages/ad-replay/src/internal/target-verification.ts +++ b/packages/ad-replay/src/internal/target-verification.ts @@ -44,7 +44,7 @@ * not engine policy. This module now only reads already-typed values. */ -import type { TargetAncestryEntry, TargetAnnotationV1 } from '@agent-device/contracts/replay'; +import type { TargetAnnotationV1 } from '@agent-device/contracts/replay'; import { firstAncestryMismatch, identityFieldMismatches, @@ -52,37 +52,11 @@ import { } from '@agent-device/ad-script'; import { readSelectorExpression } from '@agent-device/selectors'; -/** - * The verified/observed member's structural position within its capture - * (document order + sibling) — moved here (from `./step-loop.ts`, which - * still uses it for `AdReplayVerifiedTargetGuard`) so both this module's - * typed evidence shapes and the step loop can reference ONE definition - * without a cycle: this module has no dependency on `./step-loop.ts`, but - * `./step-loop.ts` already depends on this one. - */ -export type AdReplayTargetStructuralDenotation = Readonly<{ - documentOrder: number; - sibling: number; -}>; - -/** - * The guard-mismatch refusal's typed evidence, already narrowed by the - * daemon adapter from the wire response's `details` bag — the engine never - * sees the untyped bag itself. - */ -export type AdReplayGuardMismatchEvidence = Readonly<{ - targetRole?: 'source' | 'destination'; - observed: LocalIdentity | undefined; - expectedStructural: AdReplayTargetStructuralDenotation | undefined; - observedStructural: AdReplayTargetStructuralDenotation | undefined; -}>; - -/** The wait-landmark-mismatch refusal's typed evidence — same translate-before-crossing rule. */ -export type AdReplayLandmarkMismatchEvidence = Readonly<{ - matchCount: number | undefined; - observed: LocalIdentity | undefined; - observedAncestry: readonly TargetAncestryEntry[]; -}>; +import type { + AdReplayTargetStructuralDenotation, + AdReplayGuardMismatchEvidence, + AdReplayLandmarkMismatchEvidence, +} from '@agent-device/contracts/ad-replay-execution'; // --------------------------------------------------------------------------- // Pre-capture verification gating (`verifyReplayActionTarget`'s two branches). diff --git a/packages/ad-replay/src/internal/verify-dispatch.ts b/packages/ad-replay/src/internal/verify-dispatch.ts index e82303bc5d..5c9b017ec7 100644 --- a/packages/ad-replay/src/internal/verify-dispatch.ts +++ b/packages/ad-replay/src/internal/verify-dispatch.ts @@ -13,7 +13,7 @@ import type { AdReplayStepRuntime, AdReplayTargetObservation, AdReplayVerifiedTargetGuard, -} from './runtime-port-types.ts'; +} from '@agent-device/contracts/ad-replay-execution'; /** * #1478 P5 stage C2b (split out of `step-loop.ts` by the #1555 structural- diff --git a/packages/ad-script/src/index.ts b/packages/ad-script/src/index.ts index da5ccaedb8..c153e6e48c 100644 --- a/packages/ad-script/src/index.ts +++ b/packages/ad-script/src/index.ts @@ -1,5 +1,5 @@ export { parseReplayScriptDetailed, readReplayScriptMetadata } from './internal/script.ts'; -export type { ReplayScriptMetadata } from './internal/script.ts'; +export type { ReplayScriptMetadata } from '@agent-device/contracts/replay-script-data'; export { resolveDeclaredScriptPlatform } from './internal/open-script.ts'; @@ -61,6 +61,7 @@ export { } from './internal/vars.ts'; export { + getReplayPluginInstallation, isMaestroYamlPath, isReplayBackendId, maestroBackendRequiredMessage, diff --git a/packages/ad-script/src/internal/format.ts b/packages/ad-script/src/internal/format.ts index 96c5c23a6f..119871eff7 100644 --- a/packages/ad-script/src/internal/format.ts +++ b/packages/ad-script/src/internal/format.ts @@ -2,6 +2,26 @@ import path from 'node:path'; export type ReplayFormat = 'ad' | 'maestro'; +const REPLAY_PLUGIN_INSTALLATIONS = { + ad: { + package: '@agent-device/replay', + summary: 'Native .ad replay and test suites', + installationHint: + 'Install on the daemon host for native .ad replay and all test suites. Core clients can read and send native .ad sources without this plugin.', + }, + maestro: { + package: '@agent-device/maestro', + summary: 'Supported Maestro YAML commands, grammar, and runtime boundaries', + installationHint: + 'Install on the client for source collection/export and on the daemon host for Maestro execution.', + }, +} as const; + +/** Vetted installation facts for the replay format vocabulary, without loading an engine. */ +export function getReplayPluginInstallation(id: ReplayFormat) { + return { id, ...REPLAY_PLUGIN_INSTALLATIONS[id] }; +} + export function isMaestroYamlPath(sourcePath: string): boolean { const extension = path.extname(sourcePath).toLowerCase(); return extension === '.yaml' || extension === '.yml'; diff --git a/packages/ad-script/src/internal/replay-input.ts b/packages/ad-script/src/internal/replay-input.ts index 5de1fe4b8a..3b9cefcaea 100644 --- a/packages/ad-script/src/internal/replay-input.ts +++ b/packages/ad-script/src/internal/replay-input.ts @@ -1,3 +1,4 @@ +import type { ReplayScriptMetadata } from '@agent-device/contracts/replay-script-data'; import type { CommandFlags } from '@agent-device/contracts/command'; import { AppError } from '@agent-device/kernel/errors'; import { isReplayBackendId, unsupportedReplayBackendMessage } from './format.ts'; @@ -5,7 +6,6 @@ import { parseReplayScriptDetailed, readReplayScriptMetadata, type ParsedReplayScript, - type ReplayScriptMetadata, } from './script.ts'; export type ParsedReplayInput = ParsedReplayScript & { diff --git a/packages/ad-script/src/internal/script.ts b/packages/ad-script/src/internal/script.ts index 758f3c2a22..191b4439ce 100644 --- a/packages/ad-script/src/internal/script.ts +++ b/packages/ad-script/src/internal/script.ts @@ -1,3 +1,4 @@ +import type { ReplayScriptMetadata } from '@agent-device/contracts/replay-script-data'; import { AppError } from '@agent-device/kernel/errors'; import { recordingQualityInputToExportQuality } from '@agent-device/contracts/recording'; import { @@ -45,14 +46,6 @@ export const REPLAY_METADATA_PLATFORMS = new Set( ); const REPLAY_METADATA_TARGETS = new Set(['mobile', 'tv', 'desktop']); -export type ReplayScriptMetadata = { - platform?: ReplayScriptPlatform; - target?: DeviceTarget; - timeoutMs?: number; - retries?: number; - env?: Record; -}; - export type ParsedReplayScript = { actions: SessionAction[]; actionLines: number[]; diff --git a/packages/ad-script/src/internal/vars.ts b/packages/ad-script/src/internal/vars.ts index f02aaab980..e557d37f73 100644 --- a/packages/ad-script/src/internal/vars.ts +++ b/packages/ad-script/src/internal/vars.ts @@ -13,12 +13,7 @@ export type ReplayVarScope = { expandedBuiltinNames?: Set; }; -export type ReplayVarSources = { - builtins?: Record; - fileEnv?: Record; - shellEnv?: Record; - cliEnv?: Record; -}; +import type { ReplayVarSources } from '@agent-device/contracts/replay-script-data'; const SHELL_PREFIX = 'AD_VAR_'; diff --git a/packages/apple-runner/src/__tests__/runner-artifact-manifest.test.ts b/packages/apple-runner/src/__tests__/runner-artifact-manifest.test.ts index 8391782542..c53f46b09b 100644 --- a/packages/apple-runner/src/__tests__/runner-artifact-manifest.test.ts +++ b/packages/apple-runner/src/__tests__/runner-artifact-manifest.test.ts @@ -122,7 +122,7 @@ test('a certified symlink that starts escaping the cache root breaks reuse', asy runnerAppPath, ]); - fs.rmSync(linkPath); + fs.unlinkSync(linkPath); fs.symlinkSync(path.join(outside, 'evil'), linkPath); const state = mismatchOf( @@ -143,7 +143,7 @@ test('a symlink that changes target but stays inside the cache is a target chang runnerAppPath, ]); - fs.rmSync(linkPath); + fs.unlinkSync(linkPath); fs.symlinkSync('FrameworksMoved', linkPath); const state = mismatchOf( @@ -205,7 +205,7 @@ test('a symlinked product root that stays inside the cache is certified', async [path.join('staged', 'Runner-Runner.app', 'Runner')], ); - fs.rmSync(linkedProduct); + fs.unlinkSync(linkedProduct); const swapped = path.join(derived, 'staged', 'Other.app'); fs.mkdirSync(swapped, { recursive: true }); fs.writeFileSync(path.join(swapped, 'Runner'), Buffer.alloc(4096, 9), { mode: 0o755 }); diff --git a/packages/apple-runner/src/__tests__/runner-toolchain-identity.test.ts b/packages/apple-runner/src/__tests__/runner-toolchain-identity.test.ts index 889ba6abf6..3364e3c645 100644 --- a/packages/apple-runner/src/__tests__/runner-toolchain-identity.test.ts +++ b/packages/apple-runner/src/__tests__/runner-toolchain-identity.test.ts @@ -118,7 +118,7 @@ test('a bundle swapped behind a stable selection path is read from the bundle no }); assert.deepEqual(readFingerprint(), FINGERPRINT_A); - fs.rmSync(stable); + fs.unlinkSync(stable); fs.symlinkSync(path.resolve(xcodeB, '../..'), stable); assert.deepEqual(readFingerprint(), FINGERPRINT_B); }); diff --git a/packages/build-config/package.json b/packages/build-config/package.json new file mode 100644 index 0000000000..5cae8eb212 --- /dev/null +++ b/packages/build-config/package.json @@ -0,0 +1,16 @@ +{ + "name": "@agent-device/build-config", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "Shared repository bundler configuration.", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + } + }, + "devDependencies": { + "rolldown": "1.2.5" + } +} diff --git a/packages/build-config/src/index.ts b/packages/build-config/src/index.ts new file mode 100644 index 0000000000..38ca7c8926 --- /dev/null +++ b/packages/build-config/src/index.ts @@ -0,0 +1,21 @@ +import type { InputOptions } from 'rolldown'; + +export const strictBundlerInputOptions: InputOptions = { + onLog(level, log, handler) { + if (log.code === 'UNRESOLVED_IMPORT') throw new Error(log.message); + handler(level, log); + }, +}; + +export const providerPluginBuildConfig = { + entry: { 'agent-device': 'src/index.ts' }, + outDir: 'dist', + format: 'esm' as const, + platform: 'node' as const, + target: 'es2022' as const, + minify: true, + dts: false, + hash: false, + deps: { alwaysBundle: [/^@agent-device\//] }, + inputOptions: strictBundlerInputOptions, +}; diff --git a/packages/build-config/tsconfig.json b/packages/build-config/tsconfig.json new file mode 100644 index 0000000000..77de1f500d --- /dev/null +++ b/packages/build-config/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "composite": true, + "noEmit": false, + "emitDeclarationOnly": true, + "declaration": true, + "declarationDir": "./dist-types", + "rootDir": "./src", + "tsBuildInfoFile": "./dist-types/index.tsbuildinfo" + }, + "include": ["src"], + "references": [] +} diff --git a/scripts/ios-snapshot-differential.test.ts b/packages/capture-kit/test/ios-snapshot-differential.test.ts similarity index 96% rename from scripts/ios-snapshot-differential.test.ts rename to packages/capture-kit/test/ios-snapshot-differential.test.ts index 7d490384c6..e839904852 100644 --- a/scripts/ios-snapshot-differential.test.ts +++ b/packages/capture-kit/test/ios-snapshot-differential.test.ts @@ -8,20 +8,20 @@ import type { Rect } from '@agent-device/kernel/snapshot'; import { compareDifferentialCases, SWIFT_RUN_TIMEOUT_MS, -} from '../packages/capture-kit/src/ios-snapshot-engine/conformance-harness.ts'; +} from '../src/ios-snapshot-engine/conformance-harness.ts'; import { swiftToolchainAvailable, writeDifferentialFailureArtifact, -} from '../packages/capture-kit/src/ios-snapshot-engine/conformance-harness.fixtures.ts'; -import { differentialBatchArbitrary } from '../packages/capture-kit/src/ios-snapshot-engine/conformance-generator.ts'; -import { readIosSnapshotEngineFixture } from '../packages/capture-kit/src/ios-snapshot-engine/conformance-fixture.ts'; +} from '../src/ios-snapshot-engine/conformance-harness.fixtures.ts'; +import { differentialBatchArbitrary } from '../src/ios-snapshot-engine/conformance-generator.ts'; +import { readIosSnapshotEngineFixture } from '../src/ios-snapshot-engine/conformance-fixture.ts'; import { hostRowNodes, runnerNodes, safariWebViewNodes, threadNodes, viewport as capturedViewport, -} from '../packages/capture-kit/src/ios-snapshot-engine/runner-presentation-fixtures.ts'; +} from '../src/ios-snapshot-engine/runner-presentation-fixtures.ts'; type DifferentialCase = Parameters[0][number]; @@ -269,6 +269,8 @@ type ActionabilityVector = Readonly<{ const ACTIONABILITY_POLICY_PATH = path.resolve( import.meta.dirname, '..', + '..', + '..', 'contracts', 'fixtures', 'snapshot-actionability-policy.json', diff --git a/packages/client/src/__tests__/index-daemon-lifecycle.test.ts b/packages/client/src/__tests__/index-daemon-lifecycle.test.ts index 9709f0c837..339fd03b4c 100644 --- a/packages/client/src/__tests__/index-daemon-lifecycle.test.ts +++ b/packages/client/src/__tests__/index-daemon-lifecycle.test.ts @@ -1,47 +1,57 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; -import type { - AgentDeviceDaemonTransport, - AgentDeviceDaemonTransportContext, - DaemonLifecycle, -} from '@agent-device/contracts/client'; +import type { AgentDeviceDaemonTransport } from '@agent-device/contracts/client'; import { createAgentDeviceClient } from '../index.ts'; -// `daemonLifecycle` is a client choice that only the transport can act on, so the client's job is to -// hand it over exactly and to refuse a value it does not know. +// A client always attaches, so `daemonLifecycle` is no longer a choice the transport acts on. The +// client's job is to accept `'attach'` (the only value, and the default) and to refuse any value that +// would mean managing a daemon, naming the explicit owners instead. function recordingTransport() { - const contexts: Array = []; + const seen: Array> = []; const transport: AgentDeviceDaemonTransport = async (_request, context) => { - contexts.push(context); + seen.push({ ...(context ?? {}) }); return { ok: true, data: { devices: [] } }; }; - return { contexts, transport }; + return { seen, transport }; } -test('the configured daemon lifecycle reaches the transport', async () => { - const { contexts, transport } = recordingTransport(); +test('a client sends no daemon-management knob to its transport', async () => { + const { seen, transport } = recordingTransport(); const attached = createAgentDeviceClient({ daemonLifecycle: 'attach' }, { transport }); const plain = createAgentDeviceClient({}, { transport }); - const managed = createAgentDeviceClient({ daemonLifecycle: 'managed' }, { transport }); - await attached.devices.list(); - await managed.devices.list(); await plain.devices.list(); + // `'attach'` is what every request does, so it is not a per-request option either: the transport + // gets the caller's cancellation and pin, and nothing about who owns the daemon. assert.deepEqual( - contexts.map((context) => context?.daemonLifecycle), - ['attach', 'managed', undefined], + seen.map((context) => 'daemonLifecycle' in context), + [false, false], + ); +}); + +test('the removed managed lifecycle is refused where the config is read', () => { + const { transport } = recordingTransport(); + + assert.throws( + () => createAgentDeviceClient({ daemonLifecycle: 'managed' as never }, { transport }), + (error: { code?: string; details?: { daemonLifecycle?: unknown; hint?: unknown } }) => { + assert.equal(error.code, 'INVALID_ARGS'); + assert.equal(error.details?.daemonLifecycle, 'managed'); + assert.match(String(error.details?.hint), /ensureDaemon\(\{ stateDir \}\)/); + assert.match(String(error.details?.hint), /startAgentDevice\(\{ stateDir \}\)/); + return true; + }, ); }); -test('an unknown daemon lifecycle is refused instead of becoming managed', () => { +test('an unknown daemon lifecycle is refused instead of attaching blindly', () => { const { transport } = recordingTransport(); - const mistyped = 'Attach' as DaemonLifecycle; assert.throws( - () => createAgentDeviceClient({ daemonLifecycle: mistyped }, { transport }), + () => createAgentDeviceClient({ daemonLifecycle: 'Attach' as never }, { transport }), (error: { code?: string }) => error.code === 'INVALID_ARGS', ); }); diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index b00e671665..1da8a8fa9f 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -1,3 +1,4 @@ +import type { ReplayBackendResolver } from '@agent-device/contracts/replay-backend'; import type { CommandFlags, InternalRequestOptions } from '@agent-device/contracts/command'; import { readPostGestureOutcome } from '@agent-device/contracts/snapshot'; import { @@ -82,6 +83,8 @@ export function createAgentDeviceClient( config: AgentDeviceClientConfig = {}, deps: { transport?: AgentDeviceDaemonTransport; + /** The embedded runtime registry, shared by source preparation and execution. */ + resolveReplayBackend?: ReplayBackendResolver; host?: HostEnvironment; /** The operator-configured device selector enforced on every request. */ devicePin?: DevicePin; @@ -163,7 +166,6 @@ export function createAgentDeviceClient( await transport(request, { authToken: merged.daemonAuthToken, signal: merged.signal, - daemonLifecycle: merged.daemonLifecycle, ...(daemonBinding ? { daemonBinding } : {}), }), ); @@ -183,7 +185,7 @@ export function createAgentDeviceClient( command: DaemonCommandName, options: InternalRequestOptions = {}, ): Promise => { - const request = await prepareDaemonCommandRequest(command, options, host); + const request = await prepareDaemonCommandRequest(command, options, host, deps); return (await execute( request.command, request.positionals, @@ -629,10 +631,17 @@ function optionalSnapshotResponseFields( } function readDaemonLifecycle(value: unknown): DaemonLifecycle | undefined { - if (value === undefined || value === 'attach' || value === 'managed') return value; - throw new AppError('INVALID_ARGS', "daemonLifecycle must be 'attach' or 'managed'.", { - daemonLifecycle: value, - }); + if (value === undefined || value === 'attach') return value; + throw new AppError( + 'INVALID_ARGS', + value === 'managed' + ? "daemonLifecycle must be 'attach'. The 'managed' lifecycle was removed in 0.22." + : "daemonLifecycle must be 'attach'.", + { + daemonLifecycle: value, + hint: "Drop daemonLifecycle, or set it to 'attach'. To start or replace a detached daemon, call ensureDaemon({ stateDir }). To own one in this process, call startAgentDevice({ stateDir }) from 'agent-device'.", + }, + ); } /** diff --git a/packages/command-output/package.json b/packages/command-output/package.json index 96333df650..caff572370 100644 --- a/packages/command-output/package.json +++ b/packages/command-output/package.json @@ -6,7 +6,6 @@ "type": "module", "description": "Shared CLI and MCP command presentation: per-family output formatters, warning routing, color, human error lines, and result serialization. Takes terminal facts as explicit input and performs no process I/O.", "dependencies": { - "@agent-device/ad-replay": "workspace:*", "@agent-device/capture-kit": "workspace:*", "@agent-device/command-registry": "workspace:*", "@agent-device/command-surface": "workspace:*", diff --git a/packages/command-output/src/output/error.ts b/packages/command-output/src/output/error.ts index 4bd16bf785..11a1882120 100644 --- a/packages/command-output/src/output/error.ts +++ b/packages/command-output/src/output/error.ts @@ -9,7 +9,7 @@ import { } from '@agent-device/kernel/errors'; import { readResponseWarnings } from '@agent-device/kernel/success-text'; import type { OutputReader } from '../output-common.ts'; -import { formatReplayDivergenceReport } from '@agent-device/ad-replay/divergence'; +import { formatReplayDivergenceReport } from '@agent-device/contracts/replay-divergence-data'; import { collapseWarningText } from '../output-common.ts'; /** diff --git a/packages/command-output/tsconfig.json b/packages/command-output/tsconfig.json index fa6bf31bf0..36cd559426 100644 --- a/packages/command-output/tsconfig.json +++ b/packages/command-output/tsconfig.json @@ -13,7 +13,6 @@ // declared beside them; a package program that reaches registry.ts needs the declaration too. "include": ["src", "../command-registry/src/global.d.ts"], "references": [ - { "path": "../ad-replay" }, { "path": "../capture-kit" }, { "path": "../command-registry" }, { "path": "../command-surface" }, diff --git a/packages/command-registry/src/batch.ts b/packages/command-registry/src/batch.ts index ca1973fa89..3c6ff43547 100644 --- a/packages/command-registry/src/batch.ts +++ b/packages/command-registry/src/batch.ts @@ -6,7 +6,6 @@ import { type DaemonResponse, type ResponseLevel, isNonDefaultResponseLevel, - namesSessionExplicitly, } from '@agent-device/kernel/contracts'; import { AppError, @@ -14,7 +13,7 @@ import { BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, type DaemonError, } from '@agent-device/kernel/errors'; -import { isRecord } from '@agent-device/kernel/record'; +import { isRecord, namesSessionExplicitly } from '@agent-device/kernel/record'; import { DEFAULT_BATCH_MAX_STEPS, assertBatchStepCount, diff --git a/packages/command-registry/src/daemon-command-descriptor.ts b/packages/command-registry/src/daemon-command-descriptor.ts index 316a3804a0..fe6098b126 100644 --- a/packages/command-registry/src/daemon-command-descriptor.ts +++ b/packages/command-registry/src/daemon-command-descriptor.ts @@ -38,6 +38,12 @@ export type DaemonCommandDescriptor = { sessionKind?: SessionCommandKind; refFrameEffect?: DaemonRefFrameEffect; leaseAdmissionExempt?: boolean; + /** + * This command uses neither the lease nor the device of the session it resolves, so only a lease + * it carries itself can make an unnamed request need a session. A command without it acts through + * that session and stays refused. + */ + ignoresSessionLease?: boolean; /** * packages/daemon/docs/remote-device-lease-contracts.md: this command may run under a `macos-app` lease, or on a daemon whose policy requires * one. A command without it is refused there, `leaseAdmissionExempt` or not, so a command diff --git a/packages/command-registry/src/descriptors/session-operations.ts b/packages/command-registry/src/descriptors/session-operations.ts index 341a6e72dc..8cd5513382 100644 --- a/packages/command-registry/src/descriptors/session-operations.ts +++ b/packages/command-registry/src/descriptors/session-operations.ts @@ -336,6 +336,7 @@ export const SESSION_OPERATION_COMMAND_DESCRIPTORS = [ daemon: { route: 'session', refFrameEffect: 'preserve', + ignoresSessionLease: true, ...REQUEST_EXECUTION_EXEMPT, }, timeoutPolicy: DEFAULT_TIMEOUT_POLICY, diff --git a/packages/command-registry/src/flag-definitions-workflow.ts b/packages/command-registry/src/flag-definitions-workflow.ts index 53807458ff..8541ee5d91 100644 --- a/packages/command-registry/src/flag-definitions-workflow.ts +++ b/packages/command-registry/src/flag-definitions-workflow.ts @@ -53,7 +53,7 @@ export const WORKFLOW_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ usageLabel: '--maestro', usageDescription: 'Replay: treat input as a supported Maestro YAML subset; unsupported syntax fails loudly. ' + - 'See agent-device help maestro for commands and boundaries', + 'Requires the @agent-device/maestro plugin, install separately. See agent-device help maestro for commands and boundaries', projectConfig: true, recorded: false, }, diff --git a/packages/command-registry/src/registry.ts b/packages/command-registry/src/registry.ts index 3230fb2d02..8469914597 100644 --- a/packages/command-registry/src/registry.ts +++ b/packages/command-registry/src/registry.ts @@ -174,6 +174,7 @@ export const RAW_COMMAND_DESCRIPTORS = [ daemon: { route: 'lease', refFrameEffect: 'preserve', + ignoresSessionLease: true, ...ADMISSION_AND_LOCK_EXEMPT, }, timeoutPolicy: LEASE_ALLOCATE_TIMEOUT_POLICY, @@ -191,6 +192,7 @@ export const RAW_COMMAND_DESCRIPTORS = [ daemon: { route: 'lease', refFrameEffect: 'preserve', + ignoresSessionLease: true, ...ADMISSION_AND_LOCK_EXEMPT, appLease: 'allowed', }, @@ -209,6 +211,7 @@ export const RAW_COMMAND_DESCRIPTORS = [ daemon: { route: 'lease', refFrameEffect: 'preserve', + ignoresSessionLease: true, ...ADMISSION_AND_LOCK_EXEMPT, appLease: 'allowed', }, @@ -251,6 +254,7 @@ export const RAW_COMMAND_DESCRIPTORS = [ daemon: { route: 'session', refFrameEffect: 'preserve', + ignoresSessionLease: true, sessionKind: 'inventory', ...REQUEST_EXECUTION_EXEMPT, }, @@ -291,6 +295,7 @@ export const RAW_COMMAND_DESCRIPTORS = [ daemon: { route: 'session', refFrameEffect: 'preserve', + ignoresSessionLease: true, sessionKind: 'inventory', lockPolicySelectorOverride: true, ...REQUEST_EXECUTION_EXEMPT, diff --git a/packages/command-runtime/src/commands/capture/runtime/diff-screenshot.test.ts b/packages/command-runtime/src/commands/capture/runtime/diff-screenshot.test.ts index 346df406c9..42ef3accb2 100644 --- a/packages/command-runtime/src/commands/capture/runtime/diff-screenshot.test.ts +++ b/packages/command-runtime/src/commands/capture/runtime/diff-screenshot.test.ts @@ -36,7 +36,7 @@ test('runtime diff screenshot captures live current image and cleans temporary c fs.writeFileSync(outPath, solidPngBuffer(10, 10, { r: 255, g: 255, b: 255 })); return { path: outPath }; }), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy(), }); @@ -74,7 +74,7 @@ test('runtime diff screenshot compares supplied current image without backend ca backend: createScreenshotBackend(() => { throw new Error('capture should not be called'); }), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy(), }); @@ -97,7 +97,7 @@ test('runtime diff screenshot rejects overlay refs with supplied current image', backend: createScreenshotBackend(() => { throw new Error('capture should not be called'); }), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy(), }); @@ -125,7 +125,7 @@ test('runtime diff screenshot enforces the normalized comparison pixel budget', backend: createScreenshotBackend(() => { throw new Error('capture should not be called'); }), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy({ maxImagePixels: 50 }), }); @@ -172,7 +172,7 @@ test('runtime diff screenshot keeps the screen mask on current and overlay captu : {}), }; }), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy(), }); @@ -238,7 +238,7 @@ test('runtime diff refuses a screen mask for saved images before reading or capt backend: createScreenshotBackend(() => { throw new Error('must not capture'); }), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy(), }); diff --git a/packages/command-runtime/src/commands/capture/runtime/presented-surface-carriage.test.ts b/packages/command-runtime/src/commands/capture/runtime/presented-surface-carriage.test.ts index 5f71a5b919..ec1a99eae3 100644 --- a/packages/command-runtime/src/commands/capture/runtime/presented-surface-carriage.test.ts +++ b/packages/command-runtime/src/commands/capture/runtime/presented-surface-carriage.test.ts @@ -61,7 +61,7 @@ async function captureWith(result: BackendSnapshotResult) { }; const device = createAgentDevice({ backend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy(), }); diff --git a/packages/command-runtime/src/commands/capture/runtime/screenshot.test.ts b/packages/command-runtime/src/commands/capture/runtime/screenshot.test.ts index 1ef799ad7d..4933ef4076 100644 --- a/packages/command-runtime/src/commands/capture/runtime/screenshot.test.ts +++ b/packages/command-runtime/src/commands/capture/runtime/screenshot.test.ts @@ -19,7 +19,7 @@ test('runtime screenshot applies scale and forwards the capture rotation', async return { displayRotation: 'landscape-left' }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => undefined, set: () => {} }, policy: localCommandPolicy(), }); @@ -47,7 +47,7 @@ test('runtime screenshot scales the already-cropped backend capture', async () = ); }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => undefined, set: () => {} }, policy: localCommandPolicy(), }); @@ -94,7 +94,7 @@ for (const staged of [false, true]) { fs.writeFileSync(destination, sentinel); const controller = new AbortController(); const cancellation = new Error('caller cancelled after capture'); - const adapter = createLocalArtifactAdapter(); + const adapter = createLocalArtifactAdapter({ cwd: process.cwd() }); let publications = 0; let cleanups = 0; if (staged) { diff --git a/packages/command-runtime/src/commands/capture/runtime/snapshot-app-identity.test.ts b/packages/command-runtime/src/commands/capture/runtime/snapshot-app-identity.test.ts index 7cba3cd10d..61229d0f1d 100644 --- a/packages/command-runtime/src/commands/capture/runtime/snapshot-app-identity.test.ts +++ b/packages/command-runtime/src/commands/capture/runtime/snapshot-app-identity.test.ts @@ -28,7 +28,7 @@ async function snapshotWithForeground( ...sessionApp, }), }, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => undefined, set: (record) => { @@ -94,7 +94,7 @@ test('a repeated unchanged snapshot of a foreign foreground app is acknowledged appBundleId: 'com.android.settings', }), }, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => stored, set: (record) => { diff --git a/packages/command-runtime/src/commands/capture/runtime/snapshot-freshness.test.ts b/packages/command-runtime/src/commands/capture/runtime/snapshot-freshness.test.ts index 193b2ba2b6..5bbf12608f 100644 --- a/packages/command-runtime/src/commands/capture/runtime/snapshot-freshness.test.ts +++ b/packages/command-runtime/src/commands/capture/runtime/snapshot-freshness.test.ts @@ -17,7 +17,7 @@ function snapshotDevice( }; return createAgentDevice({ backend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => session, set: () => {} }, policy: localCommandPolicy(), clock: { now: () => 1_500, sleep: async () => {} }, diff --git a/packages/command-runtime/src/commands/capture/runtime/snapshot.test.ts b/packages/command-runtime/src/commands/capture/runtime/snapshot.test.ts index 0b8b362742..40985fefa4 100644 --- a/packages/command-runtime/src/commands/capture/runtime/snapshot.test.ts +++ b/packages/command-runtime/src/commands/capture/runtime/snapshot.test.ts @@ -29,7 +29,7 @@ test('runtime snapshot captures nodes and updates the session baseline', async ( appName: 'Demo', appBundleId: 'com.example.demo', })), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => undefined, set: (record) => { @@ -108,7 +108,7 @@ test('runtime snapshot recognizes equivalent bounds and still updates its baseli comparisonSafe: true, }), })), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => stored, set: (record) => { @@ -165,7 +165,7 @@ test('runtime snapshot forwards interactive capture options', async () => { }; }, }, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => undefined, set: () => {}, @@ -198,7 +198,7 @@ test('runtime diff snapshot initializes and then compares against session baseli backend: createSnapshotBackend(() => ({ snapshot: makeSnapshotState([{ index: 0, depth: 0, type: 'Window', label: 'After' }]), })), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => session, set: (record) => { @@ -222,7 +222,7 @@ test('runtime diff snapshot initializes baseline when no previous snapshot exist backend: createSnapshotBackend(() => ({ snapshot: makeSnapshotState([{ index: 0, depth: 0, type: 'Window', label: 'Initial' }]), })), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => undefined, set: (record) => { @@ -632,7 +632,7 @@ test('runtime snapshot stale-drop warning uses the runtime clock', async () => { createdAt: 3_500, }), })), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => session, set: (record) => { @@ -678,7 +678,7 @@ test('runtime snapshot stale-drop warning uses backend snapshot timestamps when backend: createSnapshotBackend(() => ({ snapshot: currentSnapshot, })), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => session, set: (record) => { @@ -724,7 +724,7 @@ test('runtime snapshot stale-drop warning falls back to runtime clock on backend backend: createSnapshotBackend(() => ({ snapshot: currentSnapshot, })), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => session, set: (record) => { @@ -759,7 +759,7 @@ function createSnapshotBackend( function createSnapshotOnlyDevice(result: BackendSnapshotResult) { return createAgentDevice({ backend: createSnapshotBackend(() => result), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => undefined, set: () => {}, @@ -961,7 +961,7 @@ test('runtime snapshot carries backend clickability evidence through presentatio let stored: Parameters[0] | undefined; const device = createAgentDevice({ backend: createSnapshotBackend(() => ({ snapshot: state })), - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => undefined, set: (record) => { diff --git a/packages/command-runtime/src/commands/interaction/runtime/__tests__/settle-device-fixtures.ts b/packages/command-runtime/src/commands/interaction/runtime/__tests__/settle-device-fixtures.ts index ea6c7f0962..a3176af3db 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/__tests__/settle-device-fixtures.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/__tests__/settle-device-fixtures.ts @@ -73,7 +73,7 @@ export function createSettleDevice(params: { fill: async () => ({ ok: true }), longPress: async () => ({ ok: true }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([ { name: 'default', diff --git a/packages/command-runtime/src/commands/interaction/runtime/__tests__/test-utils/index.ts b/packages/command-runtime/src/commands/interaction/runtime/__tests__/test-utils/index.ts index b646a045bc..cabbd788ee 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/__tests__/test-utils/index.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/__tests__/test-utils/index.ts @@ -390,7 +390,7 @@ export function createInteractionDevice( ? async (...args) => (await overrides.confirmOffscreenTargetVisible?.(...args)) ?? null : undefined, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([ { name: 'default', snapshot, metadata: overrides.sessionMetadata }, ]), @@ -636,7 +636,7 @@ export function createSelectorDevice( options.captureSnapshot ? await options.captureSnapshot() : { snapshot }, readText: async () => ({ text: options.readText ?? '' }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy(), clock: options.clock ?? { diff --git a/packages/command-runtime/src/commands/interaction/runtime/interactions-find-carried-target.test.ts b/packages/command-runtime/src/commands/interaction/runtime/interactions-find-carried-target.test.ts index 06f1cdbc19..b98d0a76a5 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/interactions-find-carried-target.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/interactions-find-carried-target.test.ts @@ -65,7 +65,7 @@ function createDevice(stored: SnapshotState) { return {}; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot: stored }]), policy: localCommandPolicy(), }); diff --git a/packages/command-runtime/src/commands/interaction/runtime/interactions-preresolved-target.test.ts b/packages/command-runtime/src/commands/interaction/runtime/interactions-preresolved-target.test.ts index b7aaf49ea8..f322f101fa 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/interactions-preresolved-target.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/interactions-preresolved-target.test.ts @@ -64,7 +64,7 @@ function deviceWithSessionTree(snapshot: ReturnType | taps.push(point); }, }, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), }); diff --git a/packages/command-runtime/src/commands/interaction/runtime/interactions.test.ts b/packages/command-runtime/src/commands/interaction/runtime/interactions.test.ts index 6324caeb28..30436585ba 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/interactions.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/interactions.test.ts @@ -310,7 +310,7 @@ test('native ref fast path proceeds untouched when the session has no snapshot', return { ref: target.ref.replace(/^@/, '') }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default' }]), policy: localCommandPolicy(), }); @@ -334,7 +334,7 @@ test('runtime interactions pass runtime signal to backend primitives', async () signal = context.signal; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), policy: localCommandPolicy(), signal: controller.signal, }); @@ -785,7 +785,7 @@ test('coordinate tap with no session snapshot has no warning', async () => { platform: 'ios', tap: async () => ({ ok: true }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default' }]), policy: localCommandPolicy(), }); diff --git a/packages/command-runtime/src/commands/interaction/runtime/moving-target-gate.test.ts b/packages/command-runtime/src/commands/interaction/runtime/moving-target-gate.test.ts index 2532dbe22f..e0068063a8 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/moving-target-gate.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/moving-target-gate.test.ts @@ -113,7 +113,7 @@ function createGuardedDevice(params: { return { ok: true }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([ { name: 'default', @@ -667,7 +667,7 @@ test('a ref from a full-tree frame is re-observed in that presentation, not renu return { ok: true }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([ { name: 'default', diff --git a/packages/command-runtime/src/commands/interaction/runtime/pre-dispatch-admission-hittability.test.ts b/packages/command-runtime/src/commands/interaction/runtime/pre-dispatch-admission-hittability.test.ts index 2348674d51..23db9c6260 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/pre-dispatch-admission-hittability.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/pre-dispatch-admission-hittability.test.ts @@ -46,7 +46,7 @@ function createPressDevice(verdict: TargetHittability | (() => Promise { return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), }); @@ -87,7 +87,7 @@ test('runtime focused predicate requests a full snapshot', async () => { return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), }); @@ -126,7 +126,7 @@ test('runtime focused predicate reads focused Android TV nodes from the full tre return { snapshot: options?.interactiveOnly ? interactiveSnapshot : fullSnapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot: interactiveSnapshot }]), policy: localCommandPolicy(), }); @@ -189,7 +189,7 @@ test('runtime is absent uses one readAny capture without requesting rects', asyn return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), }); @@ -316,7 +316,7 @@ test('runtime is absent fails closed for a sparse capture and preserves the last platform: 'ios', captureSnapshot: async () => ({ snapshot: sparse }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy(), }); diff --git a/packages/command-runtime/src/commands/interaction/runtime/selector-read.test.ts b/packages/command-runtime/src/commands/interaction/runtime/selector-read.test.ts index bbbaa7f275..5524147978 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/selector-read.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/selector-read.test.ts @@ -52,7 +52,7 @@ test('runtime get selector target captures fresh snapshot without a stored sessi }, readText: async () => ({ text: 'Fresh text' }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy(), }); @@ -159,7 +159,7 @@ test('runtime selectors pass runtime signal to backend snapshot capture', async return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), signal: controller.signal, @@ -216,7 +216,7 @@ test('runtime web find text does not pass locator text as browser selector scope return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), }); @@ -266,7 +266,7 @@ test('runtime find wait reports sparse snapshot verdicts on the selector-read ro quality: sparseSnapshot.snapshotQuality, }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy(), clock: { @@ -311,7 +311,7 @@ test('runtime find wait skips hidden-content hint derivation on every poll (#127 return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), clock: { @@ -368,7 +368,7 @@ test('runtime find wait cancels and joins a capture that consumes its full deadl }); }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions, policy: localCommandPolicy(), }); @@ -438,7 +438,7 @@ function waitDeviceWithCaptures(captures: Array<() => ReturnType Error): { throw produceError(); }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default' }]), policy: localCommandPolicy(), clock: createFakeClock(), diff --git a/packages/command-runtime/src/commands/interaction/runtime/selector-wait-cancellation.test.ts b/packages/command-runtime/src/commands/interaction/runtime/selector-wait-cancellation.test.ts index a9322e31d2..3f51f9b77a 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/selector-wait-cancellation.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/selector-wait-cancellation.test.ts @@ -27,7 +27,7 @@ for (const authority of ['runtime', 'command'] as const) { const reason = new Error(`${authority} wait canceled`); const device = createAgentDevice({ backend: { platform: 'ios' } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore(), policy: localCommandPolicy(), clock: { diff --git a/packages/command-runtime/src/commands/interaction/runtime/settle-capture-deadline.test.ts b/packages/command-runtime/src/commands/interaction/runtime/settle-capture-deadline.test.ts index 6e3d3e45b8..4f28d5b6aa 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/settle-capture-deadline.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/settle-capture-deadline.test.ts @@ -37,7 +37,7 @@ test('a stalled settle capture receives its deadline signal and the press still }, tap: async () => ({ ok: true }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot: before }]), policy: localCommandPolicy(), clock: createFakeClock(), diff --git a/packages/command-runtime/src/commands/interaction/runtime/settle-transition-baseline.test.ts b/packages/command-runtime/src/commands/interaction/runtime/settle-transition-baseline.test.ts index e7f09eb27c..30d57af0d4 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/settle-transition-baseline.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/settle-transition-baseline.test.ts @@ -21,7 +21,7 @@ test('settle recovers the session baseline when resolved target evidence is abse snapshot: elapsedMs < 1_200 ? elementTransientRoomSnapshot : elementSettledRoomSnapshot, }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([ { name: 'default', @@ -72,7 +72,7 @@ test('settle uses the authorized ref frame instead of a polluted evidence captur snapshot: elapsedMs < 1_200 ? elementTransientRoomSnapshot : elementSettledRoomSnapshot, }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([ { name: 'default', @@ -132,7 +132,7 @@ async function settlePointTargetAgainstSession(session: { snapshot: elapsedMs < 1_200 ? elementTransientRoomSnapshot : elementSettledRoomSnapshot, }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([session]), policy: localCommandPolicy(), clock: { diff --git a/packages/command-runtime/src/commands/interaction/runtime/settle-view-baseline.test.ts b/packages/command-runtime/src/commands/interaction/runtime/settle-view-baseline.test.ts index 04f5506323..c35bc5002a 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/settle-view-baseline.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/settle-view-baseline.test.ts @@ -92,7 +92,7 @@ function createDevice(params: { return { ok: true }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([ { name: 'default', snapshot: params.frame, refFrameSnapshot: params.frame }, ]), diff --git a/packages/command-runtime/src/commands/interaction/runtime/settle.test.ts b/packages/command-runtime/src/commands/interaction/runtime/settle.test.ts index ae2b6ae302..973604b496 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/settle.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/settle.test.ts @@ -157,7 +157,7 @@ test('press --settle routes its first capture afresh after a private-ax session fill: async () => ({ ok: true }), longPress: async () => ({ ok: true }), } satisfies import('@agent-device/contracts/backend').AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot: established }]), policy: localCommandPolicy(), clock: createFakeClock(), diff --git a/packages/command-runtime/src/commands/interaction/runtime/stable-capture.test.ts b/packages/command-runtime/src/commands/interaction/runtime/stable-capture.test.ts index 81f975f086..21a618c6b8 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/stable-capture.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/stable-capture.test.ts @@ -192,7 +192,7 @@ test('regular captures settle from visible semantics while offscreen rows churn' platform: 'ios', captureSnapshot: async () => ({ snapshot: snapshots[captures++ % snapshots.length]! }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore(), policy: localCommandPolicy(), clock, @@ -601,7 +601,7 @@ function staticSnapshotRuntime(snapshot: SnapshotState) { platform: 'ios', captureSnapshot: async () => ({ snapshot }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), clock: { @@ -687,7 +687,7 @@ function transitionRuntime( }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([ { name: 'default', snapshot: options.sessionSnapshot ?? presented }, ]), diff --git a/packages/command-runtime/src/commands/interaction/runtime/wait-absent.test.ts b/packages/command-runtime/src/commands/interaction/runtime/wait-absent.test.ts index ad09425f6d..9417095da5 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/wait-absent.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/wait-absent.test.ts @@ -51,7 +51,7 @@ function absentDevice( return capture!; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default' }]), policy: localCommandPolicy(), clock: createFakeClock(), @@ -75,7 +75,7 @@ function cancelledAbsentDevice(params: { platform: 'ios', captureSnapshot, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default' }]), policy: localCommandPolicy(), clock, diff --git a/packages/command-runtime/src/commands/interaction/runtime/wait-capture-options.test.ts b/packages/command-runtime/src/commands/interaction/runtime/wait-capture-options.test.ts index 9f744b8a45..3ec0256860 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/wait-capture-options.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/wait-capture-options.test.ts @@ -30,7 +30,7 @@ function pollingDevice(captureOptions: Array }; return createAgentDevice({ backend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: { get: () => undefined, set: () => {} }, policy: localCommandPolicy(), clock: createFakeClock(), diff --git a/packages/command-runtime/src/commands/interaction/runtime/wait-selector.test.ts b/packages/command-runtime/src/commands/interaction/runtime/wait-selector.test.ts index a4dccb81ff..88e5454577 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/wait-selector.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/wait-selector.test.ts @@ -30,7 +30,7 @@ test('runtime focused selector waits against a full snapshot', async () => { return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), }); @@ -95,7 +95,7 @@ function landmarkWaitDevice(captures: Array>) return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot: initial }]), policy: localCommandPolicy(), clock: createFakeClock(), @@ -239,7 +239,7 @@ async function landmarkRefusalAfter( return { snapshot: await finalCapture() }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot: impostor }]), policy: localCommandPolicy(), clock: createFakeClock(100), diff --git a/packages/command-runtime/src/commands/interaction/runtime/wait-stable.test.ts b/packages/command-runtime/src/commands/interaction/runtime/wait-stable.test.ts index 6f7fdcd79c..74a9ce9941 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/wait-stable.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/wait-stable.test.ts @@ -23,7 +23,7 @@ test('runtime wait stable preserves the requested scope, depth and raw view', as return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), clock: createFakeClock(), @@ -59,7 +59,7 @@ test('runtime wait stable settles after two unchanged captures', async () => { return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), clock, @@ -103,7 +103,7 @@ test('runtime wait stable retains a recovered private-ax backend after its first return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), clock: createFakeClock(), @@ -156,7 +156,7 @@ function createStableCaptureDevice(clock: { return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), clock, @@ -276,7 +276,7 @@ test('runtime wait stable hints when it settles on a nearly-empty tree', async ( platform: 'ios', captureSnapshot: async () => ({ snapshot: tinySnapshot }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot: tinySnapshot }]), policy: localCommandPolicy(), clock: createFakeClock(), @@ -312,7 +312,7 @@ test('runtime wait stable omits the loading hint for a normal-sized tree', async platform: 'ios', captureSnapshot: async () => ({ snapshot: normalSnapshot }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot: normalSnapshot }]), policy: localCommandPolicy(), clock: createFakeClock(), @@ -354,7 +354,7 @@ test('runtime wait stable requires quiet captures after instability before settl return { snapshot: changedSnapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), clock, @@ -391,7 +391,7 @@ test('runtime wait stable times out with capture stats when never settling', asy }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default' }]), policy: localCommandPolicy(), clock, @@ -421,7 +421,7 @@ test('runtime wait stable surfaces a capture failure instead of reporting a time throw new Error('AX bridge crashed'); }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default' }]), policy: localCommandPolicy(), clock: createFakeClock(), @@ -465,7 +465,7 @@ test('runtime wait stable times out when a backend capture stalls past the wait ); }), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default' }]), policy: localCommandPolicy(), clock, @@ -502,7 +502,7 @@ test('runtime wait stable uses provided defaults when quietMs/timeoutMs are omit return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), clock, diff --git a/packages/command-runtime/src/commands/interaction/runtime/wait-text.test.ts b/packages/command-runtime/src/commands/interaction/runtime/wait-text.test.ts index 228a62646c..a43625596d 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/wait-text.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/wait-text.test.ts @@ -32,7 +32,7 @@ function textWaitDevice(params: { ...(params.findText ? { findText: params.findText } : {}), readText: params.readText ?? (async () => ({ text: '' })), } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default' }]), policy: localCommandPolicy(), clock: params.clock ?? createFakeClock(), @@ -217,7 +217,7 @@ test('runtime wait passes its polling deadline signal to snapshot capture', asyn platform: 'ios', captureSnapshot: capture, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), }); diff --git a/packages/command-surface/src/batch/projection.ts b/packages/command-surface/src/batch/projection.ts index c258401a27..245f3dd6bc 100644 --- a/packages/command-surface/src/batch/projection.ts +++ b/packages/command-surface/src/batch/projection.ts @@ -14,6 +14,7 @@ import { AppError } from '@agent-device/kernel/errors'; import { request } from '../cli-grammar/common.ts'; import type { AsyncDaemonWriter, + DaemonWriterDependencies, CommandInput, DaemonCommandRequest, } from '../cli-grammar/types.ts'; @@ -26,6 +27,7 @@ type PrepareDaemonCommandRequest = ( input: CommandInput, stepNumber: number, host: HostEnvironment, + deps?: DaemonWriterDependencies, ) => Promise; type PrepareBatchStep = ( @@ -37,11 +39,11 @@ type PrepareBatchStep = ( export function createBatchDaemonWriter( prepareDaemonCommandRequest: PrepareDaemonCommandRequest, ): AsyncDaemonWriter { - return async (input, host) => + return async (input, host, deps) => request(PUBLIC_COMMANDS.batch, [], { ...input, batchSteps: await readBatchDaemonSteps(input.steps, (command, input, stepNumber) => - prepareDaemonCommandRequest(command, input, stepNumber, host), + prepareDaemonCommandRequest(command, input, stepNumber, host, deps), ), batchOnError: input.onError, batchMaxSteps: input.maxSteps, diff --git a/packages/command-surface/src/cli-grammar/types.ts b/packages/command-surface/src/cli-grammar/types.ts index a83175f7f7..48bb9655ad 100644 --- a/packages/command-surface/src/cli-grammar/types.ts +++ b/packages/command-surface/src/cli-grammar/types.ts @@ -1,3 +1,4 @@ +import type { ReplayBackendResolver } from '@agent-device/contracts/replay-backend'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { CliFlags, @@ -91,6 +92,10 @@ export type CliReader = (positionals: string[], flags: CliFlags) => CliInput; /** Builds the daemon request for one command. Most writers are pure projections of their input. */ export type DaemonWriter = (input: CommandInput) => DaemonCommandRequest; +export type DaemonWriterDependencies = Readonly<{ + resolveReplayBackend?: ReplayBackendResolver; +}>; + /** * A writer that has caller-side work to do before the request exists: reading the replay script * files the request carries (#1802), which for a Maestro flow also loads the engine that walks its @@ -100,6 +105,7 @@ export type DaemonWriter = (input: CommandInput) => DaemonCommandRequest; export type AsyncDaemonWriter = ( input: CommandInput, host: HostEnvironment, + deps?: DaemonWriterDependencies, ) => Promise; export type AnyDaemonWriter = DaemonWriter | AsyncDaemonWriter; diff --git a/packages/command-surface/src/index.ts b/packages/command-surface/src/index.ts index c63cad31d6..eda01c647f 100644 --- a/packages/command-surface/src/index.ts +++ b/packages/command-surface/src/index.ts @@ -1,6 +1,11 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { createBatchDaemonWriter } from './batch/projection.ts'; -import type { AnyDaemonWriter, CommandInput, DaemonCommandRequest } from './cli-grammar/types.ts'; +import type { + AnyDaemonWriter, + CommandInput, + DaemonCommandRequest, + DaemonWriterDependencies, +} from './cli-grammar/types.ts'; import { findCommandMetadata } from './command-metadata.ts'; import { refuseRetiredCommonInput } from './common-input-fields.ts'; import { readMetadataCommandFlags } from './command-flags.ts'; @@ -54,6 +59,7 @@ async function prepareBatchDaemonCommandRequest( input: CommandInput, stepNumber: number, host: HostEnvironment, + deps?: DaemonWriterDependencies, ): Promise { const writer = (daemonWriters as Readonly>)[command]; if (!writer) { @@ -69,6 +75,7 @@ async function prepareBatchDaemonCommandRequest( metadata, metadata.readInput(input) as CommandInput, host, + deps, ); } catch (error) { const message = error instanceof Error ? error.message : String(error); @@ -86,6 +93,7 @@ export async function prepareDaemonCommandRequest( command: DaemonCommandName, input: CommandInput, host: HostEnvironment, + deps?: DaemonWriterDependencies, ): Promise { const writer = daemonWriters[command]; if (!writer) { @@ -93,7 +101,7 @@ export async function prepareDaemonCommandRequest( } refuseRetiredCommonInput(input as Record); const metadata = findCommandMetadata(command); - return await prepareRequestWithMetadataFlags(writer, metadata, input, host); + return await prepareRequestWithMetadataFlags(writer, metadata, input, host, deps); } async function prepareRequestWithMetadataFlags( @@ -101,8 +109,9 @@ async function prepareRequestWithMetadataFlags( metadata: ReturnType, input: CommandInput, host: HostEnvironment, + deps?: DaemonWriterDependencies, ): Promise { - const request = await writer(input, host); + const request = await writer(input, host, deps); return { ...request, ...(metadata ? { metadataFlags: readMetadataCommandFlags(metadata, request.options) } : {}), diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 77bba7d068..9de7aa211a 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -95,7 +95,7 @@ const openCommandMetadata = defineFieldCommandMetadata( const closeCommandMetadata = defineFieldCommandMetadata( 'close', - 'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s; a relaunching open accepts that new process. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.', + 'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s; a relaunching open accepts that new process. For foreground timeouts, JSON details include foregroundObservations and initialProcessCount; the android_close_foreground_fence request diagnostic retains the last five probe results and timings, including when a probe throws. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.', { app: stringField('Optional app to close.'), shutdown: booleanField('Shutdown the session/device where supported.'), diff --git a/packages/command-surface/src/replay/index.test.ts b/packages/command-surface/src/replay/index.test.ts index f21d7fb236..471dfdf76a 100644 --- a/packages/command-surface/src/replay/index.test.ts +++ b/packages/command-surface/src/replay/index.test.ts @@ -161,7 +161,7 @@ describe('replay command interface', () => { test('validates -e keys with the grammar of the resolved replay format', async () => { fs.writeFileSync(path.join(SCRIPT_ROOT, 'flow.yaml'), 'appId: demo.app\n---\n- back\n'); - const host = { env: {}, cwd: SCRIPT_ROOT }; + const host = { env: { AGENT_DEVICE_HOME: process.env.AGENT_DEVICE_HOME }, cwd: SCRIPT_ROOT }; await expect( replayDaemonWriter({ path: './checkout.ad', backend: 'maestro', env: ['user=x'] }, host), ).rejects.toMatchObject({ code: 'INVALID_ARGS' }); diff --git a/packages/command-surface/src/replay/index.ts b/packages/command-surface/src/replay/index.ts index 8fe72d95a8..3639075eba 100644 --- a/packages/command-surface/src/replay/index.ts +++ b/packages/command-surface/src/replay/index.ts @@ -28,6 +28,7 @@ import { METRO_RELOAD_FLAGS, REPLAY_FLAGS } from '@agent-device/command-registry import { withCommandRuntimeHints } from '../runtime-hints.ts'; import { collectReplayShellEnv, + getReplayPluginInstallation, parseReplayCliEnvEntries, readReplayCliEnvEntries, resolveReplayFormat, @@ -39,6 +40,13 @@ import { discoverReplaySourcePaths } from '@agent-device/replay-port/source-disc const REPLAY_COMMAND_NAME = 'replay'; const TEST_COMMAND_NAME = 'test'; +const replayPluginMcpDetail = (['ad', 'maestro'] as const) + .map((id) => { + const declaration = getReplayPluginInstallation(id); + return `${declaration.summary} (plugin, install separately). ${declaration.installationHint}`; + }) + .join(' '); + const REPLAY_SHELL_ENV_PREFIX = 'AD_VAR_'; const replayCommandDescription = @@ -245,7 +253,7 @@ export const testCliReader: CliReader = (positionals, flags) => ({ testIme: flags.testIme, }); -export const replayDaemonWriter: AsyncDaemonWriter = async (input, host) => { +export const replayDaemonWriter: AsyncDaemonWriter = async (input, host, deps) => { const inputPath = requiredDaemonString(input.path, 'replay requires path'); const replayBackend = readReplayBackend(input); const replayShellEnv = collectReplayClientShellEnv(host.env); @@ -259,6 +267,8 @@ export const replayDaemonWriter: AsyncDaemonWriter = async (input, host) => { // client-collects-local-input move `replayShellEnv` already makes — and // the daemon executes only what arrives in this bundle. replayScriptSource: await loadReplayScriptSourceBundle({ + hostEnv: host.env, + resolveReplayBackend: deps?.resolveReplayBackend, inputPath, cwd: readReplayClientCwd(input, host.cwd), replayBackend, @@ -275,35 +285,52 @@ export const replayDaemonWriter: AsyncDaemonWriter = async (input, host) => { }); }; -export const testDaemonWriter: AsyncDaemonWriter = async (input, host) => { +export const testDaemonWriter: AsyncDaemonWriter = async (input, host, deps) => { const inputs = input.paths ?? []; const replayBackend = readReplayBackend(input); const cwd = readReplayClientCwd(input, host.cwd); const replayShellEnv = collectReplayClientShellEnv(host.env); + // #1802: `test` inputs belong to the caller, including expansion and source collection. + const sourcePaths = discoverReplaySourcePaths({ inputs, cwd, replayBackend }); + const collectSources = async (resolveReplayBackend = deps?.resolveReplayBackend) => { + const sources = []; + for (const inputPath of sourcePaths) { + sources.push( + await loadReplayScriptSourceBundle({ + hostEnv: host.env, + resolveReplayBackend, + inputPath, + cwd, + replayBackend, + env: readReplayScriptSourceEnv( + input, + replayShellEnv, + resolveReplayFormat(inputPath, replayBackend), + ), + }), + ); + } + return sources; + }; + const replayScriptSources = sourcePaths.some( + (inputPath) => resolveReplayFormat(inputPath, replayBackend) === 'maestro', + ) + ? await ( + await import('@agent-device/replay-port/replay-backend-registry') + ).withReplayBackend( + 'maestro', + host, + (backend) => collectSources(async () => backend), + deps?.resolveReplayBackend, + ) + : await collectSources(); return request(TEST_COMMAND_NAME, inputs, { ...stripReplayTestPresentationInput(input), replayUpdate: input.update, replayBackend, replayEnv: input.env, replayShellEnv, - // #1802: `test` inputs are paths, directories, and globs on the CALLER's - // filesystem. Expanding them here keeps discovery order identical for a - // local and a remote daemon and ships each discovered source's text. - replayScriptSources: await Promise.all( - discoverReplaySourcePaths({ inputs, cwd, replayBackend }).map( - async (inputPath) => - await loadReplayScriptSourceBundle({ - inputPath, - cwd, - replayBackend, - env: readReplayScriptSourceEnv( - input, - replayShellEnv, - resolveReplayFormat(inputPath, replayBackend), - ), - }), - ), - ), + replayScriptSources, }); }; @@ -311,8 +338,9 @@ export const replayCommandFacet = defineCommandFacet({ name: REPLAY_COMMAND_NAME, effect: 'destructive', text: { - summary: 'Replay a recorded session or Maestro flow', + summary: 'Replay a recorded session or Maestro flow (plugin, install separately)', searchHint: 'rerun', + mcpDetail: replayPluginMcpDetail, cliDetail: 'Replay has a 60-second work budget inside a 90-second client timeout; --timeout sets a work budget of X and client timeout of X + 30000 ms. The running step receives ordinary request cancellation at the budget. When it settles, failure returns details.reason daemon_request_timeout and details.timeoutMs, preserving the failing script path and line. The daemon and other sessions stay available if it responds; an authored close may already have ended its session. A completed replay returns success even if it settles just after the deadline. Cancellation does not prove native device work stopped. A step that ignores cancellation beyond the 30-second margin may cause a transport timeout; an unresponsive daemon retains the client liveness-based reset. Direct test keeps its own timeout behavior. For Maestro YAML compatibility flows, use replay --maestro and keep the target binding such as --platform ios on the replay command. A script with no terminal close leaves its session (and daemon) running until you close it or it idle-reaps — no different from a session opened interactively. For native .ad scripts, --keep-session suppresses exactly an authored terminal close so you can continue interactively. replay export converts compatible actions to Maestro YAML locally, including app switches with explicit launchApp.appId targets, deep links (including tel: and mailto:) as openLink, and home as pressKey: Home.', }, @@ -327,8 +355,9 @@ export const testCommandFacet = defineCommandFacet({ name: TEST_COMMAND_NAME, effect: 'destructive', text: { - summary: 'Run replay test suites', - searchHint: 'tests ad', + summary: 'Run replay test suites (plugin, install separately)', + searchHint: 'tests', + mcpDetail: replayPluginMcpDetail, cliDetail: "Relative globs are expanded on the caller from its working directory, whose name is treated literally. Quote glob inputs to defer expansion to test. Copied diagnostic artifacts receive numbered filenames when needed to preserve other artifacts, replay sources, timing traces, and attempt manifests. JUnit reports (--reporter junit:) replace characters forbidden by XML 1.0 with U+FFFD and preserve legal Unicode and whitespace. JSON and other reporters retain the original suite values. Custom reporter getExitCode hooks must return an integer from 0 to 255 or undefined; the highest valid code wins and cannot lower a failing suite's exit code. A nested test stops after a bounded resource refusal even with --retries; other failures keep their configured retries.", }, diff --git a/packages/command-surface/src/schema/command-overrides.ts b/packages/command-surface/src/schema/command-overrides.ts index 691b1dd020..cc2b47c77a 100644 --- a/packages/command-surface/src/schema/command-overrides.ts +++ b/packages/command-surface/src/schema/command-overrides.ts @@ -15,12 +15,12 @@ const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = { text: { summary: 'Manage installed provider plugins', description: - 'Install, list, update, or remove npm provider plugins in AGENT_DEVICE_HOME (default ~/.agent-device). Changes take effect after restarting the local daemon. list works offline and, when a daemon is running for --state-dir, also reports the providers it registered. Use --json for structured results.', + 'Install, list, update, or remove provider plugins in AGENT_DEVICE_HOME (default ~/.agent-device). Changes take effect after restarting the local daemon. list works offline and, when a daemon is running for --state-dir, also reports the providers it registered. For a local tarball, use a path starting with ./ or ../, or an absolute path. Use --json for structured results.', }, usageOverride: - 'plugins list [--state-dir ]|add |update |remove ', + 'plugins list [--state-dir ]|add |update |remove ', listUsageOverride: 'plugins', - positionalArgs: ['list|add|update|remove', 'package?'], + positionalArgs: ['list|add|update|remove', 'package-or-path?'], flagsByAction: { list: ['stateDir'], add: [], update: [], remove: [] }, supportedFlags: ['stateDir'], }, diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 15207e4d4d..9982191dd2 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -555,6 +555,26 @@ "./wait": { "types": "./src/wait.ts", "default": "./src/wait.ts" + }, + "./replay-divergence-data": { + "types": "./src/replay-divergence-data.ts", + "default": "./src/replay-divergence-data.ts" + }, + "./replay-script-data": { + "types": "./src/replay-script-data.ts", + "default": "./src/replay-script-data.ts" + }, + "./ad-replay-execution": { + "types": "./src/ad-replay-execution.ts", + "default": "./src/ad-replay-execution.ts" + }, + "./replay-test-execution": { + "types": "./src/replay-test-execution.ts", + "default": "./src/replay-test-execution.ts" + }, + "./replay-execution": { + "types": "./src/replay-execution.ts", + "default": "./src/replay-execution.ts" } }, "devDependencies": { diff --git a/packages/contracts/src/__tests__/lease-scope-rpc.test.ts b/packages/contracts/src/__tests__/lease-scope-rpc.test.ts new file mode 100644 index 0000000000..44a5aaca90 --- /dev/null +++ b/packages/contracts/src/__tests__/lease-scope-rpc.test.ts @@ -0,0 +1,33 @@ +import { expect, test } from 'vitest'; +import { buildDaemonRpcRequest } from '../lease-scope.ts'; + +function leaseRpcParams( + flags: { session?: string }, + meta: { sessionExplicit?: boolean }, +): Record { + return buildDaemonRpcRequest( + { + token: 'token', + session: 'default', + command: 'lease_allocate', + positionals: [], + flags, + meta: { tenantId: 'acme', runId: 'run-a', leaseBackend: 'android-instance', ...meta }, + }, + { id: 'id', includeTokenParam: false }, + ).params as Record; +} + +test.each([ + ['a client that named none', {}, { sessionExplicit: false }, false], + ['a client that named one in its meta', {}, { sessionExplicit: true }, true], + [ + 'a client that named one in its flags', + { session: 'default' }, + { sessionExplicit: false }, + true, + ], + ['a caller that predates the fact', {}, {}, undefined], +])('the lease method carries what %s said about its session', (_label, flags, meta, expected) => { + expect(leaseRpcParams(flags, meta).sessionExplicit).toBe(expected); +}); diff --git a/packages/ad-replay/src/internal/runtime-port-types.ts b/packages/contracts/src/ad-replay-execution.ts similarity index 85% rename from packages/ad-replay/src/internal/runtime-port-types.ts rename to packages/contracts/src/ad-replay-execution.ts index 5a34a33034..5c04a31395 100644 --- a/packages/ad-replay/src/internal/runtime-port-types.ts +++ b/packages/contracts/src/ad-replay-execution.ts @@ -4,12 +4,12 @@ import type { Platform, PublicPlatform } from '@agent-device/kernel/device'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import type { TargetAnnotationV1 } from '@agent-device/contracts/replay'; import type { ReplayDivergenceTargetBindingKind } from '@agent-device/contracts/divergence'; -import type { buildReplayVarScope, LocalIdentity } from '@agent-device/ad-script'; import type { - AdReplayGuardMismatchEvidence, - AdReplayLandmarkMismatchEvidence, - AdReplayTargetStructuralDenotation, -} from './target-verification.ts'; + LocalIdentity, + NodeStructuralDenotation, + TargetAncestryEntry, +} from './target-annotation.ts'; +import type { ReplayVarSources, ReplayScriptMetadata } from './replay-script-data.ts'; /** * #1478 P5 stage C2b (split out of `step-loop.ts` by the #1555 structural- @@ -23,14 +23,8 @@ import type { * full boundary rationale. */ -/** - * `${VAR}` scope inputs — plain data (builtins/file/shell/cli env) the - * daemon reads from the request/process and passes in; `runAdReplay` builds - * the scope from this. Derived structurally off `buildReplayVarScope` - * (`@agent-device/ad-script` does not export its own `ReplayVarSources` type - * by name) rather than duplicating the shape. - */ -export type AdReplayVarSources = Parameters[0]; +/** Host-provided variable sources; the engine resolves each action once. */ +export type AdReplayVarSources = ReplayVarSources; /** * A `${VAR}` value eligible for divergence-report redaction — the engine's @@ -373,3 +367,60 @@ export type AdReplayRunOutcome = readonly stepIndex: number; readonly failure: AdReplayStepFailure; }>; + +/** The verified member's shared structural position, read-only across the execution boundary. */ +export type AdReplayTargetStructuralDenotation = Readonly; + +/** + * The guard-mismatch refusal's typed evidence, already narrowed by the + * daemon adapter from the wire response's `details` bag — the engine never + * sees the untyped bag itself. + */ +export type AdReplayGuardMismatchEvidence = Readonly<{ + targetRole?: 'source' | 'destination'; + observed: LocalIdentity | undefined; + expectedStructural: AdReplayTargetStructuralDenotation | undefined; + observedStructural: AdReplayTargetStructuralDenotation | undefined; +}>; + +/** The wait-landmark-mismatch refusal's typed evidence — same translate-before-crossing rule. */ +export type AdReplayLandmarkMismatchEvidence = Readonly<{ + matchCount: number | undefined; + observed: LocalIdentity | undefined; + observedAncestry: readonly TargetAncestryEntry[]; +}>; + +export type AdReplayManifest = Readonly<{ + actions: SessionAction[]; + actionLines: number[]; + metadata: ReplayScriptMetadata; + /** SHA-256 digest of the canonical plan (`digestFlags` binds the same platform/target the replay invokes with). */ + planDigest: string; + /** The `--from`/`--plan-digest` resume-point math, closed over this manifest's own `actions`/`planDigest`. */ + resolveEntryIndex(params: AdReplayEntryIndexParams): AdReplayEntryIndexResult; +}>; + +/** The request-level `--platform`/`--target` override the plan digest binds (raw flags, before any metadata merge). */ +export type AdReplayDigestFlags = Readonly<{ platform?: string; target?: string }>; + +/** + * The session-side state that gates an EMPTY-TAIL resume (`--from actionCount + * + 1`). Stamped for `record-and-heal`, and per #1262 also for + * `caution`/`manual`'s record-and-heal-shaped alternate repair (their own + * unshifted `resume.from` is unaffected by this watermark). + */ +export type PendingRecordAndHeal = Readonly<{ + expectedFrom: number; + actionsCountAtDivergence: number; +}>; + +export type AdReplayEntryIndexParams = Readonly<{ + from: number | undefined; + digest: string | undefined; + pendingRecordAndHeal: PendingRecordAndHeal | undefined; + sessionActionsLength: number; +}>; + +export type AdReplayEntryIndexResult = + | Readonly<{ readonly ok: true; readonly value: number }> + | Readonly<{ readonly ok: false; readonly message: string }>; diff --git a/packages/contracts/src/application-lifecycle-runtime.test.ts b/packages/contracts/src/application-lifecycle-runtime.test.ts new file mode 100644 index 0000000000..84be227890 --- /dev/null +++ b/packages/contracts/src/application-lifecycle-runtime.test.ts @@ -0,0 +1,72 @@ +import assert from 'node:assert/strict'; +import { describe, test } from 'vitest'; +import { + availableAppleApplicationToolsForProvider, + type AppleApplicationTools, +} from './application-lifecycle-runtime.ts'; + +/** Every member the root port carries; the projection is checked against this full key set. */ +const FULL_PORT_MEMBERS: readonly (keyof AppleApplicationTools)[] = [ + 'resolveOpenTarget', + 'prewarmRunnerCache', + 'prewarmRunnerSession', + 'notifyRunnerAppRelaunched', + 'stopRunnerSession', + 'hasLiveRunnerSession', + 'releaseSpeculativeRunner', + 'releaseRunnerOnClose', + 'prepareRunner', + 'applyRuntimeHints', + 'clearRuntimeHints', + 'dismissCloseAlerts', + 'detachRunnerSessionsForShutdown', + 'finalizeRunnerSessionsForShutdown', +]; + +function fullTools(reached: string[]): AppleApplicationTools { + const fail = (name: string) => + (async () => { + reached.push(name); + }) as never; + return Object.fromEntries( + FULL_PORT_MEMBERS.map((member) => [member, fail(member)]), + ) as unknown as AppleApplicationTools; +} + +describe('availableAppleApplicationToolsForProvider', () => { + test('the projection publishes exactly the three operations a provider consumes', () => { + const projected = availableAppleApplicationToolsForProvider(fullTools([])); + assert.deepEqual(Object.keys(projected).sort(), [ + 'applyRuntimeHints', + 'clearRuntimeHints', + 'resolveOpenTarget', + ]); + assert.ok(Object.isFrozen(projected)); + }); + + test('the runner and shutdown members are gone from the runtime value, not only the type', async () => { + const reached: string[] = []; + const projected = availableAppleApplicationToolsForProvider( + fullTools(reached), + ) as AppleApplicationTools & Record; + // A holder reading through an unchecked reference gets `undefined`: there is no member to call, + // so no runner-session id, this lease's or another session's, can reach the daemon's registry. + for (const member of [ + 'stopRunnerSession', + 'releaseRunnerOnClose', + 'prepareRunner', + 'prewarmRunnerSession', + 'prewarmRunnerCache', + 'notifyRunnerAppRelaunched', + 'hasLiveRunnerSession', + 'releaseSpeculativeRunner', + 'dismissCloseAlerts', + 'detachRunnerSessionsForShutdown', + 'finalizeRunnerSessionsForShutdown', + ]) { + assert.equal(projected[member], undefined, member); + } + await projected.applyRuntimeHints?.({ id: 'sim-1' } as never, { values: {} }); + assert.deepEqual(reached, ['applyRuntimeHints']); + }); +}); diff --git a/packages/contracts/src/application-lifecycle-runtime.ts b/packages/contracts/src/application-lifecycle-runtime.ts index 36a38e8b9c..28cf958f43 100644 --- a/packages/contracts/src/application-lifecycle-runtime.ts +++ b/packages/contracts/src/application-lifecycle-runtime.ts @@ -438,6 +438,39 @@ export type AppleApplicationTools = Readonly<{ finalizeRunnerSessionsForShutdown(): Promise; }>; +/** + * The Apple mechanics one provider lease consumes: resolving what an open addresses, and applying + * or clearing this platform's runtime hints. Runner mechanics are absent by declaration because a + * lease owns its own runner — {@link AppleApplicationTools} names what a lease's own tools expose + * once the lease binds it — and a holder of this projection has no session id to hand to them even + * at runtime. + */ +export type AppleApplicationToolsForProvider = Readonly<{ + resolveOpenTarget( + device: DeviceInfo, + input: OpenTargetResolutionInput, + ): Promise; + applyRuntimeHints(device: DeviceInfo, input: RuntimeHintsApplicationInput): Promise; + clearRuntimeHints(device: DeviceInfo, input: RuntimeHintsApplicationInput): Promise; +}>; + +/** + * Projects Apple tools to {@link AppleApplicationToolsForProvider}. Every member beyond the allow- + * listed three — the runner-session mechanics a lease owns, and the daemon-wide shutdown members + * that hand off or stop every runner session this process holds — is removed from the runtime + * value, not only from its type, so a holder of the projection cannot reach any of them through an + * unchecked reference. The daemon's own durable-resource lifecycle keeps the full port. + */ +export function availableAppleApplicationToolsForProvider( + tools: AppleApplicationToolsForProvider, +): AppleApplicationToolsForProvider { + return Object.freeze({ + resolveOpenTarget: tools.resolveOpenTarget, + applyRuntimeHints: tools.applyRuntimeHints, + clearRuntimeHints: tools.clearRuntimeHints, + }); +} + /** Lazy Android mechanics used by the Android package's own lifecycle binding. */ export type AndroidApplicationTools = Readonly<{ resolveOpenTarget( diff --git a/packages/contracts/src/artifact-adapter.ts b/packages/contracts/src/artifact-adapter.ts index c6672e6721..6e498280a2 100644 --- a/packages/contracts/src/artifact-adapter.ts +++ b/packages/contracts/src/artifact-adapter.ts @@ -91,7 +91,7 @@ export type ArtifactAdapter = { }; export type LocalArtifactAdapterOptions = { - cwd?: string; + cwd: string; tempDir?: string; /** Restricts explicit paths lexically; symlinks are not resolved. This is not a sandbox. */ rootDir?: string; diff --git a/packages/contracts/src/client-connection.ts b/packages/contracts/src/client-connection.ts index 96bb4a55c9..19577ab673 100644 --- a/packages/contracts/src/client-connection.ts +++ b/packages/contracts/src/client-connection.ts @@ -18,19 +18,20 @@ import type { } from './remote-config-fields.ts'; /** - * Who owns the daemon on a client's state directory. + * The one daemon lifecycle a client config selects: `attach`. The transport connects to its registered + * daemon without starting, replacing, retiring or timeout-killing it, including replay/test calls. + * CLI/MCP can own a private daemon for one-shot replay/test; library client calls cannot. + * A missing daemon fails with `details.reason: 'daemon-not-running'`; an incompatible one uses + * `'daemon-incompatible'`. * - * - `managed`: the client starts a missing daemon and replaces an incompatible one itself, and may - * retire a hung one after a timeout. This is the default until 0.22. - * - `attach`: the client only connects to the daemon registered in the state directory. It never - * starts, replaces or kills one. A missing daemon fails with `details.reason: 'daemon-not-running'` - * and an incompatible one with `'daemon-incompatible'`; `ensureDaemon()` is the explicit way to - * start or replace one. + * `ensureDaemon()` is the explicit way to start or replace a detached daemon. `startAgentDevice()` + * imported from `agent-device` owns one in your process and refuses an already registered state + * directory. `ensureDaemon()` refuses to replace a daemon that holds another client's work. * - * Independent of `daemonTransport`, `daemonServerMode` and `daemonBaseUrl`: a remote connection - * never starts or retires a local daemon in either mode. + * Independent of `daemonTransport`, `daemonServerMode` and `daemonBaseUrl`: a remote connection never + * starts or retires a local daemon. */ -export type DaemonLifecycle = 'attach' | 'managed'; +export type DaemonLifecycle = 'attach'; /** What a client can learn about a daemon without talking to it: how it identifies itself on disk. */ export type DaemonIdentity = { @@ -89,8 +90,6 @@ export type DaemonConnection = { export type AgentDeviceDaemonTransportContext = { authToken?: string; - /** How this request treats the local daemon; `managed` when omitted. */ - daemonLifecycle?: DaemonLifecycle; /** See {@link DaemonBinding}. A client built with one sends this same pin on every request. */ daemonBinding?: DaemonBinding; /** @@ -109,7 +108,10 @@ export type AgentDeviceDaemonTransport = ( export type AgentDeviceClientConfig = RemoteConnectionProfileFields & CloudProviderProfileFields & { - /** See `DaemonLifecycle`. */ + /** + * See `DaemonLifecycle`. Only `'attach'` is accepted, and it is the default; the removed + * `'managed'` value fails validation instead of starting a daemon. + */ daemonLifecycle?: DaemonLifecycle; /** * Pins this client to one daemon instance: every request addresses that instance, authenticates @@ -191,10 +193,9 @@ export type AgentDeviceRequestOverrides = Pick< * daemon reset. * * The guarantee covers the daemon request, and the built-in transports enforce it; a custom - * transport receives the signal on its context and may implement cancellation differently. Two - * phases run outside it: a response-artifact download started after the response begins is not - * canceled, and a canceled one-shot replay still runs the existing cleanup that may tear down a - * daemon this client started. + * transport receives the signal on its context and may implement cancellation differently. One + * phase runs outside it: a response-artifact download started after the response begins is not + * canceled. */ signal?: AbortSignal; }; diff --git a/packages/contracts/src/command-flags.ts b/packages/contracts/src/command-flags.ts index 872a9fd63a..5b6b3fd454 100644 --- a/packages/contracts/src/command-flags.ts +++ b/packages/contracts/src/command-flags.ts @@ -18,6 +18,7 @@ import { // wire cannot enforce a shape. This is the typed view of the same field, one rank above the wire // and below every consumer. +/** Shared replay-compatibility hints; these remain core runtime behavior without the flow engine. */ export type MaestroRuntimeFlags = { allowNonHittableCoordinateFallback?: boolean; expectedTapPoint?: Point; diff --git a/packages/contracts/src/host-diagnostics.ts b/packages/contracts/src/host-diagnostics.ts index fc99bd47aa..1611d41e61 100644 --- a/packages/contracts/src/host-diagnostics.ts +++ b/packages/contracts/src/host-diagnostics.ts @@ -46,3 +46,14 @@ export type HostDiagnostics = Readonly<{ context: HostDiagnosticsContext, ): Promise; }>; + +/** The severity an event is recorded with. */ +export type DiagnosticLevel = 'info' | 'warn' | 'error' | 'debug'; + +/** A diagnostic handed to the host that owns the request log and redaction. */ +export type DiagnosticEventInput = { + level?: DiagnosticLevel; + phase: string; + durationMs?: number; + data?: Record; +}; diff --git a/packages/contracts/src/lease-scope.ts b/packages/contracts/src/lease-scope.ts index f2a3856166..04d81d74db 100644 --- a/packages/contracts/src/lease-scope.ts +++ b/packages/contracts/src/lease-scope.ts @@ -1,6 +1,6 @@ import type { DaemonResponse, LeaseBackend } from '@agent-device/kernel/contracts'; import { AppError } from '@agent-device/kernel/errors'; -import { stripUndefined } from '@agent-device/kernel/record'; +import { namesSessionExplicitly, stripUndefined } from '@agent-device/kernel/record'; import type { CloudProviderProfileFields } from './remote-config-fields.ts'; import type { CommandFlags } from './command-flags.ts'; import type { DaemonWireRequest } from './daemon-wire-request.ts'; @@ -94,6 +94,19 @@ type LeaseOptionsLike = { clientId?: string; }; +/** The refusal for a request on a provider lease that names no session. */ +export function remoteSessionRequiredError(leaseProvider: string | undefined): AppError { + return new AppError( + 'INVALID_ARGS', + 'A leased remote connection needs its session named: pass --session , set AGENT_DEVICE_SESSION, or send the session parameter.', + { + reason: 'REMOTE_SESSION_REQUIRED', + ...(leaseProvider === undefined ? {} : { leaseProvider }), + hint: "Without a name, a command could reach another agent's connection.", + }, + ); +} + export function leaseScopeFromRequest(req: LeaseRequestLike): LeaseScope { return stripUndefined({ tenantId: req.meta?.tenantId ?? readFlagString(req.flags, 'tenant'), @@ -644,9 +657,14 @@ function buildLeaseRpcParams( command: LeaseRpcCommand, options: { includeTokenParam: boolean }, ): Record { - return leaseScopeToLeaseRpcParams(leaseScopeFromRequest(req), command, { - includeTokenParam: options.includeTokenParam, - token: req.token, - session: req.session, - }); + return { + ...leaseScopeToLeaseRpcParams(leaseScopeFromRequest(req), command, { + includeTokenParam: options.includeTokenParam, + token: req.token, + session: req.session, + }), + ...(req.meta?.sessionExplicit === undefined + ? {} + : { sessionExplicit: namesSessionExplicitly(req) }), + }; } diff --git a/packages/contracts/src/platform-runtime-use.ts b/packages/contracts/src/platform-runtime-use.ts index 9c2e387842..2c0219d01f 100644 --- a/packages/contracts/src/platform-runtime-use.ts +++ b/packages/contracts/src/platform-runtime-use.ts @@ -27,7 +27,7 @@ type RuntimeUseInput< * Runtime validation keeps declarations built from dynamic data fail-closed too. */ export function runtimeUse() { - return < + const define = < const Required extends readonly RuntimeOperationKey[], const Preferred extends readonly Exclude, Required[number]>[] = readonly [], @@ -68,6 +68,7 @@ export function runtimeUse() { conditional.length === 0 ? { required, preferred } : { required, preferred, conditional }, ) as RuntimeUse; }; + return define; } function freezeUniqueKeys(keys: Keys, label: string): Keys { diff --git a/packages/contracts/src/plugin-inventory.ts b/packages/contracts/src/plugin-inventory.ts index 77e68c6fbd..4a697c4515 100644 --- a/packages/contracts/src/plugin-inventory.ts +++ b/packages/contracts/src/plugin-inventory.ts @@ -16,6 +16,7 @@ export type PluginInventoryCredentials = Readonly<{ type PluginInventoryIdentity = Readonly<{ provider?: string; + backend?: string; source: PluginSource; package?: string; version?: string; @@ -36,12 +37,13 @@ export type PluginCleanupStep = * What closing the registry did for one registered plugin. A plugin without `dispose` has nothing to * dispose, which reads as `ok`. */ -export type PluginCleanupOutcome = Readonly<{ - provider: string; - source: PluginSource; - shutdown: PluginCleanupStep; - dispose: PluginCleanupStep; -}>; +export type PluginCleanupOutcome = Readonly< + ({ provider: string; backend?: never } | { backend: string; provider?: never }) & { + source: PluginSource; + shutdown: PluginCleanupStep; + dispose: PluginCleanupStep; + } +>; export const NO_PLUGIN_CREDENTIALS: PluginInventoryCredentials = Object.freeze({ variables: Object.freeze([]), @@ -79,6 +81,7 @@ function readEntry(value: unknown): PluginInventoryEntry | undefined { if (!credentials) return undefined; const identity = { ...(typeof value.provider === 'string' ? { provider: value.provider } : {}), + ...(typeof value.backend === 'string' ? { backend: value.backend } : {}), source: value.source, ...(typeof value.package === 'string' ? { package: value.package } : {}), ...(typeof value.version === 'string' ? { version: value.version } : {}), diff --git a/packages/contracts/src/replay-backend.ts b/packages/contracts/src/replay-backend.ts index a8597b2037..07f6fc383c 100644 --- a/packages/contracts/src/replay-backend.ts +++ b/packages/contracts/src/replay-backend.ts @@ -1,3 +1,6 @@ +import type { HostCommandRequest, HostCommandResult } from './platform-runtime-host.ts'; +import type { DiagnosticEventInput } from './host-diagnostics.ts'; +import type { SnapshotClickabilityEvidence } from './snapshot-private-evidence.ts'; import type { DaemonError } from '@agent-device/kernel/errors'; import type { DaemonResponse, SessionRuntimeHints } from '@agent-device/kernel/contracts'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -230,6 +233,18 @@ export type ReplayBackendDeviceBinding = Readonly<{ * session policy is a member; stateless workspace packages stay direct imports of the plugin. */ export type ReplayBackendHost = Readonly<{ + emitDiagnostic(event: DiagnosticEventInput): void; + /** Reads capture-local facts from the host's private evidence owner, without wire fields. */ + readSnapshotClickabilityEvidence(owner: object): SnapshotClickabilityEvidence | undefined; + /** Refuses capture-derived input when the host has no established screen origin. */ + assertSnapshotScreenOrigin(owner: object, label: string): Promise; + /** Executes a backend child with the host's subprocess lifecycle and diagnostic scope. */ + runCommand( + request: Omit & + Readonly<{ host: HostEnvironment; stdin?: string; detached?: boolean }>, + signal?: AbortSignal, + ): Promise; + registerSensitiveValue(value: string): void; /** Appends one record to the run's trace file, if any; failures are diagnostics, never thrown. */ appendTraceEvent(tracePath: string | undefined, event: Record): void; /** The `AD_*` variables every replay run is seeded with. */ @@ -265,9 +280,17 @@ export type ReplayBackendHost = Readonly<{ */ export type ReplayBackendDeclaration = Readonly<{ id: TId; + package: string; + installationHint: string; help: Readonly<{ summary: string; body: string }>; }>; export type ReplayBackendPlugin = Readonly<{ - create(host: ReplayBackendHost): ReplayBackend; + create(host: ReplayBackendHost): ReplayBackend | Promise>; }>; + +export type ReplayBackendResolver = ( + id: string, + host: ReplayBackendHost, + packageName?: string, +) => Promise; diff --git a/packages/ad-replay/src/replay-divergence.test.ts b/packages/contracts/src/replay-divergence-data.test.ts similarity index 98% rename from packages/ad-replay/src/replay-divergence.test.ts rename to packages/contracts/src/replay-divergence-data.test.ts index af85a73569..8b1d7d48a1 100644 --- a/packages/ad-replay/src/replay-divergence.test.ts +++ b/packages/contracts/src/replay-divergence-data.test.ts @@ -11,7 +11,7 @@ import { REPLAY_DIVERGENCE_LEVEL_BYTE_LIMITS, REPLAY_DIVERGENCE_SUGGESTION_LIMIT, truncateUtf8Field, -} from './replay-divergence.ts'; +} from './replay-divergence-data.ts'; import type { ReplayDivergence } from '@agent-device/contracts/divergence'; function buildDivergence(overrides: Partial = {}): ReplayDivergence { @@ -240,7 +240,7 @@ test('sanitizeReplayDivergenceField redacts sensitive content even when no trunc // --- Text report carries the repair data (bounded refs + unavailable hint) --- test('formatReplayDivergenceReport lists a bounded ref/role/label subset for an available screen', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -273,7 +273,7 @@ test('formatReplayDivergenceReport lists a bounded ref/role/label subset for an }); test('formatReplayDivergenceReport carries the unavailable-screen hint', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -296,7 +296,7 @@ test('formatReplayDivergenceReport carries the unavailable-screen hint', async ( }); test('scrubReplayVarValues replaces every occurrence with a named marker, longest value first', async () => { - const { scrubReplayVarValues } = await import('./replay-divergence.ts'); + const { scrubReplayVarValues } = await import('./replay-divergence-data.ts'); const entries = [ { name: 'LONG', value: 'abc-def' }, { name: 'SHORT', value: 'abc' }, @@ -415,7 +415,7 @@ test('boundReplayDivergence keeps targetBinding on the minimal overflow fallback }); test('formatReplayDivergenceReport renders matchCount, mismatches, and candidates for a target-binding divergence', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -443,7 +443,7 @@ test('formatReplayDivergenceReport renders matchCount, mismatches, and candidate }); test('formatReplayDivergenceReport lists candidates for an identity-unverifiable target-binding divergence', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -478,7 +478,7 @@ test('formatReplayDivergenceReport lists candidates for an identity-unverifiable // refused — it surfaces `resume.reason` instead. --- test('formatReplayDivergenceReport embeds the concrete resume command for an allowed record-and-heal divergence', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -503,7 +503,7 @@ test('formatReplayDivergenceReport embeds the concrete resume command for an all }); test('formatReplayDivergenceReport never renders a --from command when resume is NOT allowed, surfacing the reason instead', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -533,7 +533,7 @@ test('formatReplayDivergenceReport never renders a --from command when resume is }); test('formatReplayDivergenceReport falls back to a generic non-resumable sentence when resume carries no reason', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -562,7 +562,7 @@ test('formatReplayDivergenceReport falls back to a generic non-resumable sentenc // NEVER re-derives resumability, so text and structured wire never disagree. --- test('formatReplayDivergenceReport embeds BOTH concrete resume commands for a caution divergence whose wire carries alternateFrom', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -595,7 +595,7 @@ test('formatReplayDivergenceReport embeds BOTH concrete resume commands for a ca }); test('formatReplayDivergenceReport embeds BOTH concrete resume commands for a manual divergence whose wire carries alternateFrom', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -623,7 +623,7 @@ test('formatReplayDivergenceReport embeds BOTH concrete resume commands for a ma }); test('formatReplayDivergenceReport renders ONLY the state-fix command for a caution divergence WITHOUT alternateFrom (the diverged step is not skip-safe)', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); // resume.allowed is true (resuming AT N is fine), but the diverged step N // is a runScript/control-flow action, so `--from N + 1` would be refused — // the daemon omits alternateFrom, and the text must NOT offer `--from N + 1`. @@ -655,7 +655,7 @@ test('formatReplayDivergenceReport renders ONLY the state-fix command for a caut }); test('formatReplayDivergenceReport renders neither caution command when resume is NOT allowed', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -696,7 +696,7 @@ const REPAIR_DIAGNOSTICS_CLAUSE_PATTERN = /Read-only inspection while armed \(snapshot -i, get attrs, find, is\) is excluded from the healed script by default — no --no-record needed\. If the step you are repairing is itself a read, add --record to that command so it lands in the heal\./; test('formatReplayDivergenceReport appends the diagnostics default-exclusion clause for record-and-heal when repairSessionHeld is true', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -719,7 +719,7 @@ test('formatReplayDivergenceReport appends the diagnostics default-exclusion cla }); test('formatReplayDivergenceReport OMITS the diagnostics clause for record-and-heal when repairSessionHeld is absent (plain, non-repair divergence)', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -742,7 +742,7 @@ test('formatReplayDivergenceReport OMITS the diagnostics clause for record-and-h }); test('formatReplayDivergenceReport appends the diagnostics clause for state-repair when armed, distinct from the existing app-state --no-record clause', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -766,7 +766,7 @@ test('formatReplayDivergenceReport appends the diagnostics clause for state-repa }); test('formatReplayDivergenceReport OMITS the diagnostics clause for state-repair when repairSessionHeld is absent', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -787,7 +787,7 @@ test('formatReplayDivergenceReport OMITS the diagnostics clause for state-repair }); test('formatReplayDivergenceReport appends the diagnostics clause for caution when armed, alongside the dual-path resume commands', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -817,7 +817,7 @@ test('formatReplayDivergenceReport appends the diagnostics clause for caution wh }); test('formatReplayDivergenceReport OMITS the diagnostics clause for caution when repairSessionHeld is absent', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, @@ -837,7 +837,7 @@ test('formatReplayDivergenceReport OMITS the diagnostics clause for caution when }); test('formatReplayDivergenceReport appends the diagnostics clause for manual when armed, even when resume is NOT allowed', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); // `repairSessionHeld` reports the daemon KEPT THE SESSION LIVE, independent // of `resume.allowed` (plan-resumability) — the diagnostics clause must // still render here: the agent may still inspect the (held) session while @@ -869,7 +869,7 @@ test('formatReplayDivergenceReport appends the diagnostics clause for manual whe }); test('formatReplayDivergenceReport OMITS the diagnostics clause for manual when repairSessionHeld is absent', async () => { - const { formatReplayDivergenceReport } = await import('./replay-divergence.ts'); + const { formatReplayDivergenceReport } = await import('./replay-divergence-data.ts'); const report = formatReplayDivergenceReport({ divergence: { version: 1, diff --git a/packages/ad-replay/src/replay-divergence.ts b/packages/contracts/src/replay-divergence-data.ts similarity index 100% rename from packages/ad-replay/src/replay-divergence.ts rename to packages/contracts/src/replay-divergence-data.ts diff --git a/packages/contracts/src/replay-execution.ts b/packages/contracts/src/replay-execution.ts new file mode 100644 index 0000000000..03b397a292 --- /dev/null +++ b/packages/contracts/src/replay-execution.ts @@ -0,0 +1,34 @@ +/** The managed backend identity that owns native replay and suite execution. */ +export const NATIVE_REPLAY_BACKEND = 'ad'; + +import type { + AdReplayDigestFlags, + AdReplayManifest, + AdReplayRunRequest, + AdReplayRunOutcome, + AdReplayStepRuntime, +} from './ad-replay-execution.ts'; +import type { + ReplayTestSuiteRequest, + ReplayTestSuiteOutcome, + ReplayTestRuntimeDependencies, +} from './replay-test-execution.ts'; + +/** Native execution receives host-owned inspection, step and suite inputs. */ +export type ReplayExecution = Readonly<{ + inspectAdReplay(script: string, digestFlags?: AdReplayDigestFlags): AdReplayManifest; + runAdReplay( + request: AdReplayRunRequest, + runtime: AdReplayStepRuntime, + ): Promise; + runReplayTestSuite( + params: { request: ReplayTestSuiteRequest } & ReplayTestRuntimeDependencies, + ): Promise; +}>; + +/** The managed registry creates one native engine and owns its lifetime. */ +export type ReplayExecutionPlugin = Readonly<{ + create(): ReplayExecution | Promise; +}>; + +export type ReplayExecutionResolver = (packageName?: string) => Promise; diff --git a/packages/contracts/src/replay-script-data.ts b/packages/contracts/src/replay-script-data.ts new file mode 100644 index 0000000000..7bd76bfd51 --- /dev/null +++ b/packages/contracts/src/replay-script-data.ts @@ -0,0 +1,16 @@ +import type { DeviceTarget, PlatformSelector } from '@agent-device/kernel/device'; + +export type ReplayScriptMetadata = { + platform?: Exclude; + target?: DeviceTarget; + timeoutMs?: number; + retries?: number; + env?: Record; +}; + +export type ReplayVarSources = { + builtins?: Record; + fileEnv?: Record; + shellEnv?: Record; + cliEnv?: Record; +}; diff --git a/packages/replay-test/src/internal/session-test-types.ts b/packages/contracts/src/replay-test-execution.ts similarity index 91% rename from packages/replay-test/src/internal/session-test-types.ts rename to packages/contracts/src/replay-test-execution.ts index a7dfe1ca44..7495c8105a 100644 --- a/packages/replay-test/src/internal/session-test-types.ts +++ b/packages/contracts/src/replay-test-execution.ts @@ -5,11 +5,6 @@ import type { ReplayTestSuiteProgressEvent, } from '@agent-device/contracts/progress'; import type { DeviceTarget, PlatformSelector } from '@agent-device/kernel/device'; -import type { - ReplayTestResolveShardTargets, - ReplayTestShardContext, - ReplayTestShardMode, -} from './session-test-sharding.ts'; /** * The device vocabulary a scheduler may name, sourced from the neutral kernel rather than @@ -276,20 +271,35 @@ export type ReplayTestExecutionDependencies = Omit< 'discoverSources' | 'resolveShardTargets' >; -/** Neutral failure outcome helper; keeps timeout/unknown construction in one place. */ -export function replayTestAttemptFailure(params: { - error: ReplayTestAttemptError; - artifactPaths?: readonly string[]; - warnings?: readonly string[]; - infrastructure?: boolean; - snapshotDiagnostics?: SnapshotDiagnosticsSummary; -}): ReplayTestAttemptFailed { - return { - status: 'failed', - error: params.error, - artifactPaths: params.artifactPaths ?? [], - warnings: params.warnings ?? [], - infrastructure: params.infrastructure ?? false, - ...(params.snapshotDiagnostics ? { snapshotDiagnostics: params.snapshotDiagnostics } : {}), - }; -} +export type ReplayTestShardMode = 'all' | 'split'; + +/** + * The device a shard runs against, in neutral vocabulary. + * + * The scheduler reads `id`/`name` for session labels and progress metadata. `platform` and + * `target` are here because the host needs them to bind a nested request, and both are already + * neutral kernel types — so `DeviceInfo` itself never crosses into scheduling. + */ +export type ReplayTestShardTarget = Readonly<{ + id: string; + name: string; + platform: ReplayTestPlatform; + target?: ReplayTestTarget; +}>; + +export type ReplayTestShardContext = { + shardIndex: number; + shardCount: number; + device: ReplayTestShardTarget; +}; + +/** + * Resolves the devices a sharded run will use (#1478 P3b). + * + * Enumerating inventory, applying allowlists and simulator set paths, and rejecting a run with + * too few devices are all host concerns. The scheduler decides how many shards there are and + * which entries go to each; it never enumerates hardware. + */ +export type ReplayTestResolveShardTargets = ( + shardCount: number, +) => Promise; diff --git a/packages/daemon-client/package.json b/packages/daemon-client/package.json index 8d0fa16303..8821b515e1 100644 --- a/packages/daemon-client/package.json +++ b/packages/daemon-client/package.json @@ -5,7 +5,6 @@ "type": "module", "description": "The client side of the daemon wire: transport and JSON-RPC framing, request cancellation and progress, local daemon launch, ensure, attach and stop, and remote daemon health. Internal workspace package bundled into the published agent-device artifact.", "dependencies": { - "@agent-device/ad-replay": "workspace:*", "@agent-device/command-registry": "workspace:*", "@agent-device/contracts": "workspace:*", "@agent-device/daemon-contracts": "workspace:*", diff --git a/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts b/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts index 94985b11b5..63a780e0c5 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts @@ -99,7 +99,7 @@ test('attach reports a missing daemon without starting one', async (t) => { if (!(await withLoopback(t))) return; const { stateDir, paths } = stateDirAndPaths(); - const error = await failureOf(sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' })); + const error = await failureOf(sendToDaemon(request(stateDir))); assert.equal(error.details?.reason, 'daemon-not-running'); assert.match(String(error.details?.hint), /agent-device devices --state-dir /); @@ -118,7 +118,7 @@ test('attach reports an incompatible daemon with both identities and leaves it r }); try { - const error = await failureOf(sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' })); + const error = await failureOf(sendToDaemon(request(stateDir))); assert.equal(error.details?.reason, 'daemon-incompatible'); assert.equal(identityIn(error, 'daemon').version, '0.0.0-stale'); @@ -141,7 +141,7 @@ for (const ownership of ['detached', 'embedded'] as const) await closeLoopbackServer(closed.server); const { child } = await registerDaemon(paths, { httpPort: closed.port, ownership }); - const error = await failureOf(sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' })); + const error = await failureOf(sendToDaemon(request(stateDir))); assert.equal(error.details?.reason, 'daemon-not-running'); assert.equal(identityIn(error, 'daemon').pid, child.pid); @@ -163,29 +163,29 @@ test('attach uses a compatible daemon and never lets a timeout retire it', async const send = vi.spyOn(transport, 'sendRequest'); try { - const response = await sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' }); + const response = await sendToDaemon(request(stateDir)); assert.deepEqual(response, { ok: true, data: { via: 'live' } }); assert.equal(send.mock.calls.at(-1)?.[5]?.timeoutRecovery, 'none'); + // The removed per-request lifecycle knob cannot resurrect the old kill path: an omitted context + // attaches too, and still may not retire the daemon on a timeout. await sendToDaemon(request(stateDir)); - assert.equal(send.mock.calls.at(-1)?.[5]?.timeoutRecovery, 'retire-unresponsive'); + assert.equal(send.mock.calls.at(-1)?.[5]?.timeoutRecovery, 'none'); assert.equal(spawn.mock.calls.length, 0); } finally { await closeLoopbackServer(live.server); } }); -test('a remote connection never starts a local daemon in either lifecycle', async (t) => { +test('a remote connection never starts a local daemon', async (t) => { if (!(await withLoopback(t))) return; const { stateDir } = stateDirAndPaths(); const unreachable = await startScriptedDaemon(okResult({})); await closeLoopbackServer(unreachable.server); const remote = { daemonBaseUrl: `http://127.0.0.1:${unreachable.port}` }; - for (const daemonLifecycle of ['attach', 'managed'] as const) { - const error = await failureOf(sendToDaemon(request(stateDir, remote), { daemonLifecycle })); - assert.match(error.message, /Remote daemon is unavailable/); - } + const error = await failureOf(sendToDaemon(request(stateDir, remote))); + assert.match(error.message, /Remote daemon is unavailable/); assert.equal(spawn.mock.calls.length, 0); }); @@ -508,9 +508,7 @@ test('a live daemon on another transport is left alone when it cannot be asked t assert.equal(ensured.details?.reason, 'daemon-incompatible'); assert.equal(ensured.details?.mismatch, 'no-quiesce'); - const attached = await failureOf( - sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' }), - ); + const attached = await failureOf(sendToDaemon(request(stateDir))); assert.equal(attached.details?.reason, 'daemon-incompatible'); assert.equal(attached.details?.mismatch, 'transport'); @@ -688,9 +686,7 @@ test('a registration whose process is gone is not running, whatever version it n ); try { - const attached = await failureOf( - sendToDaemon(request(stateDir), { daemonLifecycle: 'attach' }), - ); + const attached = await failureOf(sendToDaemon(request(stateDir))); assert.equal(attached.details?.reason, 'daemon-not-running'); // ensureDaemon replaces the dead registration without asking anyone to leave. diff --git a/packages/daemon-client/src/__tests__/daemon-client-ensuring.test.ts b/packages/daemon-client/src/__tests__/daemon-client-ensuring.test.ts index 53de2dc63c..b63a28422f 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-ensuring.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-ensuring.test.ts @@ -31,8 +31,9 @@ import { createEnsuredDaemonTransport, type sendToDaemon } from '../index.ts'; import * as ensureModule from '../daemon-client-ensure.ts'; // The CLI and MCP reach the daemon through `withEnsuredDaemon`. The transport underneath is a -// recorder, so what these tests read is the lifecycle each request was handed and what ensuring -// did to the state directory before it. +// recorder, so what these tests read is the context each request was handed — which ensuring passes +// through unchanged, since every request attaches — and what ensuring did to the state directory +// before it. const spawn = vi.mocked(runCmdDetachedMonitored); @@ -44,9 +45,13 @@ afterEach(async () => { }); function recordingTransport() { - const sent: Array<{ command: string; lifecycle: string | undefined }> = []; + const sent: Array<{ + command: string; + /** The exact context object the caller passed, proving ensuring hands it over unchanged. */ + context: unknown; + }> = []; const transport: typeof sendToDaemon = async (req, context) => { - sent.push({ command: req.command, lifecycle: context?.daemonLifecycle }); + sent.push({ command: req.command, context }); return { ok: true, data: {} }; }; return { sent, transport }; @@ -74,8 +79,8 @@ test('the first request ensures a missing daemon once and every request attaches assert.equal(spawn.mock.calls.length, 1); assert.deepEqual(sent, [ - { command: 'devices', lifecycle: 'attach' }, - { command: 'snapshot', lifecycle: 'attach' }, + { command: 'devices', context: undefined }, + { command: 'snapshot', context: undefined }, ]); } finally { await closeLoopbackServer(fresh.server); @@ -108,7 +113,7 @@ test('an idle incompatible daemon is replaced, and the replacement is reported', assert.deepEqual(replaced, [ { stateDir: paths.baseDir, pid: child.pid, reason: 'incompatible' }, ]); - assert.equal(sent[0]?.lifecycle, 'attach'); + assert.deepEqual(sent[0]?.context, undefined, 'ensuring hands the caller context through'); assert.deepEqual(leaver.clientSignals, [], 'the client signaled nothing'); } finally { await closeLoopbackServer(stale.server); @@ -146,7 +151,7 @@ test('a busy incompatible daemon fails the request before it is sent and keeps r } }); -test('a remote connection passes through without ensuring or choosing a lifecycle', async () => { +test('a remote connection passes through untouched by ensuring', async () => { const { stateDir } = stateDirAndPaths(); const { sent, transport } = recordingTransport(); const ensuring = withEnsuredDaemon(transport); @@ -156,8 +161,8 @@ test('a remote connection passes through without ensuring or choosing a lifecycl await ensuring(request('snapshot', { stateDir })); assert.deepEqual(sent, [ - { command: 'devices', lifecycle: undefined }, - { command: 'snapshot', lifecycle: undefined }, + { command: 'devices', context: undefined }, + { command: 'snapshot', context: undefined }, ]); assert.equal(spawn.mock.calls.length, 0); }); @@ -172,11 +177,11 @@ test('a one-shot replay on its own private daemon passes through, an explicit st try { await ensuring(request('replay', { daemonTransport: 'http' })); - assert.deepEqual(sent, [{ command: 'replay', lifecycle: undefined }]); + assert.deepEqual(sent, [{ command: 'replay', context: undefined }]); assert.equal(spawn.mock.calls.length, 0); await ensuring(request('replay', { stateDir, daemonTransport: 'http' })); - assert.equal(sent[1]?.lifecycle, 'attach'); + assert.equal(sent[1]?.command, 'replay'); assert.equal(spawn.mock.calls.length, 1); } finally { await closeLoopbackServer(fresh.server); @@ -270,7 +275,7 @@ test('a failed ensure is retried by the next request instead of being remembered launchesFreshDaemonAt(spawn, paths, fresh.port); await ensuring(request('devices', flags)); - assert.deepEqual(sent, [{ command: 'devices', lifecycle: 'attach' }]); + assert.deepEqual(sent, [{ command: 'devices', context: undefined }]); } finally { await closeLoopbackServer(stale.server); await closeLoopbackServer(fresh.server); @@ -323,10 +328,13 @@ test('a request canceled before it starts does not start a daemon', async (t) => const canceled = AbortSignal.abort(); try { - await ensuring(request('devices', { stateDir, daemonTransport: 'http' }), { signal: canceled }); + const signal = { signal: canceled } as const; + await ensuring(request('devices', { stateDir, daemonTransport: 'http' }), signal); - assert.equal(spawn.mock.calls.length, 0); - assert.deepEqual(sent, [{ command: 'devices', lifecycle: 'attach' }]); + assert.equal(spawn.mock.calls.length, 0, 'a caller that has given up starts nothing'); + assert.equal(sent.length, 1); + assert.equal(sent[0]?.command, 'devices'); + assert.strictEqual(sent[0]?.context, signal); } finally { await closeLoopbackServer(fresh.server); } diff --git a/packages/daemon-client/src/__tests__/daemon-client-lease-beat.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lease-beat.test.ts index 9c57045dfd..8ef0e9d438 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lease-beat.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lease-beat.test.ts @@ -604,7 +604,6 @@ describe('buildUploadLeaseHeartbeat', () => { host: { env: process.env, cwd: process.cwd() }, paths: resolveDaemonPaths('/tmp/agent-device-upload-lease'), transportPreference: 'socket' as const, - daemonLifecycle: 'managed' as const, retireIncompatibleContender: true, serverMode: 'socket' as const, }; diff --git a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-embedded.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-embedded.test.ts index 1e896dd48f..b689943598 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-embedded.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-embedded.test.ts @@ -33,7 +33,11 @@ vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({ })); import { runCmdDetachedMonitored } from '@agent-device/host-kit/command'; import { createDaemonTransport, type sendToDaemon } from '../index.ts'; -import { resolveClientSettings, resolveTimeoutRecovery } from '../daemon-client-lifecycle.ts'; +import { + resolveClientSettings, + resolveTimeoutRecovery, + ensureStartedDaemon, +} from '../daemon-client-lifecycle.ts'; const spawn = vi.mocked(runCmdDetachedMonitored); @@ -52,6 +56,16 @@ function request(stateDir: string) { } as Parameters[0]; } +async function ownerRequest(stateDir: string) { + const host = createTestHostEnvironment(); + const settings = { + ...resolveClientSettings(request(stateDir), undefined, host), + retireIncompatibleContender: true, + }; + await ensureStartedDaemon(settings); + return await createDaemonTransport(host)(request(stateDir)); +} + function pinTo(info: { token: string; pid: number; processStartTime?: string }): DaemonBinding { return { token: info.token, pid: info.pid, processStartTime: info.processStartTime ?? '' }; } @@ -161,9 +175,7 @@ for (const [ownership, reason, message, hint] of [ } const killSpy = vi.spyOn(process, 'kill'); try { - const refusal = await refusalFrom( - createDaemonTransport(createTestHostEnvironment())(request(stateDir)), - ); + const refusal = await refusalFrom(ownerRequest(stateDir)); assert.equal(refusal.details?.reason, reason); assert.equal(refusal.message, message); assert.match(String(refusal.details?.hint), hint); @@ -216,7 +228,7 @@ test('the same record with no host owner is still the takeover this client perfo try { assert.equal(metadata.readDaemonInfo(paths.infoPath)?.ownership, 'detached'); - const response = await createDaemonTransport(createTestHostEnvironment())(request(stateDir)); + const response = await ownerRequest(stateDir); assert.equal(response.ok, true); assert.equal(spawn.mock.calls.length, 1, 'the detached contender was replaced'); @@ -243,7 +255,7 @@ for (const ownership of ['embedded', 'unrecognized', 'detached'] as const) const killSpy = vi.spyOn(process, 'kill'); try { - const response = await createDaemonTransport(createTestHostEnvironment())(request(stateDir)); + const response = await ownerRequest(stateDir); assert.equal(response.ok, true, JSON.stringify(response)); assert.equal(spawn.mock.calls.length, 1, 'the state directory was taken over, not wedged'); @@ -259,26 +271,28 @@ for (const ownership of ['embedded', 'unrecognized', 'detached'] as const) } }); -test('timeout recovery asks only whether this client may, and attach never may', () => { - const { stateDir } = stateDirAndPaths(); - const managed = resolveClientSettings( - request(stateDir), - undefined, - createTestHostEnvironment(), - 'managed', - ); - const attach = resolveClientSettings( - request(stateDir), +test('ordinary requests never authorize timeout retirement', () => { + const settings = resolveClientSettings( + request(stateDirAndPaths().stateDir), undefined, createTestHostEnvironment(), - 'attach', ); - // Recovery is the retirement's judgement, so the client decides only whether it may ask at all: an - // attach client never does, and every other lifecycle asks. The retirement answers for the record's - // owner — a live embedded or unrecognized one is refused without a signal, which - // daemon-registration-embedded-owner.test.ts pins at that seam for both modes. - assert.equal(resolveTimeoutRecovery(managed), 'retire-unresponsive'); - assert.equal(resolveTimeoutRecovery(attach), 'none'); + assert.equal(resolveTimeoutRecovery(settings), 'none'); +}); + +test('a library replay without a state directory attaches instead of owning a private daemon', () => { + const host = createTestHostEnvironment(); + const replay = { session: 'default', command: 'replay', positionals: [], flags: {} }; + const attached = resolveClientSettings(replay, undefined, host); + const owned = resolveClientSettings(replay, undefined, host, undefined, true); + try { + assert.equal(attached.ownedStateDir, undefined); + assert.equal(resolveTimeoutRecovery(attached), 'none'); + assert.ok(owned.ownedStateDir); + assert.equal(resolveTimeoutRecovery(owned), 'retire-unresponsive'); + } finally { + if (owned.ownedStateDir) fs.rmSync(owned.paths.baseDir, { recursive: true, force: true }); + } }); test('a matching pin does not bypass attach compatibility checks', async (t) => { @@ -403,7 +417,6 @@ test('a client that pins a local daemon and names a base URL is refused where se { ...request(stateDirAndPaths().stateDir), flags: { daemonBaseUrl: remote } }, undefined, createTestHostEnvironment(), - 'managed', pin, ), ], @@ -415,7 +428,6 @@ test('a client that pins a local daemon and names a base URL is refused where se request(stateDirAndPaths().stateDir), undefined, createTestHostEnvironment({ env: { AGENT_DEVICE_DAEMON_BASE_URL: remote } }), - 'managed', pin, ), ], @@ -458,12 +470,10 @@ test('a pinned client keeps its hands off the state directory it was given', asy request(stateDir), undefined, createTestHostEnvironment(), - 'managed', pin, ); // A private state directory would hold a daemon nobody started, and a pinned client starts none. - assert.equal(settings.daemonLifecycle, 'attach'); assert.equal(settings.ownedStateDir, undefined); assert.deepEqual(settings.daemonBinding, pin); assert.equal(settings.paths.baseDir, paths.baseDir); diff --git a/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts index d2ad20bbf3..d54c376ce2 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts @@ -32,12 +32,24 @@ vi.mock('@agent-device/host-kit/retry', async (importOriginal) => ({ })); import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import type { DaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; -import { sendToDaemon } from '../index.ts'; +import { sendToDaemon as attach, createEnsuredDaemonTransport } from '../index.ts'; +import { ensureStartedDaemon, resolveClientSettings } from '../daemon-client-lifecycle.ts'; +import { captureHostEnvironment, readProcessStartTime } from '@agent-device/host-kit/process'; + +const ensuredTransport = createEnsuredDaemonTransport(); +async function ensureAndSend(req: Parameters[0]) { + if (req.command === 'replay' || req.command === 'test') return await ensuredTransport(req); + const host = captureHostEnvironment(process); + await ensureStartedDaemon({ + ...resolveClientSettings(req, undefined, host), + retireIncompatibleContender: true, + }); + return await attach(req); +} import { currentDaemonCodeSignature } from './code-signature-fixture.ts'; import { AppError } from '@agent-device/kernel/errors'; import { tryAcquireProcessLock, inspectProcessLock } from '@agent-device/host-kit/file'; import { runCmdDetachedMonitored, runCmdSync } from '@agent-device/host-kit/command'; -import { readProcessStartTime } from '@agent-device/host-kit/process'; import { sleep } from '@agent-device/host-kit/retry'; import { readVersion } from '@agent-device/host-kit/version'; @@ -281,7 +293,7 @@ function mockSocketErrorAfterWrite(failingPort: number): { }; } -test('sendToDaemon retains unknown metadata after a spawn failure', async () => { +test('ensureAndSend retains unknown metadata after a spawn failure', async () => { const stateDir = makeTempStateDir('agent-device-daemon-spawn-retry-'); const paths = resolveDaemonPaths(stateDir); vi.stubEnv('AGENT_DEVICE_STATE_DIR', stateDir); @@ -303,7 +315,7 @@ test('sendToDaemon retains unknown metadata after a spawn failure', async () => try { let thrown: unknown; try { - await sendToDaemon({ + await ensureAndSend({ session: 'default', command: 'spawn-retry-smoke', positionals: [], @@ -332,7 +344,7 @@ test('sendToDaemon retains unknown metadata after a spawn failure', async () => } }); -test('sendToDaemon reports early daemon exit with log tail and startup paths', async () => { +test('ensureAndSend reports early daemon exit with log tail and startup paths', async () => { const stateDir = makeTempStateDir('agent-device-daemon-early-exit-'); const paths = resolveDaemonPaths(stateDir); vi.stubEnv('AGENT_DEVICE_STATE_DIR', stateDir); @@ -351,7 +363,7 @@ test('sendToDaemon reports early daemon exit with log tail and startup paths', a try { let thrown: unknown; try { - await sendToDaemon({ + await ensureAndSend({ session: 'default', command: 'early-exit-smoke', positionals: [], @@ -394,7 +406,7 @@ test('daemon acquisition reclaims a proven reused owner before publication', asy installSpawnedHttpDaemon(paths, daemon.port); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'stale-lock-smoke', positionals: [], @@ -407,7 +419,7 @@ test('daemon acquisition reclaims a proven reused owner before publication', asy assert.equal(mockRunCmdDetached.mock.calls.length, 1); assert.equal(freshLock.state, 'held'); if (freshLock.state === 'held') assert.notEqual(freshLock.owner.startTime, staleStartTime); - assert.deepEqual(daemon.seenPaths, ['GET /health', 'POST /rpc']); + assert.deepEqual(daemon.seenPaths, ['GET /health', 'GET /health', 'POST /rpc']); } finally { if (stale.status === 'acquired') await stale.acquisition.release(); await closeLoopbackServer(daemon.server); @@ -415,7 +427,7 @@ test('daemon acquisition reclaims a proven reused owner before publication', asy } }); -test('sendToDaemon does not reuse reachable daemon metadata with mismatched version or signature', async (t) => { +test('ensureAndSend does not reuse reachable daemon metadata with mismatched version or signature', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const cases: Array<{ @@ -454,7 +466,7 @@ test('sendToDaemon does not reuse reachable daemon metadata with mismatched vers const stderrCapture = beginStderrCapture(); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: `mismatch-${fixture.name}-smoke`, positionals: [], @@ -465,7 +477,7 @@ test('sendToDaemon does not reuse reachable daemon metadata with mismatched vers assert.deepEqual(response, { ok: true, data: { via: 'fresh-daemon' } }); assert.equal(mockRunCmdDetached.mock.calls.length, 1); assert.deepEqual(staleDaemon.seenPaths, []); - assert.deepEqual(freshDaemon.seenPaths, ['GET /health', 'POST /rpc']); + assert.deepEqual(freshDaemon.seenPaths, ['GET /health', 'GET /health', 'POST /rpc']); const staleVersion = fixture.version ?? readVersion(); assert.equal( stderrCapture.read(), @@ -482,7 +494,7 @@ test('sendToDaemon does not reuse reachable daemon metadata with mismatched vers } }); -test('sendToDaemon prints a takeover notice before replacing an unreachable daemon', async (t) => { +test('ensureAndSend prints a takeover notice before replacing an unreachable daemon', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const stateDir = makeTempStateDir('agent-device-daemon-unreachable-takeover-'); @@ -500,7 +512,7 @@ test('sendToDaemon prints a takeover notice before replacing an unreachable daem const stderrCapture = beginStderrCapture(); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'unreachable-takeover-smoke', positionals: [], @@ -520,7 +532,7 @@ test('sendToDaemon prints a takeover notice before replacing an unreachable daem } }); -test('sendToDaemon replaces socket-only daemon metadata when HTTP transport is requested', async (t) => { +test('ensureAndSend replaces socket-only daemon metadata when HTTP transport is requested', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const stateDir = makeTempStateDir('agent-device-daemon-http-takeover-'); @@ -536,7 +548,7 @@ test('sendToDaemon replaces socket-only daemon metadata when HTTP transport is r const stderrCapture = beginStderrCapture(); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'http-takeover-smoke', positionals: [], @@ -546,7 +558,7 @@ test('sendToDaemon replaces socket-only daemon metadata when HTTP transport is r assert.deepEqual(response, { ok: true, data: { via: 'fresh-http-daemon' } }); assert.equal(mockRunCmdDetached.mock.calls.length, 1); - assert.deepEqual(freshDaemon.seenPaths, ['GET /health', 'POST /rpc']); + assert.deepEqual(freshDaemon.seenPaths, ['GET /health', 'GET /health', 'POST /rpc']); assert.equal( stderrCapture.read(), `Replacing daemon (pid 999999, v${readVersion()}) in ${paths.baseDir}: unreachable\n`, @@ -573,7 +585,7 @@ test('sendToDaemon falls back from failed socket transport to HTTP using daemon }); try { - const response = await sendToDaemon({ + const response = await attach({ session: 'default', command: 'transport-fallback-smoke', positionals: [], @@ -609,7 +621,7 @@ test('sendToDaemon does not replay over HTTP after the socket request is written try { let thrown: unknown; try { - await sendToDaemon({ + await attach({ session: 'default', command: 'open', positionals: ['Demo'], @@ -666,7 +678,7 @@ function unheldDivergenceError(): Record { }; } -test('sendToDaemon keeps an owned ephemeral daemon alive and hints its --state-dir on a resumable repair divergence', async (t) => { +test('ensureAndSend keeps an owned ephemeral daemon alive and hints its --state-dir on a resumable repair divergence', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const daemon = await startHttpDaemonErrorFixture(heldDivergenceError()); @@ -676,7 +688,7 @@ test('sendToDaemon keeps an owned ephemeral daemon alive and hints its --state-d }); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'replay', positionals: ['drifted.ad'], @@ -718,7 +730,7 @@ test('C1: keep-alive keys on repairSessionHeld, NOT resume.allowed — a HELD di }); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'replay', positionals: ['drifted.ad'], @@ -737,7 +749,7 @@ test('C1: keep-alive keys on repairSessionHeld, NOT resume.allowed — a HELD di } }); -test('sendToDaemon tears down an owned ephemeral daemon on an UNHELD divergence (no repairSessionHeld signal)', async (t) => { +test('ensureAndSend tears down an owned ephemeral daemon on an UNHELD divergence (no repairSessionHeld signal)', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const daemon = await startHttpDaemonErrorFixture(unheldDivergenceError()); @@ -747,7 +759,7 @@ test('sendToDaemon tears down an owned ephemeral daemon on an UNHELD divergence }); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'replay', positionals: ['drifted.ad'], @@ -796,7 +808,7 @@ test('BLOCKER 2 (third follow-up): a shutdown-time repair commit failure is surf return originalRmdir(target, options); }); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'replay', positionals: ['flow.ad'], @@ -829,7 +841,7 @@ test('BLOCKER 2 (third follow-up): a shutdown-time repair commit failure is surf } }); -test('continuation: sendToDaemon keeps the daemon alive on a held divergence even WITHOUT --save-script on the request', async (t) => { +test('continuation: ensureAndSend keeps the daemon alive on a held divergence even WITHOUT --save-script on the request', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; // The `replay --from` continuation of a repair does NOT repeat --save-script @@ -843,7 +855,7 @@ test('continuation: sendToDaemon keeps the daemon alive on a held divergence eve }); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'replay', positionals: ['drifted.ad'], @@ -889,12 +901,12 @@ function activeReplaySuccessData(overrides: Record = {}): Recor async function replayLeavingSessionActive( daemonPort: number, requestId: string, -): Promise<{ response: Awaited>; ownedStateDir: string }> { +): Promise<{ response: Awaited>; ownedStateDir: string }> { let ownedStateDir = ''; installSpawnedHttpDaemonAtOwnedStateDir(daemonPort, (dir) => { ownedStateDir = dir; }); - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'replay', positionals: ['open-only.ad'], @@ -911,7 +923,7 @@ function parseAddressHint(hint: string): { stateDir: string; session: string } { return { stateDir: match[1] ?? '', session: match[2] ?? '' }; } -test('sendToDaemon keeps an owned ephemeral daemon alive and hints its --state-dir when a close-less replay leaves the session active', async (t) => { +test('ensureAndSend keeps an owned ephemeral daemon alive and hints its --state-dir when a close-less replay leaves the session active', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const daemon = await startHttpDaemonFixture(activeReplaySuccessData()); @@ -947,7 +959,7 @@ test('sendToDaemon keeps an owned ephemeral daemon alive and hints its --state-d } }); -test('closes the loop: a follow-up sendToDaemon using the hinted --state-dir/--session reaches the SAME kept-alive daemon, without spawning a new one', async (t) => { +test('closes the loop: a follow-up ensureAndSend using the hinted --state-dir/--session reaches the SAME kept-alive daemon, without spawning a new one', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const daemon = await startHttpDaemonFixture(activeReplaySuccessData()); @@ -961,7 +973,7 @@ test('closes the loop: a follow-up sendToDaemon using the hinted --state-dir/--s assert.equal(hinted.stateDir, ownedStateDir); const spawnCallsBeforeFollowUp = mockRunCmdDetached.mock.calls.length; - const followUp = await sendToDaemon({ + const followUp = await ensureAndSend({ session: hinted.session, command: 'press', positionals: [], @@ -983,7 +995,7 @@ test('closes the loop: a follow-up sendToDaemon using the hinted --state-dir/--s } }); -test('sendToDaemon tears down an owned ephemeral daemon when replay reports the session was closed (sessionActive: false)', async (t) => { +test('ensureAndSend tears down an owned ephemeral daemon when replay reports the session was closed (sessionActive: false)', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const daemon = await startHttpDaemonFixture(activeReplaySuccessData({ sessionActive: false })); @@ -993,7 +1005,7 @@ test('sendToDaemon tears down an owned ephemeral daemon when replay reports the }); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'replay', positionals: ['closed.ad'], @@ -1031,7 +1043,7 @@ test('ADR 0012 R7 x ADR 0016: a completed --save-script repair also keeps its ow }); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'replay', positionals: ['flow.ad'], @@ -1055,7 +1067,7 @@ test('ADR 0012 R7 x ADR 0016: a completed --save-script repair also keeps its ow } }); -test('issue #1384: sendToDaemon does not stop a client-started daemon at an explicit --state-dir when replay leaves the session active', async (t) => { +test('issue #1384: ensureAndSend does not stop a client-started daemon at an explicit --state-dir when replay leaves the session active', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; // The literal #1384 repro: an explicit AGENT_DEVICE_STATE_DIR/--state-dir @@ -1069,7 +1081,7 @@ test('issue #1384: sendToDaemon does not stop a client-started daemon at an expl installSpawnedHttpDaemon(paths, daemon.port); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'replay', positionals: ['open-only.ad'], @@ -1098,7 +1110,7 @@ test('issue #1384: sendToDaemon does not stop a client-started daemon at an expl } }); -test('sendToDaemon still tears down a `test` command owned ephemeral daemon even if its response data carried sessionActive:true', async (t) => { +test('ensureAndSend still tears down a `test` command owned ephemeral daemon even if its response data carried sessionActive:true', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; // `test` never actually sets this field in practice (its own per-file @@ -1112,7 +1124,7 @@ test('sendToDaemon still tears down a `test` command owned ephemeral daemon even }); try { - const response = await sendToDaemon({ + const response = await ensureAndSend({ session: 'default', command: 'test', positionals: ['suite.ad'], diff --git a/packages/daemon-client/src/__tests__/daemon-client-proxy-upstream.test.ts b/packages/daemon-client/src/__tests__/daemon-client-proxy-upstream.test.ts index b065efa2c6..fb1e1915d9 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-proxy-upstream.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-proxy-upstream.test.ts @@ -3,18 +3,18 @@ import { expect, test, vi } from 'vitest'; import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; -const mocks = vi.hoisted(() => ({ ensureManagedDaemon: vi.fn() })); +const mocks = vi.hoisted(() => ({ ensureStartedDaemon: vi.fn() })); vi.mock('../daemon-client-lifecycle.ts', async (importOriginal) => ({ ...(await importOriginal()), - ensureManagedDaemon: mocks.ensureManagedDaemon, + ensureStartedDaemon: mocks.ensureStartedDaemon, })); import { ensureProxyUpstreamDaemon } from '../daemon-client-proxy-upstream.ts'; test('the proxy upstream is the managed local HTTP daemon of the resolved state dir', async () => { const stateDir = mkdtempForTestSync('agent-device-proxy-upstream-'); - mocks.ensureManagedDaemon.mockResolvedValue({ + mocks.ensureStartedDaemon.mockResolvedValue({ info: { httpPort: 54321, token: 'daemon-secret', pid: 4242 }, startedByClient: false, }); @@ -31,9 +31,9 @@ test('the proxy upstream is the managed local HTTP daemon of the resolved state token: 'daemon-secret', stateDir: resolveDaemonPaths(stateDir).baseDir, }); - const settings = mocks.ensureManagedDaemon.mock.calls[0]![0]; + const settings = mocks.ensureStartedDaemon.mock.calls[0]![0]; expect(settings).toMatchObject({ - daemonLifecycle: 'managed', + retireIncompatibleContender: true, transportPreference: 'http', serverMode: 'http', }); diff --git a/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts b/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts index fa6c00285c..86e4a493d0 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts @@ -21,7 +21,7 @@ import { startHttpDaemonFixture, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; -import { isProcessAlive } from '@agent-device/host-kit/process'; +import { captureHostEnvironment, isProcessAlive } from '@agent-device/host-kit/process'; import { readVersion } from '@agent-device/host-kit/version'; import { spawnRegisteredDaemonFixture, @@ -50,7 +50,17 @@ vi.mock('@agent-device/host-kit/process', async (importOriginal) => { }); import { runCmdDetachedMonitored } from '@agent-device/host-kit/command'; import { sleep } from '@agent-device/host-kit/retry'; -import { sendToDaemon } from '../index.ts'; +import { sendToDaemon as attach } from '../index.ts'; +import { ensureStartedDaemon, resolveClientSettings } from '../daemon-client-lifecycle.ts'; + +async function sendToDaemon(req: Parameters[0]) { + const host = captureHostEnvironment(process); + await ensureStartedDaemon({ + ...resolveClientSettings(req, undefined, host), + retireIncompatibleContender: true, + }); + return await attach(req); +} const actualRetry = await vi.importActual( '@agent-device/host-kit/retry', diff --git a/packages/daemon-client/src/__tests__/daemon-client-startup-race.test.ts b/packages/daemon-client/src/__tests__/daemon-client-startup-race.test.ts index 13f97b6e42..ec9ac51152 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-startup-race.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-startup-race.test.ts @@ -12,6 +12,7 @@ import { import { readVersion } from '@agent-device/host-kit/version'; import { beginStderrCapture, + createTestHostEnvironment, closeLoopbackServer, mkdtempForTestSync, startHttpDaemonFixture, @@ -27,10 +28,15 @@ import { resolveDaemonPaths, type DaemonPaths, } from '@agent-device/daemon-contracts/daemon-resolution'; -import { sendToDaemon } from '../index.ts'; +import { createEnsuredDaemonTransport, sendToDaemon as attachToDaemon } from '../index.ts'; import * as lifecycle from '../daemon-client-lifecycle.ts'; import { DAEMON_STARTUP_EXIT_CODES } from '@agent-device/daemon-contracts/daemon-registration-owner'; +// The startup machinery's owner since 0.22 is the explicit ensure: the CLI and MCP transport ensures +// the shared daemon once and attaches every request to it. Driving it here keeps these startup rows +// on the seam that still starts a daemon; a plain client request only attaches. +const sendToDaemon = createEnsuredDaemonTransport(); + vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({ ...(await importOriginal()), runCmdDetachedMonitored: vi.fn(), @@ -635,7 +641,12 @@ test.for([ }); const stderrCapture = beginStderrCapture(); try { - const pending = sendToDaemon(request(paths)); + const host = createTestHostEnvironment(); + const settings = { + ...lifecycle.resolveClientSettings(request(paths), undefined, host), + retireIncompatibleContender: true, + }; + const pending = lifecycle.ensureStartedDaemon(settings); if (expected.alive) await assert.rejects(pending, (error: unknown) => { assert.ok(error instanceof AppError); @@ -645,12 +656,14 @@ test.for([ return true; }); else { - assert.equal((await pending).ok, true); + assert.equal((await pending).startedByClient, true); await winner.exited; } assert.equal(joined, true); assert.equal(isProcessAlive(winner.pid), expected.alive); assert.equal(spawn.mock.calls.length, expected.launches); + assert.equal(http.rpcRequests.length, 0, 'ensuring never dispatches the request'); + if (!expected.alive) assert.equal((await attachToDaemon(request(paths))).ok, true); assert.equal(http.rpcRequests.length, expected.rpcs); assert.equal( stderrCapture.read().includes(`Replacing daemon (pid ${winner.pid}, v0.0.1)`), @@ -725,7 +738,7 @@ test.for(['default', 'private replay'] as const)( if (await skipWhenLoopbackUnavailable(t)) return; const http = await startHttpDaemonFixture({ devices: [], sessionActive: false }); const defaultPaths = resolveDaemonPaths(mkdtempForTestSync('daemon-missed-birth-')); - const ensure = vi.spyOn(lifecycle, 'ensureManagedDaemon'); + const ensure = vi.spyOn(lifecycle, 'ensureStartedDaemon'); let paths: DaemonPaths | undefined; let child: ReturnType | undefined; let now = Date.now(); @@ -763,8 +776,7 @@ test.for(['default', 'private replay'] as const)( : { session: 'default', command: 'replay', positionals: [], flags: {} }, ); assert.equal(response.ok, true); - assert.equal(ensure.mock.calls.length, 1); - assert.equal((await ensure.mock.results[0]!.value).startedByClient, true); + assert.equal(ensure.mock.calls.length, route === 'private replay' ? 1 : 0); assert.equal(spawn.mock.calls.length, 1); assert.equal(http.rpcRequests.length, 1); assert.ok(paths && child); diff --git a/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts b/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts index 542c7a2516..dfcc022418 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts @@ -364,7 +364,7 @@ for (const row of ROUTE_ROWS) { row.transport === 'remote' ? 'http' : row.transport, statePaths, TIMEOUT_MS, - { host: createTestHostEnvironment() }, + { host: createTestHostEnvironment(), timeoutRecovery: 'retire-unresponsive' }, ), row.hintPattern, ); @@ -412,7 +412,7 @@ test('request-timeout route: a reset never deletes a registration a replacement 'socket', statePaths, TIMEOUT_MS, - { host: createTestHostEnvironment() }, + { host: createTestHostEnvironment(), timeoutRecovery: 'retire-unresponsive' }, ), /The daemon could not be safely retired/, ); @@ -452,7 +452,7 @@ test('a refused timeout fallback preserves the timeout without an unhandled reje 'socket', paths, TIMEOUT_MS, - { host: createTestHostEnvironment() }, + { host: createTestHostEnvironment(), timeoutRecovery: 'retire-unresponsive' }, ), (error: unknown) => { assert.ok(error instanceof AppError); @@ -524,7 +524,7 @@ test('request-timeout route: the reset acts on the resolved state paths, not the 'http', resolvedPaths, TIMEOUT_MS, - { host: createTestHostEnvironment() }, + { host: createTestHostEnvironment(), timeoutRecovery: 'retire-unresponsive' }, ), /The daemon did not answer the liveness probe and was reset after the timeout/, ); diff --git a/packages/daemon-client/src/__tests__/index-host.test.ts b/packages/daemon-client/src/__tests__/index-host.test.ts index a7560f3126..e7ef097a8e 100644 --- a/packages/daemon-client/src/__tests__/index-host.test.ts +++ b/packages/daemon-client/src/__tests__/index-host.test.ts @@ -3,13 +3,6 @@ import { afterEach, expect, test, vi } from 'vitest'; const ensured = vi.hoisted(() => ({ settings: undefined as unknown })); -vi.mock('../daemon-client-lifecycle.ts', async (importOriginal) => ({ - ...(await importOriginal()), - ensureManagedDaemon: async (settings: unknown) => { - ensured.settings = settings; - throw new Error('stop before talking to a daemon'); - }, -})); vi.mock('../daemon-client-startup.ts', async (importOriginal) => ({ ...(await importOriginal()), observeLocalDaemon: async (settings: unknown) => { diff --git a/packages/daemon-client/src/__tests__/index-newer-daemon.test.ts b/packages/daemon-client/src/__tests__/index-newer-daemon.test.ts index afea8bfeae..005f921d51 100644 --- a/packages/daemon-client/src/__tests__/index-newer-daemon.test.ts +++ b/packages/daemon-client/src/__tests__/index-newer-daemon.test.ts @@ -63,7 +63,8 @@ test('sendToDaemon refuses to replace a reachable daemon newer than the client', }), (error: unknown) => { assert.ok(error instanceof AppError); - assert.match(error.message, /v999\.0\.0\) is newer than this client/); + assert.equal(error.details?.reason, 'daemon-incompatible'); + assert.equal(error.details?.mismatch, 'newer'); assert.match(String(error.details?.hint), /agent-device daemon stop --state-dir /); return true; }, @@ -112,7 +113,8 @@ test('sendToDaemon refuses a newer socket-only daemon when the client prefers ht }), (error: unknown) => { assert.ok(error instanceof AppError); - assert.match(error.message, /v999\.0\.0\) is newer than this client/); + assert.equal(error.details?.reason, 'daemon-incompatible'); + assert.equal(error.details?.mismatch, 'newer'); return true; }, ); diff --git a/packages/daemon-client/src/__tests__/index-policy-reuse.test.ts b/packages/daemon-client/src/__tests__/index-policy-reuse.test.ts index 5812ded6dc..d8cc9b7a41 100644 --- a/packages/daemon-client/src/__tests__/index-policy-reuse.test.ts +++ b/packages/daemon-client/src/__tests__/index-policy-reuse.test.ts @@ -21,7 +21,7 @@ import { } from '@agent-device/test-kit'; import { loadDaemonPolicy } from '@agent-device/daemon-contracts/daemon-policy-file'; import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; -import { createDaemonTransport, sendToDaemon } from '../index.ts'; +import { createDaemonTransport, sendToDaemon, ensureProxyUpstreamDaemon } from '../index.ts'; // ADR 0029: a caller that names a daemon policy must not use a daemon that enforces another one. @@ -114,7 +114,11 @@ test('a caller naming a policy refuses a daemon another caller started without i const fixture = await startReusableDaemon({ policyDigest: undefined, publish: 'on-spawn' }); try { await assert.rejects( - () => sendSmoke(fixture.stateDir), + () => + ensureProxyUpstreamDaemon({ + stateDir: fixture.stateDir, + host: { env: process.env, cwd: process.cwd() }, + }), (error: unknown) => { assert.ok(error instanceof AppError); assert.equal(error.details?.reason, 'DAEMON_POLICY_MISMATCH'); diff --git a/packages/daemon-client/src/__tests__/index-stalled-probe.test.ts b/packages/daemon-client/src/__tests__/index-stalled-probe.test.ts index 39fdbe3509..a2e16f09db 100644 --- a/packages/daemon-client/src/__tests__/index-stalled-probe.test.ts +++ b/packages/daemon-client/src/__tests__/index-stalled-probe.test.ts @@ -13,7 +13,7 @@ import { } from '@agent-device/host-kit/process'; import { findProjectRoot, readVersion } from '@agent-device/host-kit/version'; import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; -import { sendToDaemon } from '../index.ts'; +import { sendToDaemon, createEnsuredDaemonTransport } from '../index.ts'; import { closeLoopbackServer, listenOnLoopback, @@ -214,7 +214,8 @@ test('sendToDaemon refuses a live newer daemon whose first probe missed', async () => sendSmoke(stateDir), (error: unknown) => { assert.ok(error instanceof AppError); - assert.equal(error.details?.daemonVersion, NEWER_DAEMON_VERSION); + assert.equal(error.details?.reason, 'daemon-incompatible'); + assert.equal(error.details?.mismatch, 'newer'); return true; }, ); @@ -283,7 +284,12 @@ async function expectDeadDaemonReplaced( return; } - const response = await sendSmoke(stateDir); + const response = await createEnsuredDaemonTransport()({ + session: 'default', + command: 'stalled-probe-smoke', + positionals: [], + flags: { stateDir, daemonTransport: 'socket' }, + }); assert.deepEqual(response, { ok: true, data: { via: 'fresh-daemon' } }); assert.equal(mockSpawnDaemon.mock.calls.length, 1, 'the dead daemon was replaced'); @@ -300,10 +306,10 @@ async function expectDeadDaemonReplaced( } } -test('sendToDaemon replaces a daemon whose process is gone after a single probe', async (t) => { +test('createEnsuredDaemonTransport replaces a daemon whose process is gone after a single probe', async (t) => { await expectDeadDaemonReplaced(t, readVersion()); }); -test('sendToDaemon replaces a newer daemon whose process is gone after a single probe', async (t) => { +test('createEnsuredDaemonTransport replaces a newer daemon whose process is gone after a single probe', async (t) => { await expectDeadDaemonReplaced(t, NEWER_DAEMON_VERSION); }); diff --git a/packages/daemon-client/src/daemon-client-attach.ts b/packages/daemon-client/src/daemon-client-attach.ts index fd9407f802..26e1a35e26 100644 --- a/packages/daemon-client/src/daemon-client-attach.ts +++ b/packages/daemon-client/src/daemon-client-attach.ts @@ -1,5 +1,5 @@ import { AppError } from '@agent-device/kernel/errors'; -import { ensureManagedDaemon } from './daemon-client-lifecycle.ts'; +import { ensureStartedDaemon } from './daemon-client-lifecycle.ts'; import { assertDaemonPolicyMatches, observeLocalDaemon } from './daemon-client-startup.ts'; import type { DaemonClientSettings, @@ -9,13 +9,13 @@ import type { import { daemonBindingMismatchError } from './daemon-client-binding.ts'; import { daemonIncompatibleError, daemonNotRunningError } from './daemon-lifecycle-errors.ts'; -/** Resolves a managed daemon, or observes and verifies the one an attach client may use. */ +/** Resolves a remote or owned daemon, or verifies the daemon an attach client may use. */ export async function connectToDaemon( settings: DaemonClientSettings, healthRecovery?: RemoteHealthRecovery, ): Promise { - if (settings.remoteBaseUrl || settings.daemonLifecycle !== 'attach') { - return await ensureManagedDaemon(settings, healthRecovery); + if (settings.remoteBaseUrl || settings.ownedStateDir) { + return await ensureStartedDaemon(settings, healthRecovery); } const stateDir = settings.paths.baseDir; const observed = await observeLocalDaemon(settings, { refineUnreachable: true }).catch( diff --git a/packages/daemon-client/src/daemon-client-ensuring.ts b/packages/daemon-client/src/daemon-client-ensuring.ts index 7f7e360e3f..11c53f15af 100644 --- a/packages/daemon-client/src/daemon-client-ensuring.ts +++ b/packages/daemon-client/src/daemon-client-ensuring.ts @@ -46,7 +46,7 @@ export function withEnsuredDaemon( const stateDir = resolveDaemonPaths(target.stateDir, { env: host.env, cwd: host.cwd }).baseDir; // A caller that has already given up starts nothing: attaching refuses before any connection. if (context?.signal?.aborted) { - return await transport(req, { ...context, daemonLifecycle: 'attach' }); + return await transport(req, context); } // A finished ensure is kept for the rest of this transport's life. A rejected one is dropped so // the next request retries, and one whose daemon has since gone is dropped by the attach below. @@ -64,7 +64,7 @@ export function withEnsuredDaemon( return { relied: pending }; }; const { relied } = await ensure(); - const attach = async () => await transport(req, { ...context, daemonLifecycle: 'attach' }); + const attach = async () => await transport(req, context); try { return await attach(); } catch (error) { diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index cfea1614d7..c56f51ba75 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -1,14 +1,10 @@ import type { DaemonWireRequest } from '@agent-device/contracts/command'; -import type { - DaemonBinding, - DaemonLifecycle, - EnsureDaemonOptions, -} from '@agent-device/contracts/client'; +import type { DaemonBinding, EnsureDaemonOptions } from '@agent-device/contracts/client'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import net from 'node:net'; import { AppError, normalizeError, type NormalizedError } from '@agent-device/kernel/errors'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; -import { readReplayDivergenceResume } from '@agent-device/ad-replay/divergence'; +import { readReplayDivergenceResume } from '@agent-device/contracts/replay-divergence-data'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { createOwnedReplayStateDir, @@ -40,11 +36,10 @@ export type DaemonClientSettings = { /** The environment and working directory this client reads, for every setting below and the launch. */ host: HostEnvironment; paths: DaemonPaths; - daemonLifecycle: DaemonLifecycle; /** - * Whether a daemon that wins a startup race may be retired when this client cannot use it. A - * managed client may; `ensureDaemon` may not, because it replaces a daemon only through a quiesce - * and judges the winner again instead. + * Whether a daemon that wins a startup race may be retired when this client cannot use it. An + * explicit owner that may start a daemon may; `ensureDaemon` may not, because it replaces a daemon + * only through a quiesce and judges the winner again instead. */ retireIncompatibleContender: boolean; transportPreference: DaemonTransportPreference; @@ -67,23 +62,23 @@ LOOPBACK_BLOCK_LIST.addAddress('::1', 'ipv6'); LOOPBACK_BLOCK_LIST.addSubnet('::ffff:127.0.0.0', 104, 'ipv6'); /** - * Whether a timed-out request may retire the daemon it was waiting on. An attach client never may: the - * daemon is not its to kill, and `ensureDaemon` is where an unresponsive one is replaced. Every other - * caller asks the retirement, which judges the record's owner before it signals anything. + * Whether a timed-out request may retire the daemon it was waiting on. Only the one-shot `replay` or + * `test` request that owns a private state directory may: that daemon answers to no one else, and its + * retirement judges the record's owner before it signals anything. Every other request attaches to a + * daemon it did not start, and `ensureDaemon` is where an unresponsive one is replaced. */ export function resolveTimeoutRecovery( - settings: DaemonClientSettings, + settings: Pick, ): 'retire-unresponsive' | 'none' { - if (settings.daemonLifecycle === 'attach') return 'none'; - return 'retire-unresponsive'; + return settings.ownedStateDir ? 'retire-unresponsive' : 'none'; } export function resolveClientSettings( req: Omit, suppliedAuthToken: string | undefined, host: HostEnvironment, - daemonLifecycle: DaemonLifecycle = 'managed', daemonBinding: DaemonBinding | undefined = undefined, + ownOneShot = false, ): DaemonClientSettings { const explicitStateDir = resolveExplicitStateDir(req, host.env); const remote = resolveRemoteClientSettings(req, suppliedAuthToken, host.env); @@ -101,12 +96,13 @@ export function resolveClientSettings( }, ); } - if (daemonBinding) daemonLifecycle = 'attach'; const transport = resolveTransportClientSettings(req.flags, remote.remoteBaseUrl, host.env); - // An attach client owns no daemon, and a private state directory would hold one nobody started. A - // pinned client owns one neither: it uses the instance it was given and starts nothing. + // A one-shot `replay` or `test` with no explicit state directory runs on a private daemon of its + // own: this request starts it, attaches to it, and retires it when it finishes. Nothing else does. + // A pinned client owns one neither: it uses the instance it was given and starts nothing. const ownedStateDir = - daemonLifecycle !== 'attach' && + ownOneShot && + daemonBinding === undefined && shouldUseOwnedReplayStateDir(req, explicitStateDir, remote.rawBaseUrl) ? createOwnedReplayStateDir() : undefined; @@ -115,8 +111,7 @@ export function resolveClientSettings( paths: ownedStateDir?.paths ?? resolveDaemonPaths(explicitStateDir, { env: host.env, cwd: host.cwd }), - daemonLifecycle, - retireIncompatibleContender: true, + retireIncompatibleContender: ownedStateDir !== undefined, transportPreference: transport.preference, serverMode: transport.serverMode, ownedStateDir, @@ -164,7 +159,8 @@ export function resolveLocalDaemonSettings( env: host.env, cwd: host.cwd, }), - daemonLifecycle: 'managed', + // `ensureDaemon` replaces a daemon only through a quiesce, so a contender it cannot use is + // judged again, never retired by this call. retireIncompatibleContender: false, transportPreference: transport.preference, serverMode: transport.serverMode, @@ -226,16 +222,13 @@ function shouldUseOwnedReplayStateDir( return isOneShotReplayCommand(req.command) && !explicitStateDir && !rawRemoteBaseUrl; } -/** - * How long the remote `/health` gate may re-probe a daemon that is there but not ready: the budget - * of the command waiting behind it. Without one, the first failed probe refuses. - */ +/** The command budget for recovering a remote daemon health probe. */ export type RemoteHealthRecovery = { budgetMs: number; signal: AbortSignal | undefined; }; -export async function ensureManagedDaemon( +export async function ensureStartedDaemon( settings: DaemonClientSettings, healthRecovery?: RemoteHealthRecovery, ): Promise { @@ -243,13 +236,13 @@ export async function ensureManagedDaemon( return await ensureRemoteDaemon(settings, healthRecovery); } - const ensured = await ensureLocalDaemon(settings); + const ensured = await startOrReuseLocalDaemon(settings); // Checked on both branches: a startup can resolve to a daemon another caller raced in. await assertDaemonPolicyMatches(ensured.info, settings.paths.baseDir, settings.host); return ensured; } -async function ensureLocalDaemon(settings: DaemonClientSettings): Promise { +async function startOrReuseLocalDaemon(settings: DaemonClientSettings): Promise { const reusable = await readReusableLocalDaemon(settings); if (reusable) return { info: reusable, startedByClient: false }; @@ -258,7 +251,7 @@ async function ensureLocalDaemon(settings: DaemonClientSettings): Promise { const remoteInfo: DaemonInfo = { transport: 'http', diff --git a/packages/daemon-client/src/daemon-client-proxy-upstream.ts b/packages/daemon-client/src/daemon-client-proxy-upstream.ts index 49dce4b81c..2beda96f7e 100644 --- a/packages/daemon-client/src/daemon-client-proxy-upstream.ts +++ b/packages/daemon-client/src/daemon-client-proxy-upstream.ts @@ -1,5 +1,5 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import { ensureManagedDaemon, resolveClientSettings } from './daemon-client-lifecycle.ts'; +import { ensureStartedDaemon, resolveClientSettings } from './daemon-client-lifecycle.ts'; export type ProxyUpstreamDaemonOptions = { stateDir?: string; @@ -15,22 +15,27 @@ export type ProxyUpstreamDaemon = { export async function ensureProxyUpstreamDaemon( options: ProxyUpstreamDaemonOptions, ): Promise { - const settings = resolveClientSettings( - { - session: 'default', - command: 'proxy', - positionals: [], - flags: { - stateDir: options.stateDir, - daemonBaseUrl: '', - daemonTransport: 'http', - daemonServerMode: 'http', + // `proxy` owns the local daemon it forwards to: it starts a missing one and may retire a startup + // contender it cannot use. A client request never takes this path. + const settings = { + ...resolveClientSettings( + { + session: 'default', + command: 'proxy', + positionals: [], + flags: { + stateDir: options.stateDir, + daemonBaseUrl: '', + daemonTransport: 'http', + daemonServerMode: 'http', + }, }, - }, - undefined, - options.host, - ); - const daemon = await ensureManagedDaemon(settings); + undefined, + options.host, + ), + retireIncompatibleContender: true, + }; + const daemon = await ensureStartedDaemon(settings); return { httpPort: daemon.info.httpPort, token: daemon.info.token, diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index efd31c2c46..8eb1d37a30 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -47,9 +47,10 @@ type SendRequestOptions = { */ signal?: AbortSignal; /** - * What a timed-out request may do to the daemon. `retire-unresponsive`, the default, lets the - * liveness probe retire a daemon that answers nothing; `none` leaves every daemon alone, which is - * how an attach client and the quiesce request itself time out. + * What a timed-out request may do to the daemon. `none`, the default, leaves every daemon alone, + * which is how an attach client, a lease beat and the quiesce request itself time out. + * `retire-unresponsive` lets the liveness probe retire a daemon that answers nothing, and only the + * one-shot `replay` or `test` owner of a private state directory asks for it. */ timeoutRecovery?: 'retire-unresponsive' | 'none'; }; @@ -420,7 +421,7 @@ async function recoverFromTimeout( return await handleRequestTimeout({ info, statePaths, - retireUnresponsive: options.timeoutRecovery !== 'none', + retireUnresponsive: options.timeoutRecovery === 'retire-unresponsive', requestSent: error.details.daemonRequestSent !== false, ...timeoutRequestContext(req, isRemoteDaemon(info), expiredBudget), }); diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 0f3a533c51..4e0362d083 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -71,6 +71,7 @@ async function sendToDaemonOnHost( req: Omit, options: DaemonTransportOptions, host: HostEnvironment, + ownOneShot = false, ): Promise { const { resolveClientSettings, resolveTimeoutRecovery, attachSessionAddressHints } = await import('./daemon-client-lifecycle.ts'); @@ -89,8 +90,8 @@ async function sendToDaemonOnHost( requestWithoutAuthFlag, options.authToken ?? flagAuthToken, host, - options.daemonLifecycle, options.daemonBinding, + ownOneShot, ); const requestTimeoutMs = resolveCommandRequestTimeoutMs( resolveCommandTimeoutPolicy(requestWithoutAuthFlag.command), @@ -194,7 +195,16 @@ export function createEnsuredDaemonTransport( let ensured: Promise | undefined; return async (req, context) => { ensured ??= import('./daemon-client-ensuring.ts').then(({ withEnsuredDaemon }) => - withEnsuredDaemon(options.host ? createDaemonTransport(options.host) : sendToDaemon, options), + withEnsuredDaemon( + async (request, context) => + await sendToDaemonOnHost( + request, + context ?? {}, + options.host ?? captureHostEnvironment(process), + true, + ), + options, + ), ); return await ( await ensured @@ -454,7 +464,7 @@ export async function resolveLocalDaemonCodeIdentity(): Promise { diff --git a/packages/daemon-client/tsconfig.json b/packages/daemon-client/tsconfig.json index 0cbd24bfa4..361fd7043f 100644 --- a/packages/daemon-client/tsconfig.json +++ b/packages/daemon-client/tsconfig.json @@ -11,7 +11,6 @@ }, "include": ["src"], "references": [ - { "path": "../ad-replay" }, { "path": "../command-registry" }, { "path": "../contracts" }, { "path": "../daemon-contracts" }, diff --git a/packages/daemon/package.json b/packages/daemon/package.json index 2558eb9069..2694d82ed7 100644 --- a/packages/daemon/package.json +++ b/packages/daemon/package.json @@ -5,7 +5,6 @@ "type": "module", "description": "The agent-device daemon server: request routing, sessions, leases, device claims, snapshot and interaction handling. Internal workspace package bundled into the published agent-device artifact (#3352 daemon extraction).", "dependencies": { - "@agent-device/ad-replay": "workspace:*", "@agent-device/ad-script": "workspace:*", "@agent-device/capture-kit": "workspace:*", "@agent-device/command-registry": "workspace:*", @@ -14,12 +13,10 @@ "@agent-device/device-selection": "workspace:*", "@agent-device/host-kit": "workspace:*", "@agent-device/kernel": "workspace:*", - "@agent-device/maestro": "workspace:*", "@agent-device/platform-android": "workspace:*", "@agent-device/platform-apple": "workspace:*", "@agent-device/platform-web": "workspace:*", "@agent-device/replay-port": "workspace:*", - "@agent-device/replay-test": "workspace:*", "@agent-device/selectors": "workspace:*", "@agent-device/session-journal": "workspace:*" }, @@ -31,7 +28,11 @@ "fast-check": "^4.9.0", "oxc-parser": "^0.146.0", "vitest": "5.0.4", - "yaml": "^2.9.0" + "yaml": "^2.9.0", + "@agent-device/maestro": "workspace:*", + "@agent-device/ad-replay": "workspace:*", + "@agent-device/plugins": "workspace:*", + "@agent-device/replay": "workspace:*" }, "exports": { ".": { diff --git a/packages/daemon/src/__tests__/support/replay-script-source-fixture.ts b/packages/daemon/src/__tests__/support/replay-script-source-fixture.ts index 8e23bf18ce..6126f50c76 100644 --- a/packages/daemon/src/__tests__/support/replay-script-source-fixture.ts +++ b/packages/daemon/src/__tests__/support/replay-script-source-fixture.ts @@ -16,6 +16,7 @@ export async function maestroScriptSourceBundleFor( filePath: string, ): Promise { return await loadReplayScriptSourceBundle({ + hostEnv: process.env, inputPath: filePath, cwd: process.cwd(), replayBackend: 'maestro', @@ -48,6 +49,7 @@ export async function withClientReplayScriptSources( if (req.flags?.replayScriptSource) return req; return withFlags(req, { replayScriptSource: await loadReplayScriptSourceBundle({ + hostEnv: process.env, inputPath: entryPath, cwd, replayBackend, @@ -59,7 +61,12 @@ export async function withClientReplayScriptSources( replayScriptSources: await Promise.all( discoverReplaySourcePaths({ inputs, cwd, replayBackend }).map( async (inputPath) => - await loadReplayScriptSourceBundle({ inputPath, cwd, replayBackend }), + await loadReplayScriptSourceBundle({ + hostEnv: process.env, + inputPath, + cwd, + replayBackend, + }), ), ), }); diff --git a/packages/daemon/src/core/__tests__/daemon-command-registry.test.ts b/packages/daemon/src/core/__tests__/daemon-command-registry.test.ts index 6923ad850e..91dbd20ca6 100644 --- a/packages/daemon/src/core/__tests__/daemon-command-registry.test.ts +++ b/packages/daemon/src/core/__tests__/daemon-command-registry.test.ts @@ -4,8 +4,10 @@ import { INTERNAL_COMMANDS, PUBLIC_COMMANDS } from '@agent-device/command-regist import { canOverrideLockPolicySelector, canRunReplayScopedAction, + DAEMON_COMMAND_DESCRIPTORS, getDaemonCommandRoute, getSessionCommandKind, + ignoresSessionLease, isHumanControlMutation, isReadOnlyRequest, isLeaseAdmissionExempt, @@ -20,6 +22,22 @@ import { } from '../daemon-command-registry.ts'; import type { DaemonRequest } from '../daemon-request.ts'; +test('only the commands that never touch their session ignore its lease', () => { + assert.deepEqual( + DAEMON_COMMAND_DESCRIPTORS.map(({ command }) => command) + .filter(ignoresSessionLease) + .sort(), + [ + PUBLIC_COMMANDS.devices, + INTERNAL_COMMANDS.leaseAllocate, + INTERNAL_COMMANDS.leaseHeartbeat, + INTERNAL_COMMANDS.leaseRelease, + INTERNAL_COMMANDS.releaseMaterializedPaths, + INTERNAL_COMMANDS.sessionList, + ].sort(), + ); +}); + test('daemon command registry owns specialized handler routes', () => { assert.equal(getDaemonCommandRoute(INTERNAL_COMMANDS.humanControl), 'humanControl'); for (const command of [ diff --git a/packages/daemon/src/core/__tests__/execution-plan.test.ts b/packages/daemon/src/core/__tests__/execution-plan.test.ts index 0a9481930d..191664daca 100644 --- a/packages/daemon/src/core/__tests__/execution-plan.test.ts +++ b/packages/daemon/src/core/__tests__/execution-plan.test.ts @@ -47,3 +47,25 @@ test('batch steps carry the steps still ahead of them through the internal chann { command: 'snapshot', remaining: [] }, ]); }); + +test.each([ + ['keep', { sessionOmitted: true } as const, true], + ['do not gain', undefined, undefined], +])('batch steps %s the marker for an unnamed session', async (_label, internal, sessionOmitted) => { + const seen: unknown[] = []; + const req: DaemonRequest = { + token: 'token', + session: 'default', + command: 'batch', + positionals: [], + flags: { batchSteps: [{ command: 'snapshot' }] }, + ...(internal ? { internal } : {}), + }; + + await runBatchCommands(req, 'default', async (stepRequest) => { + seen.push(stepRequest.internal?.sessionOmitted); + return { ok: true, data: {} }; + }); + + assert.deepEqual(seen, [sessionOmitted]); +}); diff --git a/packages/daemon/src/core/composite-resource-admission-ime.test.ts b/packages/daemon/src/core/composite-resource-admission-ime.test.ts index 587629c4ba..f27ad683ac 100644 --- a/packages/daemon/src/core/composite-resource-admission-ime.test.ts +++ b/packages/daemon/src/core/composite-resource-admission-ime.test.ts @@ -1,3 +1,4 @@ +import { getReplayBackend } from '@agent-device/replay-port/replay-backend-registry'; import fs from 'node:fs'; import path from 'node:path'; import { afterEach, expect, test, vi } from 'vitest'; @@ -75,7 +76,10 @@ test.each(['batch', 'replay'] as const)( test('Maestro stop keeps the IME and app log; capture still bars caller close', async () => { const helper = androidHelperWorld(); - const world = await resourceAdmissionWorld('capture', { ime: helper.ime }); + const world = await resourceAdmissionWorld('capture', { + ime: helper.ime, + replayBackend: await getReplayBackend('maestro'), + }); try { assertRpcOk(await world.call('open', ['com.android.settings'], { testIme: true })); assertRpcOk(await world.call('logs', ['start'])); diff --git a/packages/daemon/src/core/composite-resource-admission.fixtures.ts b/packages/daemon/src/core/composite-resource-admission.fixtures.ts index e852c3ef04..7ec6fc4a89 100644 --- a/packages/daemon/src/core/composite-resource-admission.fixtures.ts +++ b/packages/daemon/src/core/composite-resource-admission.fixtures.ts @@ -1,3 +1,7 @@ +import replayPlugin from '@agent-device/replay/agent-device'; +import { resolveProviderPlugins, startProviderRegistry } from '@agent-device/plugins/registry'; +import { bindReplayBackendResolver } from '@agent-device/replay-port/replay-backend-registry'; +import type { ReplayBackend } from '@agent-device/contracts/replay-backend'; import path from 'node:path'; import { LeaseRegistry } from '../resources/lease-registry.ts'; import { applicationLifecycleRuntimeFixture } from '../__tests__/support/application-lifecycle-runtime-fixture.ts'; @@ -29,6 +33,7 @@ export async function resourceAdmissionWorld( audioMode: 'capture' | 'query' = 'capture', options: Readonly<{ device?: DeviceInfo; + replayBackend?: ReplayBackend; providerOwned?: boolean; withLifecycleProvider?: boolean; ime?: { @@ -188,9 +193,40 @@ export async function resourceAdmissionWorld( stdout: { write: () => {} }, stderr: { write: () => {} }, composeDeps: async (input) => { + const backend = options.replayBackend; + const registry = await startProviderRegistry( + await resolveProviderPlugins([ + { source: 'embedder', load: replayPlugin }, + ...(backend + ? [ + { + source: 'embedder' as const, + load: () => ({ + apiVersion: 2, + kind: 'replay-backend', + backend: backend.id, + setup: () => ({ replayBackend: { create: () => backend } }), + }), + }, + ] + : []), + ]), + input.host, + { + adaptWebDriver: async () => { + throw new Error('Resource fixture cannot create providers'); + }, + }, + ); + await bindReplayBackendResolver( + registry.resolveReplayBackend, + registry.resolveReplayExecution, + ); const base = await daemonRuntimeDepsFixture()(input); return { ...base, + pluginInventory: registry.inventory, + shutdownProviderRuntimes: registry.close, ...((options.withLifecycleProvider ?? options.providerOwned) ? { leaseLifecycleProvider: { release: providerRelease } } : {}), diff --git a/packages/daemon/src/core/daemon-command-registry.ts b/packages/daemon/src/core/daemon-command-registry.ts index 1a018a32e4..e02f8bd7dc 100644 --- a/packages/daemon/src/core/daemon-command-registry.ts +++ b/packages/daemon/src/core/daemon-command-registry.ts @@ -66,6 +66,10 @@ export function isLeaseAdmissionExempt(command: string): boolean { return getDaemonCommandDescriptor(command)?.leaseAdmissionExempt === true; } +export function ignoresSessionLease(command: string): boolean { + return getDaemonCommandDescriptor(command)?.ignoresSessionLease === true; +} + export function isAppLeaseAllowed(command: string): boolean { return getDaemonCommandDescriptor(command)?.appLease === 'allowed'; } diff --git a/packages/daemon/src/core/daemon-request.ts b/packages/daemon/src/core/daemon-request.ts index c541c252fa..1ad6514658 100644 --- a/packages/daemon/src/core/daemon-request.ts +++ b/packages/daemon/src/core/daemon-request.ts @@ -46,6 +46,12 @@ type DaemonRequestInternal = ReplayDispatchOptions & { */ retainDeviceExecutionLock?: (deviceId: string) => Promise; admittedLease?: DeviceLease; + /** + * The caller named no session. Set by `resolveRequestSessionAtIntake`, because the defaulted name + * cannot be told apart from a chosen one afterwards, and copied onto batch steps by + * `session-batch`. + */ + sessionOmitted?: true; /** * ADR 0014 / #1654: the complete ref/node/tree target a mutating `find` * resolved against its fresh capture. Its presence both marks the ref as diff --git a/packages/daemon/src/core/explicit-session-resolution.ts b/packages/daemon/src/core/explicit-session-resolution.ts index b33ee79512..2c8fb58d2f 100644 --- a/packages/daemon/src/core/explicit-session-resolution.ts +++ b/packages/daemon/src/core/explicit-session-resolution.ts @@ -1,6 +1,6 @@ import type { DaemonWireRequest } from '@agent-device/contracts/command'; import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell'; -import { namesSessionExplicitly } from '@agent-device/kernel/contracts'; +import { namesSessionExplicitly } from '@agent-device/kernel/record'; import { AppError, namedSessionNotFoundDetails, @@ -41,7 +41,7 @@ export function namedSessionNotFoundError(sessionAddress: string): AppError { * Two shapes keep the path they chose: a request that never named a session, which is using the * daemon sessionlessly by design, and one that names a device selector as well, which states its * target outright and needs no session to supply one. The predicate deciding the first is - * `namesSessionExplicitly` (`@agent-device/kernel/contracts`), traced from what the request carries + * `namesSessionExplicitly` (`@agent-device/kernel/record`), traced from what the request carries * rather than from the session string. */ export function requireNamedSessionHoldsDevice( diff --git a/packages/daemon/src/core/request-session-intake.test.ts b/packages/daemon/src/core/request-session-intake.test.ts new file mode 100644 index 0000000000..c1a9e26dd9 --- /dev/null +++ b/packages/daemon/src/core/request-session-intake.test.ts @@ -0,0 +1,30 @@ +import { expect, test } from 'vitest'; +import { resolveRequestSessionAtIntake } from './request-session-intake.ts'; + +const OMITTED = { internal: { sessionOmitted: true } }; + +test.each([ + ['a missing session', {}, { session: 'default', ...OMITTED }], + ['a blank session', { session: ' ' }, { session: ' ', ...OMITTED }], + ['an empty session', { session: '' }, { session: '', ...OMITTED }], + ['a session that is not a string', { session: 7 }, { session: 'default', ...OMITTED }], + [ + 'the literal default from a client that named none', + { session: 'default', meta: { sessionExplicit: false } }, + { session: 'default', ...OMITTED }, + ], + [ + 'a client that names the default session in its meta', + { session: 'default', meta: { sessionExplicit: true } }, + { session: 'default' }, + ], + [ + 'a client that names its session in its flags', + { session: 'default', flags: { session: 'default' }, meta: { sessionExplicit: false } }, + { session: 'default' }, + ], + ['a caller that predates the fact', { session: 'default' }, { session: 'default' }], + ['a named session', { session: 'agent-a' }, { session: 'agent-a' }], +])('intake reads %s', (_label, request, expected) => { + expect(resolveRequestSessionAtIntake(request)).toEqual(expected); +}); diff --git a/packages/daemon/src/core/request-session-intake.ts b/packages/daemon/src/core/request-session-intake.ts new file mode 100644 index 0000000000..0da852adfe --- /dev/null +++ b/packages/daemon/src/core/request-session-intake.ts @@ -0,0 +1,25 @@ +import { namesSessionExplicitly } from '@agent-device/kernel/record'; +import type { DaemonRequest } from './daemon-request.ts'; + +/** + * What a transport takes from a request's session: the name it runs under, and whether the caller + * named one at all. A missing session runs under `default`. A blank one names no session but keeps + * its literal, so a command that validates the name, such as a web open, still refuses it. The Node + * client always sends `default` and reports the omission in `meta.sessionExplicit`, so the literal + * stays and cwd-scoped routing keeps reading it. A caller on neither carrier predates the fact and + * counts as named. + */ +export function resolveRequestSessionAtIntake(request: { + session?: unknown; + flags?: { session?: unknown } | Record; + meta?: { sessionExplicit?: boolean | undefined }; +}): Pick { + const literal = typeof request.session === 'string' ? request.session : undefined; + const named = literal !== undefined && literal.trim().length > 0; + const omitted = + !named || (request.meta?.sessionExplicit === false && !namesSessionExplicitly(request)); + return { + session: literal ?? 'default', + ...(omitted ? { internal: { sessionOmitted: true } } : {}), + }; +} diff --git a/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts b/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts index f8ef230be4..1d4dc7d6ee 100644 --- a/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts +++ b/packages/daemon/src/server/__tests__/http-server-rpc-validation.test.ts @@ -126,6 +126,7 @@ test('the rpc boundary never accepts internal request fields from the wire', asy id: 'req-1', method: 'agent_device.command', params: { + session: 'agent-a', command: 'snapshot', positionals: [], internal: { @@ -339,6 +340,7 @@ test('local command RPC keeps host paths unrestricted', async (t) => { try { const port = await listenOnLoopback(server); const response = await postCommandRpc(port, { + session: 'agent-a', command: 'install_source', positionals: [], flags: { platform: 'android' }, @@ -355,6 +357,50 @@ test('local command RPC keeps host paths unrestricted', async (t) => { } }); +test.for([ + ['omitted', {}, 'default', true], + ['blank', { session: ' ' }, ' ', true], + ['named', { session: 'agent-a' }, 'agent-a', undefined], +] as const)( + 'install_from_source records a session that is %s', + async ([_label, session, resolvedSession, sessionOmitted], t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + + const received: DaemonRequest[] = []; + const server = await createDaemonHttpServer({ + handleRequest: async (req) => { + received.push(req); + return { ok: true, data: {} }; + }, + env: process.env, + cwd: process.cwd(), + }); + + try { + const port = await listenOnLoopback(server); + await fetch(`http://127.0.0.1:${port}/rpc`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 'req-1', + method: 'agent_device.install_from_source', + params: { + ...session, + platform: 'android', + source: { kind: 'url', url: 'https://example.com/app.apk' }, + }, + }), + }); + assert.equal(received.length, 1); + assert.equal(received[0]?.session, resolvedSession); + assert.equal(received[0]?.internal?.sessionOmitted, sessionOmitted); + } finally { + await closeLoopbackServer(server); + } + }, +); + test('lease.allocate forwards retainOnClose to the handler as lease meta', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; const received: DaemonRequest[] = []; diff --git a/packages/daemon/src/server/__tests__/request-execution-scope-unnamed-session.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope-unnamed-session.test.ts new file mode 100644 index 0000000000..e5d925e16a --- /dev/null +++ b/packages/daemon/src/server/__tests__/request-execution-scope-unnamed-session.test.ts @@ -0,0 +1,132 @@ +import { bindTestCommandHost, createTestHostEnvironment } from '@agent-device/test-kit'; +import { expect, test, vi } from 'vitest'; +import { + daemonClaimRecoveryGatewayFixture, + daemonPlatformServicesFixture, +} from '../../__tests__/support/platform-services-fixture.ts'; +import { makeIosSession } from '../../__tests__/support/session-factories.ts'; +import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; +import { + platformRequestScopeFixture, + unavailableDeviceRuntimeGateway, +} from '../../__tests__/support/unavailable-device-runtime-gateway.ts'; +import type { DaemonRequest } from '../../core/daemon-request.ts'; +import { LeaseRegistry } from '../../resources/lease-registry.ts'; +import { createRequestExecutionScope } from '../request-execution-scope.ts'; + +bindTestCommandHost(); + +function createTestRequestScope( + params: Pick< + Parameters[0], + 'req' | 'sessionStore' | 'leaseRegistry' + >, +) { + return createRequestExecutionScope({ + host: createTestHostEnvironment(), + ...params, + platformServices: daemonPlatformServicesFixture(), + claimRecoveryGateway: daemonClaimRecoveryGatewayFixture(), + deviceRuntimeGateway: unavailableDeviceRuntimeGateway, + platformRequestScope: platformRequestScopeFixture(), + }); +} + +function makeRequest(overrides: Partial = {}): DaemonRequest { + return { + token: 'test-token', + session: 'default', + command: 'snapshot', + positionals: [], + ...overrides, + }; +} + +function publishProviderLeasedDefaultSession( + sessionStore: ReturnType, + leaseRegistry: LeaseRegistry, +): void { + const lease = leaseRegistry.allocateLease({ + tenantId: 'tenant-a', + runId: 'run-1', + leaseProvider: 'proxy', + clientId: 'client-a', + deviceKey: 'ios:sim-1', + }); + sessionStore.publish( + 'default', + makeIosSession('default', { + lease: { + leaseId: lease.leaseId, + tenantId: lease.tenantId, + runId: lease.runId, + leaseBackend: lease.backend, + leaseProvider: 'proxy', + clientId: 'client-a', + deviceKey: 'ios:sim-1', + expiresAt: lease.expiresAt, + }, + }), + ); +} + +test.each(['snapshot', 'artifacts', 'events', 'logs', 'doctor', 'capabilities'])( + 'an unnamed %s cannot reach the provider lease another caller left on the default session', + async (command) => { + const sessionStore = makeSessionStore('agent-device-request-scope-'); + const leaseRegistry = new LeaseRegistry(); + publishProviderLeasedDefaultSession(sessionStore, leaseRegistry); + const dispatch = vi.fn(async () => 'ran'); + + const run = async () => { + const scope = await createTestRequestScope({ + req: makeRequest({ command, internal: { sessionOmitted: true } }), + sessionStore, + leaseRegistry, + }); + return await scope.runLocked(dispatch); + }; + + await expect(run()).rejects.toMatchObject({ + code: 'INVALID_ARGS', + details: { reason: 'REMOTE_SESSION_REQUIRED', leaseProvider: 'proxy' }, + }); + expect(dispatch).not.toHaveBeenCalled(); + }, +); + +test('an unnamed command is refused when the session gains a provider lease after the first check', async () => { + const sessionStore = makeSessionStore('agent-device-request-scope-'); + const leaseRegistry = new LeaseRegistry(); + const dispatch = vi.fn(async () => 'ran'); + const scope = await createTestRequestScope({ + req: makeRequest({ internal: { sessionOmitted: true } }), + sessionStore, + leaseRegistry, + }); + + publishProviderLeasedDefaultSession(sessionStore, leaseRegistry); + + await expect(scope.runLocked(dispatch)).rejects.toMatchObject({ + code: 'INVALID_ARGS', + details: { reason: 'REMOTE_SESSION_REQUIRED', leaseProvider: 'proxy' }, + }); + expect(dispatch).not.toHaveBeenCalled(); +}); + +test.each(['session_list', 'devices', 'release_materialized_paths'])( + 'an unnamed %s still answers while the default session holds a provider lease', + async (command) => { + const sessionStore = makeSessionStore('agent-device-request-scope-'); + const leaseRegistry = new LeaseRegistry(); + publishProviderLeasedDefaultSession(sessionStore, leaseRegistry); + + const scope = await createTestRequestScope({ + req: makeRequest({ command, internal: { sessionOmitted: true } }), + sessionStore, + leaseRegistry, + }); + + await expect(scope.runLocked(async () => 'ran')).resolves.toBe('ran'); + }, +); diff --git a/packages/daemon/src/server/__tests__/request-router-android-foreground-evidence.test.ts b/packages/daemon/src/server/__tests__/request-router-android-foreground-evidence.test.ts new file mode 100644 index 0000000000..5702f5ded7 --- /dev/null +++ b/packages/daemon/src/server/__tests__/request-router-android-foreground-evidence.test.ts @@ -0,0 +1,97 @@ +import { test, expect, vi } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { createTestDeviceInventoryGateways } from '@agent-device/device-selection/inventory-gateways-fixtures'; +import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { AppError } from '@agent-device/kernel/errors'; +import { getResolveTargetDeviceMock } from '../../__tests__/support/request-router-dispatch-mocks.ts'; +import { fakeCreateCommandSurface } from '../../__tests__/support/command-surface-fake.ts'; +import { dispatchApplicationLifecycleEffect } from '../../__tests__/support/application-lifecycle-runtime-fixture.ts'; +import { + createRequestHandler, + lifecycleDeviceRuntimeGateway, +} from '../../__tests__/support/test-device-runtime-gateway.ts'; +import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; +import { LeaseRegistry } from '../../resources/lease-registry.ts'; +import { makeAndroidDevice, openRequest } from './request-router-open-harness.ts'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; + +vi.mock('../../core/device/device-ready.ts', () => ({ + ensureDeviceReady: vi.fn(async () => {}), +})); +const mockResolveTargetDevice = vi.mocked(getResolveTargetDeviceMock()); +function createOpenHandler(sessionStore: ReturnType) { + return createRequestHandler({ + host: createTestHostEnvironment(), + createCommandSurface: fakeCreateCommandSurface, + logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'), + token: 'test-token', + sessionStore, + leaseRegistry: new LeaseRegistry(), + deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, + deviceInventoryGateways: createTestDeviceInventoryGateways(), + trackDownloadableArtifact: () => 'artifact-id', + }); +} + +test('open relaunch retains Android foreground probe failure in the serialized response and request artifact', async () => { + const device = makeAndroidDevice('emulator-fence'); + const failure = new AppError( + 'COMMAND_FAILED', + 'probe failed', + { reason: 'probe-failed' }, + new Error('root cause'), + ); + try { + const sessionStore = makeSessionStore('android-fence-request-'); + mockResolveTargetDevice.mockResolvedValue(device); + vi.mocked(dispatchApplicationLifecycleEffect).mockImplementationOnce(async () => { + emitDiagnostic({ + phase: 'android_close_foreground_fence', + data: { + initialProcessCount: 1, + observations: [{ startMs: 0, endMs: 10, remainingMs: 1990, result: 'error' }], + }, + }); + throw failure; + }); + const response = await createOpenHandler(sessionStore)( + openRequest('fence-session', { platform: 'android', relaunch: true }, 'fence-request', {}, [ + 'com.example.app', + ]), + ); + expect(response.ok).toBe(false); + if (response.ok) throw new Error('expected failure'); + const wire = JSON.parse(JSON.stringify(response)); + expect(wire.error).toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'probe-failed' }, + }); + expect(response.error.logPath).toBe( + path.join( + sessionStore.resolveDaemonStateDir(), + 'sessions', + 'fence-session', + 'requests', + 'fence-request.ndjson', + ), + ); + const events = fs + .readFileSync(response.error.logPath!, 'utf8') + .trim() + .split('\n') + .map((line) => JSON.parse(line)); + expect(events).toContainEqual( + expect.objectContaining({ + phase: 'android_close_foreground_fence', + data: { + initialProcessCount: 1, + observations: [{ startMs: 0, endMs: 10, remainingMs: 1990, result: 'error' }], + }, + }), + ); + expect(events).toContainEqual(expect.objectContaining({ phase: 'request_failed' })); + } finally { + vi.mocked(dispatchApplicationLifecycleEffect).mockReset(); + } +}); diff --git a/packages/daemon/src/server/__tests__/request-router-replay-plugin.test.ts b/packages/daemon/src/server/__tests__/request-router-replay-plugin.test.ts new file mode 100644 index 0000000000..ad297276f5 --- /dev/null +++ b/packages/daemon/src/server/__tests__/request-router-replay-plugin.test.ts @@ -0,0 +1,212 @@ +import { createPluginSelectionGuard } from '@agent-device/plugins/store'; +import path from 'node:path'; +import { expect, test, vi } from 'vitest'; +import { createTestDeviceInventoryGateways } from '@agent-device/device-selection/inventory-gateways-fixtures'; +import { bindReplayBackendResolver } from '@agent-device/replay-port/replay-backend-registry'; +import { resolveProviderPlugins, startProviderRegistry } from '@agent-device/plugins/registry'; +import { + selectV2Plugin, + mkdtempForTestSync, + createTestHostEnvironment, +} from '@agent-device/test-kit'; +import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; +import { LeaseRegistry } from '../../resources/lease-registry.ts'; +import { createRequestHandler } from '../../__tests__/support/test-device-runtime-gateway.ts'; +import { fakeCreateCommandSurface } from '../../__tests__/support/command-surface-fake.ts'; + +async function fixture(storeEnv?: NodeJS.ProcessEnv) { + const root = mkdtempForTestSync('replay-plugin-admission-'); + const discover = vi.fn(async () => []); + const registry = await startProviderRegistry( + await resolveProviderPlugins([]), + { env: {}, cwd: '/' }, + { + assertReplaySelectionCurrent: storeEnv ? createPluginSelectionGuard([], storeEnv) : undefined, + adaptWebDriver: async () => { + throw new Error('no provider'); + }, + }, + ); + await bindReplayBackendResolver(registry.resolveReplayBackend, registry.resolveReplayExecution); + const store = makeSessionStore('replay-plugin-admission-store-'); + const handler = createRequestHandler({ + host: createTestHostEnvironment(), + createCommandSurface: fakeCreateCommandSurface, + logPath: path.join(root, 'daemon.log'), + token: 'token', + sessionStore: store, + leaseRegistry: new LeaseRegistry(), + deviceInventoryGateways: createTestDeviceInventoryGateways({ local: discover }), + trackDownloadableArtifact: () => 'artifact-id', + }); + return { registry, discover, handler, store }; +} + +const source = { + entry: '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/caller/flow.ad', + files: { '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/caller/flow.ad': 'open com.example.app\nclose\n' }, +}; + +test.each([ + ['yaml', 'replay'], + ['yml', 'replay'], + ['yaml', 'test'], + ['yml', 'test'], +] as const)( + 'bare %s %s reports explicit routing before plugin or device admission', + async (extension, command) => { + const f = await fixture(); + const entry = `/caller/flow.${extension}`; + const bundle = { entry, files: { [entry]: 'appId: com.example.app' } }; + try { + const result = await f.handler({ + token: 'token', + command, + session: 'untouched', + positionals: [entry], + flags: + command === 'test' ? { replayScriptSources: [bundle] } : { replayScriptSource: bundle }, + }); + expect(result).toMatchObject({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: `Maestro YAML requires explicit --maestro routing: ${command} ${entry} --maestro`, + }, + }); + if (result.ok) throw new Error('Bare YAML command succeeded'); + expect(result.error.details?.installCommand).toBeUndefined(); + expect(f.discover).not.toHaveBeenCalled(); + expect(f.store.get('untouched')).toBeUndefined(); + } finally { + await f.registry.close(); + } + }, +); + +test.each(['replay', 'test'] as const)( + 'missing %s execution is classified before device selection', + async (command) => { + const f = await fixture(); + try { + const result = await f.handler({ + token: 'token', + command, + session: 'untouched', + positionals: [source.entry], + flags: { platform: 'ios', replayScriptSource: source, replayScriptSources: [source] }, + }); + expect(result).toMatchObject({ + ok: false, + error: { + code: 'INVALID_ARGS', + details: { + reason: 'plugin-not-installed', + package: '@agent-device/replay', + installCommand: 'agent-device plugins add @agent-device/replay', + }, + }, + }); + expect(f.discover).not.toHaveBeenCalled(); + expect(f.store.get('untouched')).toBeUndefined(); + } finally { + await f.registry.close(); + } + }, +); + +test.each(['replay', 'test'] as const)( + 'explicit Maestro %s retains its required plugin admission', + async (command) => { + const f = await fixture(); + const entry = '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/caller/flow.yaml'; + const bundle = { entry, files: { [entry]: 'appId: com.example.app' } }; + try { + const result = await f.handler({ + token: 'token', + command, + session: 'untouched', + positionals: [entry], + flags: { + replayBackend: 'maestro', + ...(command === 'test' + ? { replayScriptSources: [bundle] } + : { replayScriptSource: bundle }), + }, + }); + expect(result).toMatchObject({ + ok: false, + error: { + details: { + reason: 'plugin-not-installed', + package: command === 'test' ? '@agent-device/replay' : '@agent-device/maestro', + }, + }, + }); + expect(f.discover).not.toHaveBeenCalled(); + expect(f.store.get('untouched')).toBeUndefined(); + } finally { + await f.registry.close(); + } + }, +); + +test('a changed store needs a daemon restart and embedded runtimes never consult it', async () => { + const home = mkdtempForTestSync('replay-plugin-store-'); + const env = { AGENT_DEVICE_HOME: home }; + const f = await fixture(env); + try { + selectV2Plugin( + home, + '@agent-device/replay', + 'throw new Error("must not import while detecting stale daemon");', + ); + const request = { + token: 'token', + command: 'replay', + session: 'untouched', + positionals: [source.entry], + flags: { replayScriptSource: source }, + }; + expect(await f.handler(request)).toMatchObject({ + ok: false, + error: { details: { reason: 'daemon-plugin-set-stale' } }, + }); + const embedded = await fixture(); + try { + expect(await embedded.handler(request)).toMatchObject({ + ok: false, + error: { details: { reason: 'plugin-not-installed' } }, + }); + expect(embedded.discover).not.toHaveBeenCalled(); + } finally { + await embedded.registry.close(); + } + expect(f.discover).not.toHaveBeenCalled(); + } finally { + await f.registry.close(); + } +}); + +test.each(['unknown-engine', ''])( + 'backend %j receives no inferred installation command', + async (backend) => { + const f = await fixture(); + try { + const result = await f.handler({ + token: 'token', + command: 'replay', + session: 'untouched', + positionals: [source.entry], + flags: { replayBackend: backend, replayScriptSource: source }, + }); + expect(result).toMatchObject({ ok: false, error: { code: 'INVALID_ARGS' } }); + if (result.ok) throw new Error('Unknown backend succeeded'); + expect(result.error.details?.installCommand).toBeUndefined(); + expect(result.error.message).toContain('Unsupported replay backend'); + expect(f.discover).not.toHaveBeenCalled(); + } finally { + await f.registry.close(); + } + }, +); diff --git a/packages/daemon/src/server/http/daemon-runtime-bounded-close.test.ts b/packages/daemon/src/server/http/daemon-runtime-bounded-close.test.ts index d87635bed5..0358ddc376 100644 --- a/packages/daemon/src/server/http/daemon-runtime-bounded-close.test.ts +++ b/packages/daemon/src/server/http/daemon-runtime-bounded-close.test.ts @@ -19,6 +19,7 @@ import { daemonPlatformServicesFixture } from '../../__tests__/support/platform- import { providerCredentialsFixture } from '../../__tests__/support/provider-credentials-fixture.ts'; import { startDaemonRuntime } from './daemon-runtime.ts'; import { + createPluginClose, describeUnfinishedShutdownWork, reportDaemonClose, type ShutdownReport, @@ -258,3 +259,46 @@ test('a clean close disposes the state composition declared in the entered handl expect(report.platformOwners).toBe('closed'); expect(disposeState).toHaveBeenCalledOnce(); }); + +test('only registered cleanup owners stay pending after a lazy backend failure', async () => { + vi.useFakeTimers(); + try { + const inventory: import('@agent-device/contracts/plugin-inventory').PluginInventoryEntry[] = [ + { + backend: 'maestro', + source: 'store', + state: 'active', + credentials: { variables: [], byBackend: {} }, + }, + { + backend: 'maestro', + source: 'embedder', + state: 'failed', + error: { code: 'INVALID_ARGS', message: 'duplicate', reason: 'duplicate_replay_backend' }, + credentials: { variables: [], byBackend: {} }, + }, + { + backend: 'rejected', + source: 'store', + state: 'failed', + error: { code: 'COMMAND_FAILED', message: 'setup failed', reason: 'plugin_setup_failed' }, + credentials: { variables: [], byBackend: {} }, + }, + ]; + const owner = createPluginClose({ + close: () => new Promise(() => {}), + timeoutMs: 50, + inventory, + }); + inventory[0] = { + ...inventory[0]!, + state: 'failed', + error: { code: 'COMMAND_FAILED', message: 'load failed', reason: 'plugin_load_failed' }, + }; + const close = owner.close(); + await vi.advanceTimersByTimeAsync(50); + expect(await close).toEqual({ disposed: [], failed: [], pending: ['replay-backend:maestro'] }); + } finally { + vi.useRealTimers(); + } +}); diff --git a/packages/daemon/src/server/http/daemon-runtime-leased-session.test.ts b/packages/daemon/src/server/http/daemon-runtime-leased-session.test.ts new file mode 100644 index 0000000000..65efb8af45 --- /dev/null +++ b/packages/daemon/src/server/http/daemon-runtime-leased-session.test.ts @@ -0,0 +1,216 @@ +import fs from 'node:fs'; +import { afterEach, beforeEach, expect, test } from 'vitest'; +import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; +import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { daemonRuntimeDepsFixture } from '../../__tests__/support/daemon-runtime-deps-fixture.ts'; +import { startDaemonRuntime } from './daemon-runtime.ts'; + +const TENANT = 'tenant-a'; +const RUN = 'run-1'; +const PROXY_SCOPE = { + tenantId: TENANT, + runId: RUN, + leaseProvider: 'proxy', + clientId: 'client-a', + deviceKey: 'android:mobile:emulator-5554', + backend: 'android-instance', +} as const; + +type RpcBody = { + result?: { ok?: boolean; data?: { lease?: { leaseId?: string } } }; + error?: { data?: { code?: string; details?: { reason?: string; leaseProvider?: string } } }; +}; + +let daemon: { close: () => Promise; httpPort: number; token: string }; + +beforeEach(async () => { + const stateDir = mkdtempForTestSync('agent-device-leased-session-'); + const runtime = await startDaemonRuntime({ + host: createTestHostEnvironment({ + env: { + ...process.env, + AGENT_DEVICE_STATE_DIR: stateDir, + AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0', + AGENT_DEVICE_DAEMON_SERVER_MODE: 'http', + }, + }), + stderr: { write: () => {} }, + stdout: { write: () => {} }, + composeDeps: daemonRuntimeDepsFixture({}), + }); + const { httpPort, token } = JSON.parse( + fs.readFileSync(resolveDaemonPaths(stateDir).infoPath, 'utf8'), + ) as { httpPort: number; token: string }; + daemon = { + close: async () => { + await runtime.close(); + }, + httpPort, + token, + }; +}); + +afterEach(async () => { + await daemon.close(); +}); + +async function rpc(method: string, params: Record): Promise { + const response = await fetch(`http://127.0.0.1:${daemon.httpPort}/rpc`, { + method: 'POST', + headers: { authorization: `Bearer ${daemon.token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ jsonrpc: '2.0', id: method, method, params }), + }); + return (await response.json()) as RpcBody; +} + +function allocate(params: Record): Promise { + return rpc('agent_device.lease.allocate', params); +} + +async function allocateNamedLease(session: string): Promise { + const allocated = await allocate({ ...PROXY_SCOPE, session }); + const leaseId = allocated.result?.data?.lease?.leaseId; + expect(leaseId, JSON.stringify(allocated)).toBeTypeOf('string'); + return leaseId as string; +} + +function expectSessionRequired(body: RpcBody): void { + expect(body.error?.data).toMatchObject({ + code: 'INVALID_ARGS', + details: { reason: 'REMOTE_SESSION_REQUIRED', leaseProvider: 'proxy' }, + }); +} + +test.each([ + ['omitted', {}], + ['blank', { session: ' ' }], +])('a %s session is refused before a provider lease is allocated', async (_label, session) => { + expectSessionRequired(await allocate({ ...PROXY_SCOPE, ...session })); + + // Another client finds the device free, so the refused request left no lease behind. + const other = await allocate({ ...PROXY_SCOPE, clientId: 'client-b', session: 'agent-b' }); + expect(other.result?.ok, JSON.stringify(other)).toBe(true); +}); + +test.each([ + [ + 'the command method', + () => { + const { backend: leaseBackend, ...scope } = PROXY_SCOPE; + return rpc('agent_device.command', { + session: 'default', + command: 'lease_allocate', + positionals: [], + meta: { ...scope, leaseBackend, sessionExplicit: false }, + }); + }, + ], + [ + 'the lease method', + () => allocate({ ...PROXY_SCOPE, session: 'default', sessionExplicit: false }), + ], +])('a client that names no session through %s is refused', async (_label, send) => { + expectSessionRequired(await send()); + + const other = await allocate({ ...PROXY_SCOPE, clientId: 'client-b', session: 'agent-b' }); + expect(other.result?.ok, JSON.stringify(other)).toBe(true); +}); + +test.each([ + ['in its meta', { sessionExplicit: true }, {}], + ['in its flags', { sessionExplicit: false }, { session: 'default' }], +])('a client that names the default session %s is not refused', async (_label, meta, flags) => { + const { backend: leaseBackend, ...scope } = PROXY_SCOPE; + + const allocated = await rpc('agent_device.command', { + session: 'default', + command: 'lease_allocate', + positionals: [], + flags, + meta: { ...scope, leaseBackend, ...meta }, + }); + + expect(allocated.result?.ok, JSON.stringify(allocated)).toBe(true); +}); + +test('an unnamed heartbeat is refused and the named lease stays usable', async () => { + const leaseId = await allocateNamedLease('agent-a'); + + expectSessionRequired(await rpc('agent_device.lease.heartbeat', { ...PROXY_SCOPE, leaseId })); + + const named = await rpc('agent_device.lease.heartbeat', { + ...PROXY_SCOPE, + leaseId, + session: 'agent-a', + }); + expect(named.result?.ok).toBe(true); +}); + +test('an unnamed release is refused and the lease is still released when named', async () => { + const leaseId = await allocateNamedLease('agent-a'); + + expectSessionRequired(await rpc('agent_device.lease.release', { ...PROXY_SCOPE, leaseId })); + + const named = await rpc('agent_device.lease.release', { + ...PROXY_SCOPE, + leaseId, + session: 'agent-a', + }); + expect(named.result?.data).toMatchObject({ released: true }); +}); + +test.each([ + ['shared', {}], + ['tenant-isolated', { sessionIsolation: 'tenant' }], +])( + 'an unnamed leased command is refused for its session in a %s daemon', + async (_label, isolation) => { + const leaseId = await allocateNamedLease('agent-a'); + const { backend: leaseBackend, ...scope } = PROXY_SCOPE; + + const refused = await rpc('agent_device.command', { + command: 'snapshot', + positionals: [], + meta: { ...scope, leaseBackend, leaseId, ...isolation }, + }); + + expectSessionRequired(refused); + }, +); + +test('a named leased command is not refused for its session', async () => { + const leaseId = await allocateNamedLease('agent-a'); + const { backend: leaseBackend, ...scope } = PROXY_SCOPE; + + const named = await rpc('agent_device.command', { + session: 'agent-a', + command: 'snapshot', + positionals: [], + meta: { ...scope, leaseBackend, leaseId }, + }); + + expect(named.error?.data?.code, JSON.stringify(named)).toBe('DEVICE_NOT_FOUND'); + expect(named.error?.data?.details?.reason).not.toBe('REMOTE_SESSION_REQUIRED'); +}); + +test('an unnamed request that names a provider but holds no lease is not refused for its session', async () => { + const listed = await rpc('agent_device.command', { + command: 'apps', + positionals: [], + flags: { platform: 'android', leaseProvider: 'proxy' }, + }); + + expect(listed.error?.data?.details?.reason).not.toBe('REMOTE_SESSION_REQUIRED'); +}); + +test('requests with no lease provider keep their unnamed default session', async () => { + const allocated = await allocate({ + tenantId: TENANT, + runId: RUN, + backend: 'android-instance', + }); + expect(allocated.result?.ok, JSON.stringify(allocated)).toBe(true); + + const listed = await rpc('agent_device.command', { command: 'session_list' }); + expect(listed.result?.ok, JSON.stringify(listed)).toBe(true); +}); diff --git a/packages/daemon/src/server/http/daemon-runtime-metadata-ownership.test.ts b/packages/daemon/src/server/http/daemon-runtime-metadata-ownership.test.ts index 084dd43c04..99262f486a 100644 --- a/packages/daemon/src/server/http/daemon-runtime-metadata-ownership.test.ts +++ b/packages/daemon/src/server/http/daemon-runtime-metadata-ownership.test.ts @@ -288,6 +288,15 @@ test('a plugin whose cleanup failed at shutdown is recorded in daemon.log', asyn shutdown: { status: 'ok' }, dispose: { status: 'ok' }, }, + { + backend: 'maestro', + source: 'store', + shutdown: { status: 'ok' }, + dispose: { + status: 'failed', + error: { code: 'COMMAND_FAILED', message: 'backend disposal broke' }, + }, + }, ]; const runtime = await startRuntime(stateDir); try { @@ -295,12 +304,17 @@ test('a plugin whose cleanup failed at shutdown is recorded in daemon.log', asyn const events = logEvents(stateDir).filter( ({ phase }) => phase === 'provider_plugin_cleanup_failed', ); - expect(events).toHaveLength(1); + expect(events).toHaveLength(2); expect(events[0]?.data).toMatchObject({ provider: 'example', source: 'store', shutdown: { code: 'COMMAND_FAILED' }, }); + expect(events[1]?.data).toMatchObject({ + backend: 'maestro', + source: 'store', + dispose: { code: 'COMMAND_FAILED' }, + }); } finally { fs.rmSync(stateDir, { recursive: true, force: true }); } diff --git a/packages/daemon/src/server/http/daemon-runtime.ts b/packages/daemon/src/server/http/daemon-runtime.ts index 7054039ae3..55a27df8cf 100644 --- a/packages/daemon/src/server/http/daemon-runtime.ts +++ b/packages/daemon/src/server/http/daemon-runtime.ts @@ -825,6 +825,7 @@ async function startDaemonRuntimeOnHost( for (const failure of plugins.failed) { await emitDaemonDiagnostic(logPath, 'provider_plugin_cleanup_failed', { provider: failure.provider, + backend: failure.backend, source: failure.source, [failure.step]: failure.error, }); diff --git a/packages/daemon/src/server/http/http-rpc-methods.ts b/packages/daemon/src/server/http/http-rpc-methods.ts index 948de61a0f..2d85d8cdc5 100644 --- a/packages/daemon/src/server/http/http-rpc-methods.ts +++ b/packages/daemon/src/server/http/http-rpc-methods.ts @@ -12,6 +12,7 @@ import type { import { commandRpcParamsSchema } from '@agent-device/kernel/contracts'; import { readLeaseAllocateProviderFlags } from '@agent-device/contracts/lease-scope'; import type { DaemonRequest } from '../../core/daemon-request.ts'; +import { resolveRequestSessionAtIntake } from '../../core/request-session-intake.ts'; import { resolveToken } from './http-authorization.ts'; import { resolveMaterializedPathRetentionMs } from '../../sessions/materialized-path-registry.ts'; @@ -47,7 +48,7 @@ const SUPPORTED_RPC_METHODS = new Set([ function toDaemonRequest(params: CommandRpcParams, headers: IncomingHttpHeaders): DaemonRequest { return { token: resolveToken(params as Record, headers), - session: params.session ?? 'default', + ...resolveRequestSessionAtIntake(params), command: params.command ?? '', positionals: params.positionals ?? [], input: params.input, @@ -155,7 +156,10 @@ function toLeaseDaemonRequest( ): DaemonRequest { return { token: resolveToken(params, headers), - session: readStringParam(params, 'session') ?? 'default', + ...resolveRequestSessionAtIntake({ + session: readStringParam(params, 'session'), + meta: { sessionExplicit: readBooleanParam(params, 'sessionExplicit') }, + }), command, positionals: [], flags: command === 'lease_allocate' ? readLeaseAllocateProviderFlags(params) : undefined, @@ -234,7 +238,7 @@ function toInstallFromSourceDaemonRequest( } return { token: resolveToken(params, headers), - session: readStringParam(params, 'session') ?? 'default', + ...resolveRequestSessionAtIntake({ session: readStringParam(params, 'session') }), command: 'install_source', positionals: [], flags: { platform }, @@ -260,7 +264,7 @@ function toReleaseMaterializedPathsDaemonRequest( } return { token: resolveToken(params, headers), - session: readStringParam(params, 'session') ?? 'default', + ...resolveRequestSessionAtIntake({ session: readStringParam(params, 'session') }), command: 'release_materialized_paths', positionals: [], meta: { diff --git a/packages/daemon/src/server/http/server-shutdown.ts b/packages/daemon/src/server/http/server-shutdown.ts index 62afb2cc37..d269471eaa 100644 --- a/packages/daemon/src/server/http/server-shutdown.ts +++ b/packages/daemon/src/server/http/server-shutdown.ts @@ -69,7 +69,8 @@ export type ShutdownReport = { plugins: { disposed: string[]; failed: { - provider: string; + provider?: string; + backend?: string; source?: PluginCleanupOutcome['source']; step: 'shutdown' | 'dispose'; error: NormalizedError; @@ -106,7 +107,7 @@ export function describeUnfinishedShutdownWork(report: ShutdownReport): string[] } for (const failure of report.plugins.failed) { lines.push( - `Daemon shutdown: plugin ${failure.provider} failed to ${failure.step === 'shutdown' ? 'shut down' : 'dispose'}: ${failure.error.message}`, + `Daemon shutdown: plugin ${failure.provider ?? `replay backend ${failure.backend}`} failed to ${failure.step === 'shutdown' ? 'shut down' : 'dispose'}: ${failure.error.message}`, ); } const { pending, unknown } = report.providerReleases; @@ -151,7 +152,7 @@ export type PluginClose = Readonly<{ /** * The daemon's one plugin cleanup: the registry closes each plugin (runtime shutdown, then dispose) * and answers with a per-plugin outcome. Bounded, because one plugin that never finishes must not - * hold the whole close: past the budget every active plugin is reported pending while its cleanup + * hold the whole close: past the budget every registered plugin is reported pending while its cleanup * keeps running. */ export function createPluginClose(params: { @@ -160,10 +161,9 @@ export function createPluginClose(params: { timeoutMs?: number; }): PluginClose { let closing: Promise | undefined; - const activeProviders = (): string[] => - params.inventory.flatMap((entry) => - entry.state === 'active' && entry.provider !== undefined ? [entry.provider] : [], - ); + const cleanupOwners = params.inventory.flatMap((entry) => + entry.state === 'active' ? [{ provider: entry.provider, backend: entry.backend }] : [], + ); return { close: () => (closing ??= (async () => { @@ -172,14 +172,20 @@ export function createPluginClose(params: { params.timeoutMs ?? DAEMON_PLUGIN_SHUTDOWN_TIMEOUT_MS, ); if (outcome.kind === 'deadline') { - return { disposed: [], failed: [], pending: activeProviders() }; + return { + disposed: [], + failed: [], + pending: cleanupOwners.map( + ({ provider, backend }) => provider ?? `replay-backend:${backend}`, + ), + }; } if (outcome.kind === 'rejected') { const error = normalizeError(outcome.error); return { disposed: [], - failed: activeProviders().map((provider) => ({ - provider, + failed: cleanupOwners.map((identity) => ({ + ...identity, step: 'shutdown' as const, error, })), @@ -221,7 +227,8 @@ function reportCleanupOutcomes( outcomes: readonly PluginCleanupOutcome[], ): ShutdownReport['plugins'] { const report: ShutdownReport['plugins'] = { disposed: [], failed: [], pending: [] }; - for (const { provider, source, shutdown, dispose } of outcomes) { + for (const { provider, backend, source, shutdown, dispose } of outcomes) { + const identity = provider === undefined ? { backend } : { provider }; for (const [step, result] of [ ['shutdown', shutdown], ['dispose', dispose], @@ -229,13 +236,14 @@ function reportCleanupOutcomes( if (result.status !== 'failed') continue; const { code, message, hint } = result.error; report.failed.push({ - provider, + ...identity, source, step, error: { code, message, ...(hint === undefined ? {} : { hint }) }, }); } - if (shutdown.status === 'ok' && dispose.status === 'ok') report.disposed.push(provider); + if (shutdown.status === 'ok' && dispose.status === 'ok') + report.disposed.push(provider ?? `replay-backend:${backend}`); } return report; } diff --git a/packages/daemon/src/server/http/transport.test.ts b/packages/daemon/src/server/http/transport.test.ts index a4261f1320..9d080a9b3c 100644 --- a/packages/daemon/src/server/http/transport.test.ts +++ b/packages/daemon/src/server/http/transport.test.ts @@ -247,6 +247,38 @@ test('socket transport refuses a non-string positional before dispatch', async ( } }); +test.for([ + ['omitted', undefined, 'default', true], + ['blank', ' ', ' ', true], + ['named', 'agent-a', 'agent-a', undefined], +] as const)( + 'the socket records a session that is %s', + async ([_label, session, resolvedSession, sessionOmitted], t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + + const observedRequests: DaemonRequest[] = []; + const server = createSocketServer(async (req): Promise => { + observedRequests.push(req); + return { ok: true, data: {} }; + }); + + try { + const client = await connectSocket(await listenNetServer(server)); + await writeSocketRequests( + client, + [JSON.stringify({ token: 'token', session, command: 'session_list', positionals: [] })], + 1, + ); + client.destroy(); + assert.equal(observedRequests.length, 1); + assert.equal(observedRequests[0]?.session, resolvedSession); + assert.equal(observedRequests[0]?.internal?.sessionOmitted, sessionOmitted); + } finally { + await closeLoopbackServer(server); + } + }, +); + // A socket client that vanishes mid-request must cancel that connection's // in-flight request via its request-scoped signal — never through a global // Apple-runner abort, and never touching another connection's request. diff --git a/packages/daemon/src/server/http/transport.ts b/packages/daemon/src/server/http/transport.ts index 8755e6911e..21653b8ddc 100644 --- a/packages/daemon/src/server/http/transport.ts +++ b/packages/daemon/src/server/http/transport.ts @@ -15,6 +15,7 @@ import { isReadOnlyRequest, resolveDaemonRequestResultDeadlineMs, } from '../../core/daemon-command-registry.ts'; +import { resolveRequestSessionAtIntake } from '../../core/request-session-intake.ts'; import { clearRequestAbortRegistration, isRequestCanceled, @@ -219,7 +220,7 @@ function parseSocketDaemonRequest(line: string): DaemonRequest { if (isRecord(request.meta)) { request.meta = { ...request.meta, devicePin: readDevicePin(request.meta.devicePin) }; } - return request as DaemonRequest; + return { ...request, ...resolveRequestSessionAtIntake(request) } as DaemonRequest; } export function listenNetServer(server: net.Server): Promise { diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index 4175bdb984..3ac91886c7 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -32,6 +32,7 @@ import { } from '../sessions/session-routing.ts'; import { deriveWebSessionIdentity } from '../core/session-tenant-scope.ts'; import { + assertProviderLeaseRequestNamesSession, assertRequestLeaseAdmissionPreflight, scopeRequestSession, } from '../sessions/request-admission.ts'; @@ -308,6 +309,7 @@ export async function createRequestExecutionScope(params: { : undefined; if (devicePin && pinPolicy) pinPolicy.assertRequestHonorsDevicePin(devicePin, scopedReq); if (params.daemonPolicy) assertDaemonPolicyAdmitsRequest(params.daemonPolicy, scopedReq); + assertProviderLeaseRequestNamesSession(scopedReq, sessionStore.get(sessionName)); assertRequestLeaseAdmissionPreflight(scopedReq); // Parse the budget once, before resolving the target device or taking any lock. The lock plan // still supplies the device to wait for, but an out-of-range budget is refused before either. @@ -399,6 +401,7 @@ export async function createRequestExecutionScope(params: { try { const existingRef = sessionStore.lookup(sessionName); const session = existingRef?.session; + assertProviderLeaseRequestNamesSession(scopedReq, session); const boundedResources = boundedStep ? await import('../core/composite-resource-admission.ts') : undefined; @@ -837,12 +840,7 @@ function contextFromRequestFlags( }; } -/** - * The per-`LeaseRegistry` execution-lock map a request's session and device locks are taken from. - * Exported because the #2833 session-idle reaper expires sessions through this same map: an expiry - * that did not wait on the session's execution lock could tear down a session mid-command, and a - * second map would make that race invisible rather than impossible. - */ +/** The idle reaper shares these locks so expiry cannot tear down an active request. */ export function getLeaseRegistryExecutionLocks( leaseRegistry: LeaseRegistry, ): Map> { diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index 899038a363..b7b06e3312 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -22,11 +22,11 @@ import { timingSafeStringEqual } from '@agent-device/host-kit/transport'; import { type ResponseCost, errorResponse, - namesSessionExplicitly, noActiveSessionError, type DaemonResponse, type DaemonResponseData, } from '@agent-device/kernel/contracts'; +import { namesSessionExplicitly } from '@agent-device/kernel/record'; import type { CloudArtifactProvider } from '@agent-device/contracts/observability'; import type { TrackDownloadableArtifact } from '../resources/artifact-tracking.ts'; import type { @@ -275,6 +275,16 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { const unsupportedDeviceSpec = deviceSpecFlagsResponse(req); if (unsupportedDeviceSpec) return unsupportedDeviceSpec; + if (req.command === 'replay' || req.command === 'test') { + try { + const { requireReplayPlugins } = + await import('@agent-device/replay-port/replay-plugin-admission'); + await requireReplayPlugins(req); + } catch (error) { + return finalizeThrownRequestError(error); + } + } + let scope: RequestExecutionScope | undefined; let response: DaemonResponse; const platformRequestScope = createPlatformRequestScope(req); diff --git a/packages/daemon/src/sessions/__tests__/replay-runtime/replay-command-fixture.ts b/packages/daemon/src/sessions/__tests__/replay-runtime/replay-command-fixture.ts index ed4b2c94c8..215db348a3 100644 --- a/packages/daemon/src/sessions/__tests__/replay-runtime/replay-command-fixture.ts +++ b/packages/daemon/src/sessions/__tests__/replay-runtime/replay-command-fixture.ts @@ -1,5 +1,5 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import type { ReplayTestAttemptStepSink } from '@agent-device/replay-test'; +import type { ReplayTestAttemptStepSink } from '@agent-device/contracts/replay-test-execution'; import type { DaemonInvokeFn, DaemonRequest } from '../../../core/daemon-request.ts'; import type { SessionStore } from '../../../core/session-store.ts'; import { diff --git a/packages/daemon/src/sessions/__tests__/replay-runtime/session-replay-runtime-failure.test.ts b/packages/daemon/src/sessions/__tests__/replay-runtime/session-replay-runtime-failure.test.ts index 1c1bd76a76..45ae051d07 100644 --- a/packages/daemon/src/sessions/__tests__/replay-runtime/session-replay-runtime-failure.test.ts +++ b/packages/daemon/src/sessions/__tests__/replay-runtime/session-replay-runtime-failure.test.ts @@ -15,7 +15,7 @@ import path from 'node:path'; import { runReplayForTest } from './replay-command-fixture.ts'; import { SessionStore } from '../../../core/session-store.ts'; import { makeIosSession } from '../../../__tests__/support/session-factories.ts'; -import { formatReplayDivergenceReport } from '@agent-device/ad-replay/divergence'; +import { formatReplayDivergenceReport } from '@agent-device/contracts/replay-divergence-data'; import { maestroScriptSourceBundleFor } from '../../../__tests__/support/replay-script-source-fixture.ts'; import { captureSnapshotThroughLegacyDispatchFixture, diff --git a/packages/daemon/src/sessions/__tests__/replay-suite/session-test-suite-command-video.test.ts b/packages/daemon/src/sessions/__tests__/replay-suite/session-test-suite-command-video.test.ts index 45822f8a6f..c2a79121ec 100644 --- a/packages/daemon/src/sessions/__tests__/replay-suite/session-test-suite-command-video.test.ts +++ b/packages/daemon/src/sessions/__tests__/replay-suite/session-test-suite-command-video.test.ts @@ -1,3 +1,4 @@ +import { getReplayExecution } from '@agent-device/replay-port/replay-backend-registry'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { daemonPlatformServicesFixture } from '../../../__tests__/support/platform-services-fixture.ts'; /** Per-attempt recording is finalized exactly once after cancellation. */ @@ -217,6 +218,7 @@ function expectRecordRuntimeCall( } test('test finalizes replay video exactly once when cancellation arrives after start', async () => { + await getReplayExecution(); vi.useFakeTimers({ now: 1_000 }); const { root, replayPath, sessionStore, nestedRequests, events } = createRecordVideoFixture(); const finish = vi.fn(async () => ({ diff --git a/packages/daemon/src/sessions/__tests__/request-admission.test.ts b/packages/daemon/src/sessions/__tests__/request-admission.test.ts index efec73795c..4f76905c9b 100644 --- a/packages/daemon/src/sessions/__tests__/request-admission.test.ts +++ b/packages/daemon/src/sessions/__tests__/request-admission.test.ts @@ -4,7 +4,11 @@ import { makeIosSession, makeMacOsSession } from '../../__tests__/support/sessio import { parseDaemonPolicy } from '@agent-device/daemon-contracts/daemon-policy-file'; import { AppError } from '@agent-device/kernel/errors'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; -import { assertRequestLeaseAdmission, isConfinedToAppLease } from '../request-admission.ts'; +import { + assertProviderLeaseRequestNamesSession, + assertRequestLeaseAdmission, + isConfinedToAppLease, +} from '../request-admission.ts'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import type { ProviderAppCatalog } from '@agent-device/contracts/device'; @@ -550,3 +554,43 @@ test('a daemon policy that requires a macos-app lease refuses unleased and other lease.leaseId, ); }); + +const SESSION_LEASE = { tenantId: 'tenant-a', runId: 'run-1', leaseId: 'a'.repeat(32) }; + +test('an unnamed request reaching a provider lease through its session is refused', () => { + const session = makeIosSession('default', { + lease: { ...SESSION_LEASE, leaseProvider: 'proxy' }, + }); + + assert.throws( + () => + assertProviderLeaseRequestNamesSession( + makeRequest({ command: 'snapshot', internal: { sessionOmitted: true } }), + session, + ), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + assert.equal(error.details?.reason, 'REMOTE_SESSION_REQUIRED'); + assert.equal(error.details?.leaseProvider, 'proxy'); + return true; + }, + ); +}); + +test('a named request on the same provider-leased session is not refused', () => { + const session = makeIosSession('default', { + lease: { ...SESSION_LEASE, leaseProvider: 'proxy' }, + }); + + assertProviderLeaseRequestNamesSession(makeRequest({ command: 'snapshot' }), session); +}); + +test('an unnamed request on a session whose lease has no provider is not refused', () => { + const session = makeIosSession('default', { lease: SESSION_LEASE }); + + assertProviderLeaseRequestNamesSession( + makeRequest({ command: 'snapshot', internal: { sessionOmitted: true } }), + session, + ); +}); diff --git a/packages/daemon/src/sessions/handlers/__tests__/lease.test.ts b/packages/daemon/src/sessions/handlers/__tests__/lease.test.ts index f080327d15..3ba3e45355 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/lease.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/lease.test.ts @@ -881,6 +881,7 @@ test('lease_allocate names the plugin that failed to register when it could have failed('testmu', '@agent-device/testmu'), failed(undefined, 'unloadable-plugin'), failed('other', 'other-plugin'), + { ...failed(undefined, '@agent-device/maestro'), backend: 'maestro' }, ], }), (error: unknown) => { diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index 7f4c7ba238..bd3186db08 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -437,7 +437,9 @@ function assertProviderRuntimeRegistered( if (provider === undefined || registeredProviders.includes(provider)) return; // A plugin that failed before its provider id was known could have been this provider. const failures = failedPlugins.flatMap((plugin) => - plugin.state === 'failed' && (plugin.provider === provider || plugin.provider === undefined) + plugin.state === 'failed' && + plugin.backend === undefined && + (plugin.provider === provider || plugin.provider === undefined) ? [ { ...(plugin.provider === undefined ? {} : { provider: plugin.provider }), diff --git a/packages/daemon/src/sessions/handlers/record-runtime-request.ts b/packages/daemon/src/sessions/handlers/record-runtime-request.ts index a3fc5920d2..02ffa78915 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime-request.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime-request.ts @@ -7,7 +7,7 @@ import { import { retiredScreenshotMaxSizeFlagError } from '@agent-device/contracts/capture'; import { AppError } from '@agent-device/kernel/errors'; import type { DaemonRequest } from '../../core/daemon-request.ts'; -import { namesSessionExplicitly } from '@agent-device/kernel/contracts'; +import { namesSessionExplicitly } from '@agent-device/kernel/record'; const IOS_DEVICE_RECORD_MIN_FPS = 1; const IOS_DEVICE_RECORD_MAX_FPS = 120; diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index d28da91dab..081f880252 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -19,7 +19,7 @@ import { } from '@agent-device/contracts/screen-recording-runtime-plan'; import { isWholeScreenRecordingScope } from '@agent-device/contracts/recording'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; -import { namesSessionExplicitly } from '@agent-device/kernel/contracts'; +import { namesSessionExplicitly } from '@agent-device/kernel/record'; import { deviceIdentityFlag, type DeviceIdentity, diff --git a/packages/daemon/src/sessions/handlers/session-appstate.ts b/packages/daemon/src/sessions/handlers/session-appstate.ts index 208d14dadd..360d35181f 100644 --- a/packages/daemon/src/sessions/handlers/session-appstate.ts +++ b/packages/daemon/src/sessions/handlers/session-appstate.ts @@ -1,5 +1,5 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { namesSessionExplicitly } from '@agent-device/kernel/contracts'; +import { namesSessionExplicitly } from '@agent-device/kernel/record'; import { isApplePlatform } from '@agent-device/kernel/device'; import { hasExplicitDeviceSelector } from '../../core/device/device-selector-intent.ts'; import { diff --git a/packages/daemon/src/sessions/handlers/session-batch.ts b/packages/daemon/src/sessions/handlers/session-batch.ts index e964d3a500..695d80a0ec 100644 --- a/packages/daemon/src/sessions/handlers/session-batch.ts +++ b/packages/daemon/src/sessions/handlers/session-batch.ts @@ -30,6 +30,7 @@ export async function runBatchCommands( ...step.internal, webSession: req.internal?.webSession, ...(req.internal?.publicNetworkOnly ? { publicNetworkOnly: true } : {}), + ...(req.internal?.sessionOmitted ? { sessionOmitted: true } : {}), executionPlan: { remainingSteps: context.remainingSteps }, }, }); diff --git a/packages/daemon/src/sessions/request-admission.ts b/packages/daemon/src/sessions/request-admission.ts index 115eae1490..bf32e513d7 100644 --- a/packages/daemon/src/sessions/request-admission.ts +++ b/packages/daemon/src/sessions/request-admission.ts @@ -5,6 +5,7 @@ import { resolveSessionIsolationMode } from '../core/config.ts'; import { tenantScopedSessionName } from '../core/session-tenant-scope.ts'; import { isAppLeaseAllowed, + ignoresSessionLease, isLeaseAdmissionExempt, isHumanControlMutation, resolveSessionlessLeaseAdmissionExemption, @@ -15,7 +16,10 @@ import { resolveLeaseScope, resolveRequestOrSessionLeaseScope, } from '../core/lease-context.ts'; -import { leaseScopeToHeartbeatRequest } from '@agent-device/contracts/lease-scope'; +import { + leaseScopeToHeartbeatRequest, + remoteSessionRequiredError, +} from '@agent-device/contracts/lease-scope'; import type { LeaseRegistry } from '../resources/lease-registry.ts'; import type { DaemonRequest } from '../core/daemon-request.ts'; import type { SessionState } from '../core/session-state.ts'; @@ -169,6 +173,25 @@ function hasSessionlessLeaseAdmissionExemption( ); } +/** + * An unnamed session resolves to whichever connection holds the default name, so a request that + * would allocate, use or release a provider lease has to name the session it means. Naming a + * provider alone is not that: a sessionless catalog read holds no lease. A request that names only + * a lease id passes here too, because the registry's owner scope refuses it for omitting the + * provider. + */ +export function assertProviderLeaseRequestNamesSession( + req: DaemonRequest, + session: SessionState | undefined, +): void { + if (!req.internal?.sessionOmitted) return; + const { leaseProvider, leaseId } = ignoresSessionLease(req.command) + ? resolveLeaseScope(req) + : resolveRequestOrSessionLeaseScope(req, session); + if (!leaseProvider) return; + if (leaseId || req.command === 'lease_allocate') throw remoteSessionRequiredError(leaseProvider); +} + export function assertRequestLeaseAdmissionPreflight(req: DaemonRequest): void { if (isLeaseAdmissionExempt(req.command)) return; assertProxyOpenLeaseMetadata(req, resolveLeaseScope(req)); diff --git a/packages/daemon/src/sessions/session-replay-coordinator.ts b/packages/daemon/src/sessions/session-replay-coordinator.ts index b6a47ad730..bc0c40b563 100644 --- a/packages/daemon/src/sessions/session-replay-coordinator.ts +++ b/packages/daemon/src/sessions/session-replay-coordinator.ts @@ -1,7 +1,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import type { SessionAction } from '@agent-device/contracts/session'; import type { ReplayDivergenceResume, ReplayRepairHint } from '@agent-device/contracts/divergence'; -import { readReplayDivergenceResume } from '@agent-device/ad-replay/divergence'; +import { readReplayDivergenceResume } from '@agent-device/contracts/replay-divergence-data'; import type { SessionRuntimeHints, SessionState } from '../core/session-state.ts'; import { armRepairStep, diff --git a/packages/daemon/src/sessions/session-routing.ts b/packages/daemon/src/sessions/session-routing.ts index 4caed91518..a7c3adf4b6 100644 --- a/packages/daemon/src/sessions/session-routing.ts +++ b/packages/daemon/src/sessions/session-routing.ts @@ -12,7 +12,7 @@ import type { DaemonRequest } from '../core/daemon-request.ts'; import type { SessionRef, SessionState } from '../core/session-state.ts'; import type { SessionScope } from '@agent-device/contracts/session'; import { SessionStore } from '../core/session-store.ts'; -import { namesSessionExplicitly } from '@agent-device/kernel/contracts'; +import { namesSessionExplicitly } from '@agent-device/kernel/record'; import { listSessionSelectorConflicts, type SessionSelectorConflict, diff --git a/packages/daemon/tsconfig.json b/packages/daemon/tsconfig.json index d0e51a2557..fb3d123454 100644 --- a/packages/daemon/tsconfig.json +++ b/packages/daemon/tsconfig.json @@ -11,6 +11,9 @@ }, "include": ["src"], "references": [ + { + "path": "../plugins" + }, { "path": "../ad-replay" }, @@ -59,9 +62,6 @@ { "path": "../replay-port" }, - { - "path": "../replay-test" - }, { "path": "../selectors" }, @@ -70,6 +70,9 @@ }, { "path": "../test-kit" + }, + { + "path": "../replay" } ] } diff --git a/packages/host-kit/src/code-signature.test.ts b/packages/host-kit/src/code-signature.test.ts index c4377bbab4..41ec7ac6f5 100644 --- a/packages/host-kit/src/code-signature.test.ts +++ b/packages/host-kit/src/code-signature.test.ts @@ -98,7 +98,7 @@ test('a checkout named through a symlink stamps the same repository-relative lab 'src/daemon.ts', ]); } finally { - fs.rmSync(linkedRoot, { force: true }); + fs.unlinkSync(linkedRoot); fs.rmSync(root, { recursive: true, force: true }); } }); @@ -117,7 +117,7 @@ test('an installed dependency is not followed into through a symlinked root', () 'src/daemon.ts', ]); } finally { - fs.rmSync(linkedRoot, { force: true }); + fs.unlinkSync(linkedRoot); fs.rmSync(root, { recursive: true, force: true }); } }); diff --git a/packages/host-kit/src/internal/diagnostics.ts b/packages/host-kit/src/internal/diagnostics.ts index 7820de0fd0..0f8d291ac0 100644 --- a/packages/host-kit/src/internal/diagnostics.ts +++ b/packages/host-kit/src/internal/diagnostics.ts @@ -6,9 +6,14 @@ import path from 'node:path'; import { redactDiagnosticData } from '@agent-device/kernel/redaction'; import type { JsonValue } from '@agent-device/contracts/client'; import type { DiagnosticsRecordRef } from '@agent-device/kernel/errors'; - -/** The severity an event is recorded with. */ -export type DiagnosticLevel = 'info' | 'warn' | 'error' | 'debug'; +import type { + DiagnosticEventInput, + DiagnosticLevel, +} from '@agent-device/contracts/host-diagnostics'; +export type { + DiagnosticEventInput, + DiagnosticLevel, +} from '@agent-device/contracts/host-diagnostics'; type DiagnosticEvent = { ts: string; @@ -136,13 +141,6 @@ export type ResourceDiagnostic = Readonly<{ data: Readonly>; }>; -export type DiagnosticEventInput = { - level?: DiagnosticLevel; - phase: string; - durationMs?: number; - data?: Record; -}; - /** * Encodes diagnostic data for JSON-only ports, preserving bigints as decimal strings. * Performs no redaction; the receiving diagnostics port owns redaction. diff --git a/packages/host-kit/src/internal/exec-trace.ts b/packages/host-kit/src/internal/exec-trace.ts index 9b1f516476..2f740638ce 100644 --- a/packages/host-kit/src/internal/exec-trace.ts +++ b/packages/host-kit/src/internal/exec-trace.ts @@ -16,6 +16,7 @@ export type ExecSettlementReason = | 'success' | 'exit_failure' | 'timeout' + | 'output_limit' | 'abort' | 'spawn_error' | 'stdin_error'; @@ -68,3 +69,23 @@ export function createExecTraceContext( emit('spawn_start'); return { emit }; } + +export function commandSettlementReason(input: { + didAbort: boolean; + exceededStream: 'stdout' | 'stderr' | undefined; + didTimeout: boolean; + code: number | null; + allowFailure: boolean | undefined; +}): ExecSettlementReason { + if (input.didAbort) return 'abort'; + if (input.didTimeout) return 'timeout'; + if (input.exceededStream) return 'output_limit'; + return (input.code ?? 1) !== 0 && !input.allowFailure ? 'exit_failure' : 'success'; +} + +export function normalizeTimeoutMs(value: number | undefined): number | undefined { + if (!Number.isFinite(value)) return undefined; + const timeout = Math.floor(value as number); + if (timeout <= 0) return undefined; + return timeout; +} diff --git a/packages/host-kit/src/internal/exec.test.ts b/packages/host-kit/src/internal/exec.test.ts index 6009a3f6a9..6dd8284a76 100644 --- a/packages/host-kit/src/internal/exec.test.ts +++ b/packages/host-kit/src/internal/exec.test.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest'; +import { expect, test } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; @@ -500,3 +500,178 @@ test.skipIf(process.platform === 'win32')( assert.equal('signal' in exited, false); }, ); + +test('async captured output enforces a per-stream byte limit', async () => { + for (const stream of ['stdout', 'stderr'] as const) { + const emit = `process.${stream}.write('x'.repeat(Number(process.argv[1])))`; + const within = await runCmd(process.execPath, ['-e', emit, '128'], { maxBuffer: 128 }); + expect(within[stream]).toHaveLength(128); + await expect( + runCmd(process.execPath, ['-e', emit, '129'], { maxBuffer: 128 }), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'command_output_limit', stream, maxBuffer: 128 }, + }); + } + const separate = await runCmd( + process.execPath, + ['-e', "process.stdout.write('x'.repeat(128)); process.stderr.write('y'.repeat(128));"], + { maxBuffer: 128 }, + ); + expect(separate.stdout).toHaveLength(128); + expect(separate.stderr).toHaveLength(128); +}); + +test.skipIf(process.platform === 'win32')( + 'an output-limit failure retains bounded output with allowFailure enabled', + async () => { + for (const stream of ['stdout', 'stderr'] as const) { + let child: ReturnType | undefined; + let received = ''; + const onChunk = (chunk: string) => { + received += chunk; + if (received.length === 128) child?.kill('SIGUSR1'); + }; + await expect( + runCmdStreaming( + process.execPath, + [ + '-e', + `process.on('SIGUSR1', () => process.${stream}.write('x')); setInterval(() => {}, 1000); process.${stream}.write('x'.repeat(128));`, + ], + { + maxBuffer: 128, + allowFailure: true, + onSpawn: (spawned) => { + child = spawned; + }, + ...(stream === 'stdout' ? { onStdoutChunk: onChunk } : { onStderrChunk: onChunk }), + }, + ), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { + reason: 'command_output_limit', + stream, + maxBuffer: 128, + [stream]: 'x'.repeat(128), + }, + }); + } + }, +); + +test('async output limits count raw bytes before decoding text', async () => { + for (const stream of ['stdout', 'stderr'] as const) { + for (const bytes of [[0xff], [0xe2, 0x82]]) { + const result = await runCmd( + process.execPath, + ['-e', 'process.' + stream + '.write(Buffer.from(' + JSON.stringify(bytes) + '))'], + { maxBuffer: bytes.length }, + ); + expect(result[stream]).toBe('\uFFFD'); + } + await expect( + runCmd(process.execPath, ['-e', 'process.' + stream + '.write(Buffer.from([0xff, 0xff]))'], { + maxBuffer: 1, + }), + ).rejects.toMatchObject({ details: { reason: 'command_output_limit', stream, maxBuffer: 1 } }); + } + const binary = await runCmd( + process.execPath, + ['-e', 'process.stdout.write(Buffer.from([0xff]))'], + { binaryStdout: true, maxBuffer: 1 }, + ); + expect(binary.stdoutBuffer).toEqual(Buffer.from([0xff])); +}); + +test.skipIf(process.platform === 'win32').each([false, true])( + 'deadline retries an unsuccessful output-limit kill (allowFailure=%s)', + async (allowFailure) => { + let child: ReturnType | undefined; + let forceCleanup: (() => void) | undefined; + let attempts = 0; + let received = ''; + const cleanup = setTimeout(() => forceCleanup?.(), 2_000); + try { + const result = runCmdStreaming( + process.execPath, + [ + '-e', + "process.on('SIGUSR1', () => process.stdout.write('x')); setInterval(() => {}, 1000); process.stdout.write('x'.repeat(128));", + ], + { + maxBuffer: 128, + timeoutMs: 1_000, + allowFailure, + onSpawn: (spawned) => { + child = spawned; + const kill = spawned.kill.bind(spawned); + forceCleanup = () => { + if (spawned.exitCode === null && spawned.signalCode === null) kill('SIGKILL'); + }; + spawned.kill = (signal) => { + if (signal === 'SIGKILL' && ++attempts === 1) return false; + return kill(signal); + }; + }, + onStdoutChunk: (chunk) => { + received += chunk; + if (received.length === 128) child?.kill('SIGUSR1'); + }, + }, + ); + await expect(result).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'command_output_limit', stream: 'stdout', stdout: 'x'.repeat(128) }, + }); + assert.equal(attempts, 2); + } finally { + clearTimeout(cleanup); + forceCleanup?.(); + } + }, +); + +test('bounded text output preserves multibyte characters across pipe chunks', async () => { + const expected = '\u20AC'.repeat(50_000); + for (const stream of ['stdout', 'stderr'] as const) { + const result = await runCmd( + process.execPath, + ['-e', 'process.' + stream + '.write(String.fromCharCode(0x20ac).repeat(50000))'], + { maxBuffer: Buffer.byteLength(expected) }, + ); + expect(result[stream]).toBe(expected); + } +}); + +test.skipIf(process.platform === 'win32')( + 'graceful shutdown output does not replace an earlier timeout', + async () => { + let stdout = ''; + const error = await runCmdStreaming( + process.execPath, + [ + '-e', + [ + "process.on('SIGTERM', () => { process.stderr.write('x'.repeat(129)); clearInterval(keepAlive); });", + 'const keepAlive = setInterval(() => {}, 100);', + "process.stdout.write('ready');", + ].join('\n'), + ], + { + timeoutMs: 1_000, + maxBuffer: 128, + kill: { signal: 'SIGTERM', graceMs: 1_000 }, + onStdoutChunk: (chunk) => { + stdout += chunk; + }, + }, + ).then( + () => undefined, + (error: unknown) => error, + ); + assert.equal(stdout, 'ready'); + assert.ok(isCommandTimeoutError(error)); + }, +); diff --git a/packages/host-kit/src/internal/exec.ts b/packages/host-kit/src/internal/exec.ts index e9611933a6..297c45ef71 100644 --- a/packages/host-kit/src/internal/exec.ts +++ b/packages/host-kit/src/internal/exec.ts @@ -5,8 +5,14 @@ import path from 'node:path'; import { spawn, spawnSync, type ChildProcess, type StdioOptions } from 'node:child_process'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; +import { StringDecoder } from 'node:string_decoder'; import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; -import { createExecTraceContext, type ExecSettlementReason } from './exec-trace.ts'; +import { + commandSettlementReason, + createExecTraceContext, + normalizeTimeoutMs, + type ExecSettlementReason, +} from './exec-trace.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; export type ExecResult = { @@ -27,7 +33,7 @@ export type ExecOptions = { timeoutMs?: number; detached?: boolean; signal?: AbortSignal; - /** Max stdout/stderr bytes for synchronous runs (default Node ~1MB). */ + /** Max captured bytes per stream for runCmd and runCmdSync. runCmd is unlimited when omitted. */ maxBuffer?: number; /** * How a deadline or a cancelled request stops the child. Without this it is SIGKILL at @@ -76,7 +82,7 @@ export type ExecDetachedProcess = { * `signal`; a caller that kills the child directly still waits for the streams to * drain, exactly as before. */ -export type ExecBackgroundOptions = Omit & { +export type ExecBackgroundOptions = Omit & { /** * Capture stdout/stderr into the wait result when the child has piped stdio. * Set false when the caller owns, ignores, or forwards the streams. @@ -227,6 +233,8 @@ function runSpawnedCommand( const stdoutChunks: Buffer[] | undefined = options.binaryStdout && options.captureOutput !== false ? [] : undefined; let stderr = ''; + const outputBytes = { stdout: 0, stderr: 0 }; + let exceededStream: 'stdout' | 'stderr' | undefined; let didTimeout = false; const timeoutMs = normalizeTimeoutMs(options.timeoutMs); let timeoutHandle: NodeJS.Timeout | null = null; @@ -244,15 +252,29 @@ function runSpawnedCommand( if (finish(reason)) reject(error); } function settle(code: number | null): void { - const finalReason = abort.didAbort - ? 'abort' - : didTimeout - ? 'timeout' - : (code ?? 1) !== 0 && !options.allowFailure - ? 'exit_failure' - : 'success'; + const finalReason = commandSettlementReason({ + didAbort: abort.didAbort, + exceededStream, + didTimeout, + code, + allowFailure: options.allowFailure, + }); if (!finish(finalReason)) return; const finalExitCode = code ?? 1; + if (!abort.didAbort && exceededStream && !didTimeout) { + reject( + new AppError('COMMAND_FAILED', `${executable} exceeded its output limit`, { + cmd, + args, + reason: 'command_output_limit', + stream: exceededStream, + maxBuffer: options.maxBuffer, + stdout, + stderr, + }), + ); + return; + } if (!abort.didAbort && didTimeout && timeoutMs) { reject(createTimeoutError(executable, cmd, args, timeoutMs, finalExitCode, stdout, stderr)); return; @@ -283,24 +305,17 @@ function runSpawnedCommand( // A deadline that fires after the child exited on its own still has to settle: the // group kill that would have ended the pipe holder can no longer run through a child // Node already reaped. - const settlement = createCommandKillSettlement({ - killProcessTree: () => killProcessTree(child, options), - settle, - }); - const abort = watchCommandAbort(options, () => { - execTrace.emit('abort'); - settlement.requestKill(); - }); + const { settlement, abort } = bindCommandLifecycle(child, options, execTrace, settle); timeoutHandle = timeoutMs ? setTimeout(() => { execTrace.emit('deadline'); - didTimeout = true; + didTimeout = exceededStream === undefined; settlement.requestKill(); }, timeoutMs) : null; - if (!options.binaryStdout) child.stdout.setEncoding('utf8'); - child.stderr.setEncoding('utf8'); + const stdoutDecoder = new StringDecoder('utf8'); + const stderrDecoder = new StringDecoder('utf8'); void writeChildStdin(child, options.stdin).catch((error: unknown) => { if (abort.didAbort || didTimeout) return; @@ -309,39 +324,53 @@ function runSpawnedCommand( killProcessTree(child, options); }); - child.stdout.on('data', (chunk) => { + function acceptOutput(stream: 'stdout' | 'stderr', chunk: string | Buffer): boolean { + if (exceededStream) return false; + if (options.captureOutput === false || options.maxBuffer === undefined) return true; + outputBytes[stream] += Buffer.byteLength(chunk); + if (outputBytes[stream] <= options.maxBuffer) return true; + exceededStream = stream; + settlement.requestKill(); + return false; + } + + function appendText(stream: 'stdout' | 'stderr', text: string): void { + if (!text) return; + if (options.captureOutput !== false) { + if (stream === 'stdout') stdout += text; + else stderr += text; + } + if (stream === 'stdout') options.onStdoutChunk?.(text); + else options.onStderrChunk?.(text); + } + + child.stdout.on('data', (chunk: Buffer) => { + if (!acceptOutput('stdout', chunk)) return; if (options.binaryStdout) { stdoutChunks?.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); return; } - const text = String(chunk); - if (options.captureOutput !== false) stdout += text; - options.onStdoutChunk?.(text); + appendText('stdout', stdoutDecoder.write(chunk)); }); - child.stderr.on('data', (chunk) => { - const text = String(chunk); - if (options.captureOutput !== false) stderr += text; - options.onStderrChunk?.(text); + child.stderr.on('data', (chunk: Buffer) => { + if (!acceptOutput('stderr', chunk)) return; + appendText('stderr', stderrDecoder.write(chunk)); + }); + child.stdout.on('end', () => { + if (!options.binaryStdout && !exceededStream) appendText('stdout', stdoutDecoder.end()); + }); + child.stderr.on('end', () => { + if (!exceededStream) appendText('stderr', stderrDecoder.end()); }); child.on('error', (err) => { execTrace.emit('error'); fail(spawnRejectionError(abort, executable, cmd, args, err), 'spawn_error'); }); - - child.once('exit', (code, signal) => { - execTrace.emit('exit', { exitCode: code, signal }); - settlement.recordExit(code); - }); - child.once('close', (code, signal) => { - execTrace.emit('close', { exitCode: code, signal }); - settle(code); - }); }); } -/** Returns the result with `signal` added when a signal terminated the process. */ function execResult(ended: { signalCode: string | null }, result: ExecResult): ExecResult { return ended.signalCode ? { ...result, signal: ended.signalCode } : result; } @@ -572,26 +601,11 @@ export function runCmdBackground( } resolve({ stdout, stderr, exitCode: finalExitCode }); } - const settlement = createCommandKillSettlement({ - killProcessTree: () => killProcessTree(child, options), - settle, - }); - const abort = watchCommandAbort(options, () => { - execTrace.emit('abort'); - settlement.requestKill(); - }); + const { abort } = bindCommandLifecycle(child, options, execTrace, settle); child.on('error', (err) => { execTrace.emit('error'); if (finish('error')) reject(spawnRejectionError(abort, executable, cmd, args, err)); }); - child.once('exit', (code, signal) => { - execTrace.emit('exit', { exitCode: code, signal }); - settlement.recordExit(code); - }); - child.once('close', (code, signal) => { - execTrace.emit('close', { exitCode: code, signal }); - settle(code); - }); }); return { child, wait }; @@ -855,17 +869,36 @@ async function isFilePath(filePath: string): Promise { } } -function normalizeTimeoutMs(value: number | undefined): number | undefined { - if (!Number.isFinite(value)) return undefined; - const timeout = Math.floor(value as number); - if (timeout <= 0) return undefined; - return timeout; -} - /** * A killed command settles when its direct child exits: descendants can keep inherited pipes * open indefinitely. Both kill/exit orderings must settle once without waiting for `close`. */ + +function bindCommandLifecycle( + child: ReturnType, + options: Pick, + trace: ReturnType, + settle: (code: number | null) => void, +) { + const settlement = createCommandKillSettlement({ + killProcessTree: () => killProcessTree(child, options), + settle, + }); + const abort = watchCommandAbort(options, () => { + trace.emit('abort'); + settlement.requestKill(); + }); + child.once('exit', (code, signal) => { + trace.emit('exit', { exitCode: code, signal }); + settlement.recordExit(code); + }); + child.once('close', (code, signal) => { + trace.emit('close', { exitCode: code, signal }); + settle(code); + }); + return { settlement, abort }; +} + type CommandKillSettlement = { /** Signals the command's process tree, then settles the command if its child is gone. */ readonly requestKill: () => void; diff --git a/packages/host-kit/src/internal/host-process-liveness.test.ts b/packages/host-kit/src/internal/host-process-liveness.test.ts index 034658fd49..afe99fa315 100644 --- a/packages/host-kit/src/internal/host-process-liveness.test.ts +++ b/packages/host-kit/src/internal/host-process-liveness.test.ts @@ -21,6 +21,8 @@ import { readProcessIdentityFacts, } from './host-process.ts'; +const readFile = fs.readFileSync; + function psReturns(stdout: string, exitCode = 0): void { mockRunCmdSync.mockReturnValue({ stdout, stderr: '', exitCode }); } @@ -51,6 +53,11 @@ beforeEach(() => { }); mockRunCmdSync.mockReset(); mockRunCmd.mockReset(); + vi.spyOn(fs, 'readFileSync').mockImplementation((...args) => { + // The ps fixture must not borrow the real host's identity for a fabricated pid. + if (String(args[0]) === '/proc/sys/kernel/random/boot_id') throw new Error('ENOENT'); + return readFile(...args); + }); }); afterEach(() => { diff --git a/packages/host-kit/src/internal/host-process-stop-confirm.test.ts b/packages/host-kit/src/internal/host-process-stop-confirm.test.ts index 4d59d70012..f156670cbe 100644 --- a/packages/host-kit/src/internal/host-process-stop-confirm.test.ts +++ b/packages/host-kit/src/internal/host-process-stop-confirm.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import fs from 'node:fs'; import { afterEach, test, vi } from 'vitest'; // Every claim the stopper makes is about what the host answers, so one double answers both syscalls it @@ -16,6 +17,7 @@ import { type ProcessStopTarget, } from './host-process.ts'; +const readFile = fs.readFileSync; const PID = 4242; const BUDGET = { termTimeoutMs: 1_000, killTimeoutMs: 500 }; type Signal = 'SIGTERM' | 'SIGINT' | 'SIGKILL'; @@ -256,6 +258,11 @@ const STOP_CASES: HostCase[] = [ ]; function driveHost(model: HostCase): { signals: Signal[] } { + vi.spyOn(fs, 'readFileSync').mockImplementation((...args) => { + // This host model supplies process identity through its ps answers. + if (String(args[0]) === '/proc/sys/kernel/random/boot_id') throw new Error('ENOENT'); + return readFile(...args); + }); const signals: Signal[] = []; let psRefused = false; let ended = false; diff --git a/packages/host-kit/src/local-artifact-adapter.test.ts b/packages/host-kit/src/local-artifact-adapter.test.ts index 76f23ca0d0..8630885334 100644 --- a/packages/host-kit/src/local-artifact-adapter.test.ts +++ b/packages/host-kit/src/local-artifact-adapter.test.ts @@ -6,7 +6,7 @@ import { mkdtempForTestSync } from './internal/tmp-dir.fixtures.ts'; import { createLocalArtifactAdapter } from './local-artifact-adapter.ts'; test('local artifact adapter marks command outputs and temp files by visibility', async () => { - const adapter = createLocalArtifactAdapter(); + const adapter = createLocalArtifactAdapter({ cwd: process.cwd() }); const output = await adapter.reserveOutput(undefined, { field: 'path', ext: '.png', diff --git a/packages/host-kit/src/local-artifact-adapter.ts b/packages/host-kit/src/local-artifact-adapter.ts index 014d92ef2b..acefbb1523 100644 --- a/packages/host-kit/src/local-artifact-adapter.ts +++ b/packages/host-kit/src/local-artifact-adapter.ts @@ -1,4 +1,3 @@ -import { captureHostEnvironment } from './process.ts'; import { promises as fs } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; @@ -8,10 +7,8 @@ import type { LocalArtifactAdapterOptions, } from '@agent-device/contracts/artifact-adapter'; -export function createLocalArtifactAdapter( - options: LocalArtifactAdapterOptions = {}, -): ArtifactAdapter { - const cwd = options.cwd ?? captureHostEnvironment(process).cwd; +export function createLocalArtifactAdapter(options: LocalArtifactAdapterOptions): ArtifactAdapter { + const cwd = options.cwd; const tempDir = options.tempDir ?? os.tmpdir(); const rootDir = options.rootDir ? resolveLocalPath(options.rootDir, cwd) : undefined; diff --git a/packages/kernel/src/contracts.ts b/packages/kernel/src/contracts.ts index c352cdeaa4..a1aac81400 100644 --- a/packages/kernel/src/contracts.ts +++ b/packages/kernel/src/contracts.ts @@ -300,24 +300,6 @@ export function errorResponse( export const NO_ACTIVE_SESSION_MESSAGE = 'No active session. Run agent-device open first, then retry the command.'; -/** - * Whether the caller named the session it wants, traced from what the request carries rather than - * from the session string. Every request has a session *name*, because an unnamed one inherits the - * workspace's own session address, so comparing names cannot answer this. Both carriers count: - * every client sets `meta.sessionExplicit`, and the commands whose own input schema declares - * `--session` also deliver the value in `flags.session`. The flag bag reaches this predicate in - * both shapes the wire carries it in: a command's declared flag type, or a generic record from a - * runner that merges flags (batch steps); the string check below is what decides either way. - */ -export function namesSessionExplicitly(request: { - flags?: { session?: unknown } | Record | undefined; - meta?: { sessionExplicit?: boolean } | undefined; -}): boolean { - if (request.meta?.sessionExplicit === true) return true; - const value = request.flags?.session; - return typeof value === 'string' && value.trim().length > 0; -} - /** * Shared no-active-session failure used by handlers that require * an open session before dispatching. diff --git a/packages/kernel/src/contracts.test.ts b/packages/kernel/src/record-session-naming.test.ts similarity index 92% rename from packages/kernel/src/contracts.test.ts rename to packages/kernel/src/record-session-naming.test.ts index 45976dd723..f182e9b904 100644 --- a/packages/kernel/src/contracts.test.ts +++ b/packages/kernel/src/record-session-naming.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; -import { namesSessionExplicitly } from './contracts.ts'; +import { namesSessionExplicitly } from './record.ts'; test('a client that set the explicit-session meta names its session', () => { assert.equal(namesSessionExplicitly({ meta: { sessionExplicit: true } }), true); diff --git a/packages/kernel/src/record.ts b/packages/kernel/src/record.ts index 0d7f531a61..7fedf19663 100644 --- a/packages/kernel/src/record.ts +++ b/packages/kernel/src/record.ts @@ -291,6 +291,24 @@ type WithoutUndefined> = { [K in keyof T as undefined extends T[K] ? K : never]?: Exclude; }; +/** + * Whether the caller named the session it wants, traced from what the request carries rather than + * from the session string. Every request has a session *name*, because an unnamed one inherits the + * workspace's own session address, so comparing names cannot answer this. Both carriers count: + * every client sets `meta.sessionExplicit`, and the commands whose own input schema declares + * `--session` also deliver the value in `flags.session`. The flag bag reaches this predicate in + * both shapes the wire carries it in: a command's declared flag type, or a generic record from a + * runner that merges flags (batch steps); the string check below is what decides either way. + */ +export function namesSessionExplicitly(request: { + flags?: { session?: unknown } | Record | undefined; + meta?: { sessionExplicit?: boolean } | undefined; +}): boolean { + if (request.meta?.sessionExplicit === true) return true; + const value = request.flags?.session; + return typeof value === 'string' && value.trim().length > 0; +} + export function stripUndefined>(value: T): WithoutUndefined { const output = {} as WithoutUndefined; for (const [key, current] of Object.entries(value)) { diff --git a/packages/maestro/package.json b/packages/maestro/package.json index c56e47f68e..b046e13215 100644 --- a/packages/maestro/package.json +++ b/packages/maestro/package.json @@ -2,38 +2,56 @@ "name": "@agent-device/maestro", "version": "0.0.0", "private": true, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/callstack/agent-device.git", + "directory": "packages/maestro" + }, "sideEffects": false, "type": "module", - "description": "Private Maestro compatibility engine for agent-device.", - "dependencies": { - "@agent-device/ad-script": "workspace:*", - "@agent-device/capture-kit": "workspace:*", - "@agent-device/contracts": "workspace:*", - "@agent-device/host-kit": "workspace:*", - "@agent-device/kernel": "workspace:*", - "@agent-device/provision-kit": "workspace:*", - "@agent-device/selectors": "workspace:*" - }, + "description": "Optional Maestro compatibility engine plugin for agent-device.", "exports": { ".": { "types": "./src/index.ts", "default": "./src/index.ts" }, - "./replay-backend": { - "types": "./src/replay-backend/replay-maestro-backend.ts", - "default": "./src/replay-backend/replay-maestro-backend.ts" - }, - "./replay-backend-declaration": { - "types": "./src/replay-backend/replay-maestro-declaration.ts", - "default": "./src/replay-backend/replay-maestro-declaration.ts" - }, "./run-script-http": { "types": "./src/daemon-port/run-script-http.ts", "default": "./src/daemon-port/run-script-http.ts" + }, + "./agent-device": { + "types": "./src/plugin.ts", + "default": "./src/plugin.ts" } }, "devDependencies": { "undici": "7.30.1", - "yaml": "^2.9.0" + "yaml": "^2.9.0", + "@agent-device/test-kit": "workspace:*", + "@agent-device/ad-script": "workspace:*", + "@agent-device/capture-kit": "workspace:*", + "@agent-device/contracts": "workspace:*", + "@agent-device/host-kit": "workspace:*", + "@agent-device/kernel": "workspace:*", + "@agent-device/provision-kit": "workspace:*", + "@agent-device/selectors": "workspace:*", + "agent-device": "workspace:*" + }, + "scripts": { + "build": "tsdown --config tsdown.config.ts", + "prepack": "pnpm build" + }, + "files": [ + "dist" + ], + "publishConfig": { + "exports": { + "./agent-device": { + "types": "./dist/agent-device.d.mts", + "import": "./dist/agent-device.mjs" + } + }, + "access": "public" } } diff --git a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-fixtures.ts b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-fixtures.ts index c340894509..9480f62aea 100644 --- a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-fixtures.ts +++ b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-fixtures.ts @@ -1,4 +1,14 @@ +import { runCmd, withCommandHost } from '@agent-device/host-kit/command'; +import { createTestHostEnvironment } from '@agent-device/test-kit'; +import { + emitDiagnostic, + registerDiagnosticSensitiveValue, +} from '@agent-device/host-kit/diagnostics'; import type { CommandFlags } from '@agent-device/contracts/command'; +import { + assertSnapshotScreenOrigin, + readSnapshotClickabilityEvidence, +} from '@agent-device/contracts/capture'; import { formatRole } from '@agent-device/kernel/snapshot'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; @@ -21,8 +31,27 @@ export function makeSnapshot( /** The daemon-owned half of the port options: the runtime envelope flags and the network origin. */ export function makeRuntimeEnvelope( overrides: { flags?: CommandFlags; publicNetworkOnly?: boolean } = {}, -): Pick { +): Pick< + CreateDaemonMaestroRuntimeOperationsOptions, + | 'readSnapshotClickabilityEvidence' + | 'assertSnapshotScreenOrigin' + | 'flags' + | 'publicNetworkOnly' + | 'host' + | 'registerSensitiveValue' + | 'emitDiagnostic' + | 'runCommand' +> { return { + readSnapshotClickabilityEvidence, + assertSnapshotScreenOrigin, + host: createTestHostEnvironment(), + emitDiagnostic, + runCommand: ({ executable, args, host, ...options }, signal) => + withCommandHost({ host, requestEnv: undefined }, () => + runCmd(executable, args, { ...options, ...host, signal }), + ), + registerSensitiveValue: registerDiagnosticSensitiveValue, publicNetworkOnly: false, ...overrides, }; diff --git a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-support.test.ts b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-support.test.ts index ad1d7a5cfc..22fd587e3e 100644 --- a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-support.test.ts +++ b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-support.test.ts @@ -1,3 +1,7 @@ +import { + commandHostEnvironment, + withCommandExecutorOverride, +} from '@agent-device/host-kit/command'; import { expect, test, vi } from 'vitest'; import { invokeMaestroPublicOperation } from '../daemon-runtime-port-support.ts'; import { makeRuntimeEnvelope, makeDependencies } from './daemon-runtime-port-fixtures.ts'; @@ -123,3 +127,17 @@ test('preserves diagnostic metadata carried inside daemon error details', async details: { hint: 'Enable developer tools.', diagnosticId: 'diag-1' }, }); }); + +test('the runtime command adapter enters the supplied host scope', async () => { + const envelope = makeRuntimeEnvelope(); + const host = { ...envelope.host, env: { ...envelope.host.env, DEVELOPER_DIR: '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/fixture/Xcode' } }; + await withCommandExecutorOverride( + async () => { + expect(commandHostEnvironment().env.DEVELOPER_DIR).toBe('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/fixture/Xcode'); + return { stdout: '', stderr: '', exitCode: 0 }; + }, + async () => { + await envelope.runCommand({ executable: 'fixture', args: [], host }); + }, + ); +}); diff --git a/packages/maestro/src/daemon-port/__tests__/run-script-execution.test.ts b/packages/maestro/src/daemon-port/__tests__/run-script-execution.test.ts index fed45f972f..e138e87814 100644 --- a/packages/maestro/src/daemon-port/__tests__/run-script-execution.test.ts +++ b/packages/maestro/src/daemon-port/__tests__/run-script-execution.test.ts @@ -1,9 +1,11 @@ +import { makeRuntimeEnvelope } from './daemon-runtime-port-fixtures.ts'; +import { createTestHostEnvironment } from '@agent-device/test-kit'; import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; import { expect, test, vi } from 'vitest'; import { AppError, isRequestCanceledError } from '@agent-device/kernel/errors'; -import { executeRunScriptFile } from '../run-script-execution.ts'; +import { executeRunScriptFile as runScriptFile } from '../run-script-execution.ts'; import { MAX_RUN_SCRIPT_HTTP_RESPONSE_BYTES } from '../run-script-http.ts'; import { mkdtempForTestSync } from '../../tmp-dir.fixtures.ts'; import { @@ -12,6 +14,10 @@ import { skipWhenLoopbackUnavailable, } from './loopback.fixtures.ts'; +function executeRunScriptFile(request: Parameters[0]) { + return runScriptFile(request, createTestHostEnvironment(), makeRuntimeEnvelope().runCommand); +} + async function withLoopbackServer( handler: http.RequestListener, run: (url: string) => Promise, @@ -237,3 +243,13 @@ test('executeRunScriptFile refuses remote scripts before reading or running host fs.rmSync(root, { recursive: true, force: true }); } }); + +test('script children resolve paths against the supplied embedded host working directory', async () => { + const { root } = writeScript('output.location = "embedded-host";'); + const output = await runScriptFile( + { scriptPath: 'setup.js', env: {}, publicNetworkOnly: false }, + createTestHostEnvironment({ cwd: root, env: {} }), + makeRuntimeEnvelope().runCommand, + ); + expect(output).toEqual({ 'output.location': 'embedded-host' }); +}); diff --git a/packages/maestro/src/daemon-port/__tests__/wait-for-animation-to-end.test.ts b/packages/maestro/src/daemon-port/__tests__/wait-for-animation-to-end.test.ts index 4741c9b43a..0db39d83b4 100644 --- a/packages/maestro/src/daemon-port/__tests__/wait-for-animation-to-end.test.ts +++ b/packages/maestro/src/daemon-port/__tests__/wait-for-animation-to-end.test.ts @@ -1,3 +1,4 @@ +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { promises as fs } from 'node:fs'; import path from 'node:path'; import { expect, test } from 'vitest'; @@ -10,6 +11,7 @@ test('captures an explicit zero-timeout pair and accepts exactly 0.005% RGB diff let tempRoot: string | undefined; const stable = await waitForMaestroAnimationToEnd({ + emitDiagnostic, timeoutMs: 0, now: () => 0, capture: async (screenshotPath) => { @@ -29,6 +31,7 @@ test('retries changed pairs immediately until a matching pair is captured', asyn let tempRoot: string | undefined; const stable = await waitForMaestroAnimationToEnd({ + emitDiagnostic, timeoutMs: 2, now: () => now, capture: async (screenshotPath) => { @@ -58,6 +61,7 @@ test('treats dimension and capture failures as nonmatches before retrying', asyn let tempRoot: string | undefined; const stable = await waitForMaestroAnimationToEnd({ + emitDiagnostic, timeoutMs: 10, now: () => now, capture: async (screenshotPath) => { @@ -85,6 +89,7 @@ test('reports an expired deadline when no screenshot pair is stable', async () = let captureCount = 0; const stable = await waitForMaestroAnimationToEnd({ + emitDiagnostic, timeoutMs: 0, now: () => 0, capture: async (screenshotPath) => { @@ -106,6 +111,7 @@ test('propagates cancellation and cleans temporary screenshots', async () => { await expect( waitForMaestroAnimationToEnd({ + emitDiagnostic, timeoutMs: 10, now: () => 0, signal: controller.signal, diff --git a/packages/maestro/src/daemon-port/daemon-runtime-port-snapshot-source.ts b/packages/maestro/src/daemon-port/daemon-runtime-port-snapshot-source.ts index 5aa7b90d03..2059272164 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-port-snapshot-source.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-port-snapshot-source.ts @@ -1,6 +1,6 @@ import { AppError } from '@agent-device/kernel/errors'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; -import { copySnapshotClickabilityEvidence } from '@agent-device/contracts/capture'; +import { attachSnapshotClickabilityEvidence } from '@agent-device/contracts/capture'; import { MAESTRO_RUNTIME_ADAPTER_POLICY, type MaestroObservationIdentity, @@ -36,7 +36,9 @@ export function createDaemonMaestroSnapshotSource( if (!data || !Array.isArray(data.nodes)) { throw new AppError('COMMAND_FAILED', 'Maestro snapshot did not return node data.'); } - const snapshot = copySnapshotClickabilityEvidence(data, data as SnapshotState); + const snapshot = data as SnapshotState; + const clickability = options.readSnapshotClickabilityEvidence(data); + if (clickability) attachSnapshotClickabilityEvidence(snapshot, clickability); cached = { generation: context.generation, snapshot }; return snapshot; }; diff --git a/packages/maestro/src/daemon-port/daemon-runtime-port-support.ts b/packages/maestro/src/daemon-port/daemon-runtime-port-support.ts index a8b87f36d2..a831484019 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-port-support.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-port-support.ts @@ -1,3 +1,5 @@ +import type { ReplayBackendHost } from '@agent-device/contracts/replay-backend'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { CommandFlags } from '@agent-device/contracts/command'; import path from 'node:path'; import type { @@ -22,7 +24,14 @@ export type MaestroDaemonOperationInvoke = ( request: MaestroDaemonOperationRequest, ) => Promise; -export type CreateDaemonMaestroRuntimeOperationsOptions = { +export type CreateDaemonMaestroRuntimeOperationsOptions = Pick< + ReplayBackendHost, + 'readSnapshotClickabilityEvidence' | 'assertSnapshotScreenOrigin' +> & { + readonly host: HostEnvironment; + readonly runCommand: ReplayBackendHost['runCommand']; + readonly emitDiagnostic: ReplayBackendHost['emitDiagnostic']; + readonly registerSensitiveValue: (value: string) => void; readonly invoke: MaestroDaemonOperationInvoke; /** The runtime envelope every operation carries: platform, target, device, and recording flags. */ readonly flags?: CommandFlags; diff --git a/packages/maestro/src/daemon-port/daemon-runtime-port.ts b/packages/maestro/src/daemon-port/daemon-runtime-port.ts index 44ae555403..86d5bc94fe 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-port.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-port.ts @@ -8,9 +8,7 @@ import { type MaestroRuntimeOperations, type MaestroRuntimePort, } from '@agent-device/maestro'; -import { registerDiagnosticSensitiveValue } from '@agent-device/host-kit/diagnostics'; import { AppError } from '@agent-device/kernel/errors'; -import { assertSnapshotScreenOrigin } from '@agent-device/contracts/capture'; import { stripUndefined } from '@agent-device/kernel/record'; import { executeRunScriptFile } from './run-script-execution.ts'; import { captureMaestroComparisonScreenshot } from './maestro-comparison-screenshot.ts'; @@ -138,7 +136,7 @@ function createDaemonMaestroRuntimeParts(options: CreateDaemonMaestroRuntimeOper context: MaestroRuntimeOperationContext, delayMs?: number, ): Promise => { - registerDiagnosticSensitiveValue(text); + options.registerSensitiveValue(text); await invokeMutation( { kind: 'typeText', text, ...(delayMs === undefined ? {} : { delayMs }) }, context, @@ -301,7 +299,8 @@ function createDaemonMaestroRuntimeParts(options: CreateDaemonMaestroRuntimeOper input.durationMs, platform, ); - if (gesture) await assertSnapshotScreenOrigin(snapshot.nodes, 'Maestro scroll target'); + if (gesture) + await options.assertSnapshotScreenOrigin(snapshot.nodes, 'Maestro scroll target'); await invokeMutation( gesture ? { kind: 'swipe', ...gesture } @@ -342,6 +341,7 @@ function createDaemonMaestroRuntimeParts(options: CreateDaemonMaestroRuntimeOper }, waitForAnimationToEnd: async (input, context) => { const visualStabilityReached = await waitForMaestroAnimationToEnd({ + emitDiagnostic: options.emitDiagnostic, timeoutMs: input.timeoutMs ?? MAESTRO_RUNTIME_ADAPTER_POLICY.animationWaitTimeoutMs, now: options.dependencies.now, signal: context.signal, @@ -356,15 +356,19 @@ function createDaemonMaestroRuntimeParts(options: CreateDaemonMaestroRuntimeOper artifactPaths: artifactPathsFromData(await invoke({ kind: 'screenshot', path: input.path })), }), runScript: async (input, context) => ({ - outputEnv: await executeRunScriptFile({ - scriptPath: resolveScriptPath(input.file, context, options.sourcePath), - publicNetworkOnly: options.publicNetworkOnly, - env: { - ...context.env, - ...(input.env ? stringifyEnvironment(input.env) : {}), + outputEnv: await executeRunScriptFile( + { + scriptPath: resolveScriptPath(input.file, context, options.sourcePath), + publicNetworkOnly: options.publicNetworkOnly, + env: { + ...context.env, + ...(input.env ? stringifyEnvironment(input.env) : {}), + }, + signal: context.signal, }, - signal: context.signal, - }), + options.host, + options.runCommand, + ), }), }; return { diff --git a/packages/maestro/src/daemon-port/daemon-runtime-tap.ts b/packages/maestro/src/daemon-port/daemon-runtime-tap.ts index 1ebf721e7b..6b420b8efe 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-tap.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-tap.ts @@ -1,5 +1,4 @@ import { AppError, asAppError } from '@agent-device/kernel/errors'; -import { assertSnapshotScreenOrigin } from '@agent-device/contracts/capture'; import { INTERACTION_ERROR_REASONS } from '@agent-device/selectors/interaction-error'; import type { Rect } from '@agent-device/kernel/snapshot'; import { @@ -12,7 +11,6 @@ import { type MaestroTargetMatch, type MaestroTargetQuery, } from '@agent-device/maestro'; -import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { pointInsideRect } from '@agent-device/kernel/rect-center'; import { withMaestroScreenshotBaseline, @@ -52,7 +50,7 @@ export async function resolveDaemonMaestroTarget(params: { { context, snapshot: snapshots.capture, dependencies: options.dependencies }, deadline, ); - await assertSnapshotScreenOrigin(currentSnapshot.nodes, 'Maestro selector target'); + await options.assertSnapshotScreenOrigin(currentSnapshot.nodes, 'Maestro selector target'); const match = resolveTypedMaestroTarget({ query: input, context, @@ -93,6 +91,7 @@ export async function tapTargetAndSettle( if (options.platform === 'ios') { await withMaestroScreenshotBaseline({ + emitDiagnostic: options.emitDiagnostic, signal: context.signal, capture: async (path) => { metrics.screenshotCaptures += 1; @@ -232,7 +231,7 @@ async function clickSelector( expectedPoint: { x: number; y: number }, flags: MaestroClickOptions, ): Promise { - emitDiagnostic({ + options.emitDiagnostic({ level: 'debug', phase: 'maestro_tap_dispatch', data: { kind: 'selector', selectorKey: selector.key, expectedPoint }, @@ -261,7 +260,7 @@ export async function clickMaestroTargetPoint( flags: MaestroClickOptions, ): Promise { if (!point) throw new AppError('COMMAND_FAILED', 'Maestro target did not resolve to a point.'); - emitDiagnostic({ + options.emitDiagnostic({ level: 'debug', phase: 'maestro_tap_dispatch', data: { kind: 'point', point }, diff --git a/packages/maestro/src/daemon-port/maestro-screenshot-comparison.ts b/packages/maestro/src/daemon-port/maestro-screenshot-comparison.ts index 167b03b4bc..86d048eee2 100644 --- a/packages/maestro/src/daemon-port/maestro-screenshot-comparison.ts +++ b/packages/maestro/src/daemon-port/maestro-screenshot-comparison.ts @@ -3,7 +3,7 @@ import os from 'node:os'; import path from 'node:path'; import { MAESTRO_RUNTIME_ADAPTER_POLICY } from '@agent-device/maestro'; import { createRequestCanceledError, isRequestCanceledError } from '@agent-device/kernel/errors'; -import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import type { ReplayBackendHost } from '@agent-device/contracts/replay-backend'; import { computePngRgbDifferenceAsync } from '@agent-device/capture-kit/png-worker-client'; import type { PngRgbDifferenceResult } from '@agent-device/capture-kit/png-rgb-difference'; @@ -17,6 +17,7 @@ type MaestroScreenshotCaptureOptions = { }; export async function withMaestroScreenshotBaseline(options: { + readonly emitDiagnostic: ReplayBackendHost['emitDiagnostic']; readonly signal?: AbortSignal; readonly capture: (path: string) => Promise; readonly run: (baseline: MaestroScreenshotBaseline) => Promise; @@ -30,7 +31,13 @@ export async function withMaestroScreenshotBaseline(options: { if (!baselineAvailable || !(await captureMaestroScreenshot(options, afterPath))) { return undefined; } - return await compareMaestroScreenshotFiles(beforePath, afterPath, options.signal, 'tap'); + return await compareMaestroScreenshotFiles( + beforePath, + afterPath, + options.signal, + 'tap', + options.emitDiagnostic, + ); }, }); }); @@ -55,6 +62,7 @@ export async function compareMaestroScreenshotFiles( secondPath: string, signal: AbortSignal | undefined, purpose: 'animation' | 'tap', + emitDiagnostic: ReplayBackendHost['emitDiagnostic'], ): Promise { try { const [firstBuffer, secondBuffer] = await Promise.all([ @@ -68,7 +76,7 @@ export async function compareMaestroScreenshotFiles( 'Maestro screenshot', ); throwIfMaestroScreenshotAborted(signal); - return screenshotsMatch(comparison, purpose); + return screenshotsMatch(comparison, purpose, emitDiagnostic); } catch (error) { rethrowCancellation(error, signal); emitDiagnostic({ @@ -103,14 +111,15 @@ export async function captureMaestroScreenshot( function screenshotsMatch( comparison: PngRgbDifferenceResult, purpose: 'animation' | 'tap', + emitDiagnostic: ReplayBackendHost['emitDiagnostic'], ): boolean { if (comparison.status !== 'compared') { - emitComparison(purpose, comparison.status, comparison); + emitComparison(purpose, comparison.status, comparison, emitDiagnostic); return false; } const differencePercent = comparison.differencePercent; const matches = differencePercent <= MAESTRO_RUNTIME_ADAPTER_POLICY.animationDifferencePercent; - emitComparison(purpose, matches ? 'stable' : 'changed', comparison); + emitComparison(purpose, matches ? 'stable' : 'changed', comparison, emitDiagnostic); return matches; } @@ -118,6 +127,7 @@ function emitComparison( purpose: 'animation' | 'tap', result: 'stable' | 'changed' | 'dimension_mismatch' | 'data_length_mismatch', comparison: PngRgbDifferenceResult, + emitDiagnostic: ReplayBackendHost['emitDiagnostic'], ): void { emitDiagnostic({ level: 'debug', diff --git a/packages/maestro/src/daemon-port/run-script-execution.ts b/packages/maestro/src/daemon-port/run-script-execution.ts index 552097ca7a..042dbaeb62 100644 --- a/packages/maestro/src/daemon-port/run-script-execution.ts +++ b/packages/maestro/src/daemon-port/run-script-execution.ts @@ -1,8 +1,9 @@ +import type { HostEnvironment } from '@agent-device/kernel/source-value'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { AppError } from '@agent-device/kernel/errors'; -import { runCmd } from '@agent-device/host-kit/command'; +import type { ReplayBackendHost } from '@agent-device/contracts/replay-backend'; import { assertMaestroScriptsTrusted } from '../internal/engine-flow.ts'; import type { RunScriptChildOutput, RunScriptRequest } from './run-script-vm.ts'; @@ -20,17 +21,24 @@ const RUN_SCRIPT_CHILD_TIMEOUT_MS = 2 * RUN_SCRIPT_TIMEOUT_MS + 5_000; */ export async function executeRunScriptFile( request: RunScriptRequest & { signal?: AbortSignal }, + host: HostEnvironment, + runCommand: ReplayBackendHost['runCommand'], ): Promise> { const { signal, ...childRequest } = request; assertMaestroScriptsTrusted({ trustedScripts: !childRequest.publicNetworkOnly }, 'runScript'); - const result = await runCmd(process.execPath, resolveRunScriptChildArgs('run-script-child'), { - stdin: JSON.stringify(childRequest), + const result = await runCommand( + { + executable: process.execPath, + args: resolveRunScriptChildArgs('run-script-child'), + host, + stdin: JSON.stringify(childRequest), + timeoutMs: RUN_SCRIPT_CHILD_TIMEOUT_MS, + // Its own process group, so a cancel or timeout also reaps an in-flight `http.post` child. + detached: true, + allowFailure: true, + }, signal, - timeoutMs: RUN_SCRIPT_CHILD_TIMEOUT_MS, - // Its own process group, so a cancel or timeout also reaps an in-flight `http.post` child. - detached: true, - allowFailure: true, - }); + ); const output = readScriptChildOutput(result.stdout); if (output && 'outputEnv' in output) return output.outputEnv; if (output) throw new AppError(output.error.code, output.error.message, output.error.details); diff --git a/packages/maestro/src/daemon-port/wait-for-animation-to-end.ts b/packages/maestro/src/daemon-port/wait-for-animation-to-end.ts index ee8db1e97e..8c077d5e24 100644 --- a/packages/maestro/src/daemon-port/wait-for-animation-to-end.ts +++ b/packages/maestro/src/daemon-port/wait-for-animation-to-end.ts @@ -1,4 +1,5 @@ import path from 'node:path'; +import type { ReplayBackendHost } from '@agent-device/contracts/replay-backend'; import { AppError } from '@agent-device/kernel/errors'; import { captureMaestroScreenshot, @@ -8,6 +9,7 @@ import { } from './maestro-screenshot-comparison.ts'; export type MaestroAnimationWaitOptions = { + readonly emitDiagnostic: ReplayBackendHost['emitDiagnostic']; readonly timeoutMs: number; readonly now: () => number; readonly signal?: AbortSignal; @@ -47,8 +49,13 @@ async function capturePairMatches( ]; if (!captures[0] || !captures[1]) return false; return ( - (await compareMaestroScreenshotFiles(firstPath, secondPath, options.signal, 'animation')) === - true + (await compareMaestroScreenshotFiles( + firstPath, + secondPath, + options.signal, + 'animation', + options.emitDiagnostic, + )) === true ); } diff --git a/packages/maestro/src/index.test.ts b/packages/maestro/src/index.test.ts index 4a7ec925e8..c6cf0e6abb 100644 --- a/packages/maestro/src/index.test.ts +++ b/packages/maestro/src/index.test.ts @@ -22,18 +22,13 @@ describe('@agent-device/maestro facade', () => { test('keeps the plugin and helper off the engine entry and declares pure modules', () => { const manifest = JSON.parse( fs.readFileSync(path.join(import.meta.dirname, '../package.json'), 'utf8'), - ) as { exports: Record; sideEffects?: boolean }; - // The runScript HTTP helper is a subpath, not part of the engine entry, and the replay - // backend plugin (#3377) is the only other way in: its engine-free declaration lets help list - // the backend without evaluating the engine. This pins the surface; - // scripts/__tests__/eager-closure-budgets.test.ts is what keeps `.` from starting to evaluate - // host-kit, capture-kit, or provision-kit. - expect(Object.keys(manifest.exports)).toEqual([ - '.', - './replay-backend', - './replay-backend-declaration', - './run-script-http', - ]); + ) as { + exports: Record; + publishConfig: { exports: Record }; + sideEffects?: boolean; + }; + expect(Object.keys(manifest.exports)).toEqual(['.', './run-script-http', './agent-device']); + expect(Object.keys(manifest.publishConfig.exports)).toEqual(['./agent-device']); expect(manifest.sideEffects).toBe(false); }); }); diff --git a/packages/maestro/src/index.ts b/packages/maestro/src/index.ts index 94d51c0fa4..37a5638570 100644 --- a/packages/maestro/src/index.ts +++ b/packages/maestro/src/index.ts @@ -5,7 +5,6 @@ export { type MaestroActionEvent, type MaestroCompletedActionEvent, type MaestroExecutionObserver, - type MaestroExecutionOptions, type MaestroExecutionOutcome, type MaestroFailedAction, type MaestroFlow, @@ -13,26 +12,12 @@ export { export type { MaestroSourceReader } from './internal/program-loader.ts'; -export { - collectMaestroFlowSources, - type MaestroOptionalSourceReader, -} from './internal/source-closure.ts'; +export { collectMaestroFlowSources } from './internal/source-closure.ts'; -export { - exportReplayActionsToMaestro, - type MaestroExportOptions, - type MaestroExportResult, - type MaestroExportWarning, - type MaestroSelectorProjection, -} from './internal/export-flow.ts'; +export { exportReplayActionsToMaestro } from './internal/export-flow.ts'; export { MAESTRO_SELECTOR_PROJECTION } from './internal/selector-vocabulary.ts'; -export { - MAESTRO_COMPAT_LIMITATIONS, - MAESTRO_COMPAT_SUPPORTED_CAPABILITIES, -} from './internal/facade-support.ts'; - export { createMaestroRuntimePort, literalFromMaestroRegex, @@ -50,16 +35,12 @@ export { type MaestroRuntimeMetrics, type MaestroRuntimeCommand, type MaestroRuntimeOperationContext, - type MaestroRuntimeOperationResult, type MaestroRuntimeOperations, type MaestroRuntimePort, - type MaestroRuntimePortLifecycle, type MaestroRuntimeReadContext, type MaestroSelector, type MaestroSinglePointerGestureInput, type MaestroSnapshotTargetQuery, - type MaestroTargetFailureReason, type MaestroTargetMatch, type MaestroTargetQuery, - type MaestroTargetResolution, } from './internal/facade-runtime-port.ts'; diff --git a/packages/maestro/src/internal/export-flow.test.ts b/packages/maestro/src/internal/export-flow.test.ts new file mode 100644 index 0000000000..edc12e281e --- /dev/null +++ b/packages/maestro/src/internal/export-flow.test.ts @@ -0,0 +1,308 @@ +import { parseAllDocuments } from 'yaml'; +import { describe, expect, test } from 'vitest'; +import { AppError } from '@agent-device/kernel/errors'; +import { + exportReplayActionsToMaestro, + inspectMaestroFlow, + MAESTRO_SELECTOR_PROJECTION, +} from '../index.ts'; +import { parseReplayScriptDetailed, readReplayScriptMetadata } from '@agent-device/ad-script'; +import { projectSelectorExpression } from '@agent-device/selectors'; + +describe('exportReplayScriptToMaestro', () => { + test('exports app launch, selectors, input, keyboard, assertions, and screenshots', () => { + const result = exportReplayScriptToMaestro(`env USER="Ada" +context platform=ios target=mobile +open com.example.app --relaunch +click id="email" +fill id="email" "ada@example.com" +keyboard dismiss +find text "Continue" exists +screenshot "./artifacts/checkout" +`); + + const docs = parseYamlDocs(result.yaml); + expect(() => inspectMaestroFlow(result.yaml, 'export.yaml')).not.toThrow(); + expect(docs).toEqual([ + { appId: 'com.example.app', env: { USER: 'Ada' } }, + [ + { launchApp: { appId: 'com.example.app', stopApp: true } }, + { tapOn: { id: 'email' } }, + { tapOn: { id: 'email' } }, + { inputText: 'ada@example.com' }, + 'hideKeyboard', + { assertVisible: 'Continue' }, + { takeScreenshot: './artifacts/checkout' }, + ], + ]); + expect(result.warnings).toEqual([ + { + line: 5, + action: 'fill id="email" ada@example.com', + message: + 'fill exports as tapOn + inputText; Maestro may append text instead of replacing existing field contents', + }, + ]); + }); + + test('exports each app target when a script switches apps and returns', () => { + const result = exportReplayScriptToMaestro(`open com.example.shop +open com.example.auth +open com.example.shop +`); + + expect(() => inspectMaestroFlow(result.yaml, 'apps.yaml')).not.toThrow(); + expect(parseYamlDocs(result.yaml)).toEqual([ + { appId: 'com.example.shop' }, + [ + { launchApp: { appId: 'com.example.shop' } }, + { launchApp: { appId: 'com.example.auth' } }, + { launchApp: { appId: 'com.example.shop' } }, + ], + ]); + expect(result.warnings).toEqual([]); + }); + + test('exports the empty-fill clear as eraseText, never a vacuous inputText', () => { + // `fill ""` is the clear-field primitive (#2063); Maestro's `inputText: ""` types + // nothing, so the recorded clear must become its clear verb. + const result = exportReplayScriptToMaestro(`context platform=ios target=mobile +open com.example.app +fill id="email" "" +`); + + const docs = parseYamlDocs(result.yaml); + expect(docs[1]).toEqual([ + { launchApp: { appId: 'com.example.app' } }, + { tapOn: { id: 'email' } }, + 'eraseText', + ]); + expect(result.warnings).toEqual([ + { + line: 3, + action: 'fill id="email"', + message: + 'fill "" exports as tapOn + eraseText; Maestro erases at most its 50-character default', + }, + ]); + }); + + test('exports coordinate gestures and sleep waits with warnings', () => { + const result = exportReplayScriptToMaestro(`open com.example.app +click 120 240 +swipe 200 700 200 200 --count 2 +wait 500 +`); + + expect(parseYamlDocs(result.yaml)).toEqual([ + { appId: 'com.example.app' }, + [ + { launchApp: { appId: 'com.example.app' } }, + { tapOn: { point: '120,240' } }, + { swipe: { start: '200,700', end: '200,200', duration: 100 } }, + { swipe: { start: '200,700', end: '200,200', duration: 100 } }, + { waitForAnimationToEnd: { timeout: 500 } }, + ], + ]); + expect(result.warnings).toEqual([ + { + line: 4, + action: 'wait 500', + message: + 'wait exports as waitForAnimationToEnd and may return before the full duration', + }, + ]); + }); + + test('exports wait stable as waitForAnimationToEnd and text or selector waits with their timeouts', () => { + const result = exportReplayScriptToMaestro(`open com.example.app +wait stable +wait stable 500 3000 +wait text "Ready" 2000 +wait 'id="done"' 4000 +wait id="save" enabled=true 25000 +wait text Sign in 2000 +`); + + expect(parseYamlDocs(result.yaml)).toEqual([ + { appId: 'com.example.app' }, + [ + { launchApp: { appId: 'com.example.app' } }, + 'waitForAnimationToEnd', + { waitForAnimationToEnd: { timeout: 3000 } }, + { extendedWaitUntil: { visible: 'Ready', timeout: 2000 } }, + { extendedWaitUntil: { visible: { id: 'done' }, timeout: 4000 } }, + { extendedWaitUntil: { visible: { id: 'save', enabled: true }, timeout: 25000 } }, + { extendedWaitUntil: { visible: 'Sign in', timeout: 2000 } }, + ], + ]); + const stableWarning = + 'wait stable exports as waitForAnimationToEnd, which uses its own screen-stability threshold instead of the quiet window'; + expect(result.warnings).toEqual([ + { line: 2, action: 'wait stable', message: stableWarning }, + { line: 3, action: 'wait stable 500 3000', message: stableWarning }, + ]); + }); + + test('rejects wait forms that have no on-screen text to wait for', () => { + const run = () => + exportReplayScriptToMaestro(`open com.example.app +wait @e3 +wait text +wait stable 500 junk +wait visible label="Save" 25000 +`); + expect(run).toThrowError(AppError); + expect(run).toThrowError('line 2 (wait @e3): wait @ref names a session-local ref'); + expect(run).toThrowError('line 3 (wait text): wait text requires the text to wait for'); + expect(run).toThrowError( + 'line 4 (wait stable 500 junk): wait stable takes at most a numeric quietMs and timeoutMs', + ); + // The whole selector reaches the projection, which refuses `visible`; it never exports as text. + expect(run).toThrowError( + 'line 5 (wait visible label="Save" 25000): wait selector is not Maestro-compatible', + ); + }); + + // #3197: `scroll --until` became part of a scroll action, so the export names + // the stop condition it cannot carry instead of exporting a bare page scroll. + test('warns when scroll --until exports as a bare Maestro scroll', () => { + const result = exportReplayScriptToMaestro(`open com.example.app +scroll down --until 'id="far-button"' +`); + + expect(parseYamlDocs(result.yaml)).toEqual([ + { appId: 'com.example.app' }, + [{ launchApp: { appId: 'com.example.app' } }, 'scroll'], + ]); + expect(result.warnings).toEqual([ + { + line: 2, + // The action label names positionals only, so the flag shows in the message. + action: 'scroll down', + message: 'scroll --until id="far-button" is not represented by Maestro scroll', + }, + ]); + }); + + test('warns when explicit long-press durations export to Maestro defaults', () => { + const result = exportReplayScriptToMaestro(`open com.example.app +longpress "label=\\"Last message\\"" 800 +click id="hold-button" --hold-ms 1200 +press text="Retry" --hold-ms 1500 +`); + + expect(parseYamlDocs(result.yaml)).toEqual([ + { appId: 'com.example.app' }, + [ + { launchApp: { appId: 'com.example.app' } }, + { longPressOn: { text: 'Last message' } }, + { longPressOn: { id: 'hold-button' } }, + { longPressOn: { text: 'Retry' } }, + ], + ]); + expect(result.warnings).toEqual([ + { + line: 2, + action: 'longpress label="Last message" 800', + message: + 'label= selectors export as Maestro text; Maestro text matching is broader than agent-device label-only matching', + }, + { + line: 2, + action: 'longpress label="Last message" 800', + message: + 'long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of 800ms', + }, + { + line: 3, + action: 'click id="hold-button"', + message: + 'long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of 1200ms', + }, + { + line: 4, + action: 'press text="Retry"', + message: + 'long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of 1500ms', + }, + ]); + }); + + test('warns when double-tap and hold exports ignore repeated tap options', () => { + const result = exportReplayScriptToMaestro(`open com.example.app +click id="retry" --double-tap --count 2 --interval-ms 200 +press text="Hold" --hold-ms 1000 --count 3 --interval-ms 150 +`); + + expect(parseYamlDocs(result.yaml)).toEqual([ + { appId: 'com.example.app' }, + [ + { launchApp: { appId: 'com.example.app' } }, + { doubleTapOn: { id: 'retry' } }, + { longPressOn: { text: 'Hold' } }, + ], + ]); + expect(result.warnings).toEqual([ + { + line: 2, + action: 'click id="retry"', + message: 'tap --count 2 is not represented by Maestro doubleTapOn', + }, + { + line: 2, + action: 'click id="retry"', + message: 'tap --interval-ms 200 is not represented by Maestro doubleTapOn', + }, + { + line: 3, + action: 'press text="Hold"', + message: + 'long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of 1000ms', + }, + { + line: 3, + action: 'press text="Hold"', + message: 'tap --count 3 is not represented by Maestro longPressOn', + }, + { + line: 3, + action: 'press text="Hold"', + message: 'tap --interval-ms 150 is not represented by Maestro longPressOn', + }, + ]); + }); + + test('rejects native-only replay actions', () => { + expect(() => + exportReplayScriptToMaestro(`open com.example.app +snapshot -i +get text id="status" +`), + ).toThrowError(AppError); + try { + exportReplayScriptToMaestro(`open com.example.app +snapshot -i +get text id="status" +`); + } catch (error) { + expect(error).toBeInstanceOf(AppError); + expect((error as AppError).message).toContain('line 2 (snapshot)'); + expect((error as AppError).message).toContain('line 3 (get text id="status")'); + } + }); +}); + +function exportReplayScriptToMaestro(script: string) { + const parsed = parseReplayScriptDetailed(script); + return exportReplayActionsToMaestro(parsed.actions, { + actionLines: parsed.actionLines, + metadata: readReplayScriptMetadata(script), + resolveSelector: (expression) => + projectSelectorExpression(expression, MAESTRO_SELECTOR_PROJECTION), + }); +} + +function parseYamlDocs(script: string): unknown[] { + return parseAllDocuments(script).map((doc) => doc.toJSON()); +} diff --git a/packages/maestro/src/internal/facade-support.ts b/packages/maestro/src/internal/facade-support.ts deleted file mode 100644 index ae1d71f7dd..0000000000 --- a/packages/maestro/src/internal/facade-support.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { - MAESTRO_COMPAT_LIMITATIONS, - MAESTRO_COMPAT_SUPPORTED_CAPABILITIES, -} from './support-matrix.ts'; diff --git a/packages/maestro/src/internal/program-ir-command-parser-fuzz-coverage.test.ts b/packages/maestro/src/internal/program-ir-command-parser-fuzz-coverage.test.ts new file mode 100644 index 0000000000..08df4493c9 --- /dev/null +++ b/packages/maestro/src/internal/program-ir-command-parser-fuzz-coverage.test.ts @@ -0,0 +1,32 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { maestroValidationArb } from '@agent-device/test-kit'; +import { SUPPORTED_MAESTRO_COMMAND_NAMES } from './program-ir-command-parser.ts'; + +const sample = fc.sample(maestroValidationArb, { numRuns: 3_000, seed: 1 }); + +function coversCommand(line: string, command: string): boolean { + const trimmed = line.trim(); + return trimmed === `- ${command}` || trimmed.startsWith(`- ${command}:`); +} + +describe('shape coverage against the converter', () => { + it('does not count invalid command-name prefixes as coverage', () => { + expect(coversCommand('- tapOnPoint: 10,20', 'tapOn')).toBe(false); + expect(coversCommand('- inputTextt: Login', 'inputText')).toBe(false); + expect(coversCommand('- tapOn: Login', 'tapOn')).toBe(true); + expect(coversCommand(' - back', 'back')).toBe(true); + }); + + it('emits every command the converter supports', () => { + const emitted = new Set( + sample.flatMap((entry) => { + const { payload } = JSON.parse(entry) as { payload: string | string[] }; + return typeof payload === 'string' ? payload.split('\n') : []; + }), + ); + const covered = (command: string) => [...emitted].some((line) => coversCommand(line, command)); + const missing = SUPPORTED_MAESTRO_COMMAND_NAMES.filter((command) => !covered(command)); + expect(missing).toEqual([]); + }); +}); diff --git a/packages/maestro/src/internal/support-matrix.ts b/packages/maestro/src/internal/support-matrix.ts deleted file mode 100644 index dc72bcc5ac..0000000000 --- a/packages/maestro/src/internal/support-matrix.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const MAESTRO_COMPAT_SUPPORTED_CAPABILITIES = [ - 'Flows: launchApp (with clearState, permissions, and Apple-only launch arguments; permissions apply after state clearing but before launch, and a launchApp without permissions touches nothing — there is no silent all: allow default); setPermissions (mid-flow permission grants, denials, and resets; all resolves in the backend — one simctl call on iOS, the declared permissions on Android — with specific entries overriding after it); runFlow file/inline; runFlow.when and repeat.while conditions (platform, visible, notVisible, and true, all re-evaluated before every repeat iteration); onFlowStart/onFlowComplete; repeat with times, while, or both; and retry.', - 'Interactions: tapOn, doubleTapOn, longPressOn, inputText on the focused element, eraseText (up to 10000 characters), openLink, hideKeyboard, basic pressKey, and back; selector targets poll until available and support recursive index, childOf, above, below, leftOf, rightOf, containsChild, containsDescendants, points, and optional; outer command labels are metadata, not target selectors.', - 'Assertions and navigation: assertVisible, assertNotVisible, assertTrue (literal values and ${VAR} lookups only; "", "false", "0", "null", and "undefined" are falsy, everything else is truthy), extendedWaitUntil, scroll, scrollUntilVisible, absolute/percentage/target swipe, takeScreenshot, waitForAnimationToEnd, clearState, stopApp, and killApp (system-initiated process death: am kill on ADB-backed Android devices, which refuse a foreground target with android-kill-requires-background-app — background the app first, for example pressKey: Home — and fail a target whose process survives with android-kill-process-survived; iOS, Limrun, and WebDriver-provider backends run it as stopApp).', - 'Scripts: ordered runScript file/env scripts with http.post, json, and output variables; evalScript inline expressions run flow-scoped JavaScript and write output.* leaves for later steps.', -] as const; - -export const MAESTRO_COMPAT_LIMITATIONS = [ - 'Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict: current runtimes refuse a targeted notifications change and leave notifications untouched under all.', - 'Runtime: iOS and Android only; launchApp.clearState and standalone clearState support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading - unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported.', - 'Expressions: evalScript and condition true: fields (runFlow.when and repeat.while share one evaluator) are evaluated as JavaScript (flow env and prior output leaves are string-typed); a true: field that is a boolean, a maestro.platform comparison, or plain literal text after ${VAR} lookups is decided without JavaScript, with the assertTrue falsy table for literal text. Other fields stay literal or ${VAR} lookup-only — assertTrue supports literals and bare lookups, and other expression-shaped payloads fail loud.', - 'Environment: flow env is the default, AD_VAR_* overrides it, and CLI -e KEY=VALUE wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and AD_* stays reserved.', - 'Failure diagnostics: resolved targets and runFlow paths are rendered, while inputText payloads remain hidden; do not place secrets in diagnostic identifiers.', - 'Trust: runScript, evalScript, and JavaScript condition true: fields execute flow scripts via node:vm, which is not a security sandbox. runScript runs in a daemon child process with a 30 s script budget. It may make http.post network requests (30 s each, response bodies up to 8 MiB), and its output keys cannot contain a dot. Remote flows refuse runScript before reading its file, including files supplied in the replay bundle, and refuse evalScript and true: fields that need JavaScript. Run these scripts only in trusted local flows. Local runScript paths refer to the daemon filesystem: relative paths resolve from the containing flow, and absolute paths and symlinks are allowed.', - 'Remote screenshots: takeScreenshot uses a daemon-generated path and reports that path in artifactPaths. The flow cannot choose a file destination on the daemon host. Animation waits and tap retry comparisons use temporary screenshots that are removed after comparison.', - 'Errors and tracking: unsupported commands and fields fail with source context when available; open a focused issue only when implementation work is planned.', -] as const; - -export const MAESTRO_COMPATIBILITY_ADR_URL = - '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/callstack/agent-device/blob/main/docs/adr/0015-direct-maestro-engine.md'; - -export const MAESTRO_COMPATIBILITY_ISSUE_URL = - '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/callstack/agent-device/issues/new'; - -export function formatMaestroCompatibilityReference(): string { - return [ - 'Supported subset:', - ...MAESTRO_COMPAT_SUPPORTED_CAPABILITIES.map((capability) => ` - ${capability}`), - '', - 'Boundaries:', - ...MAESTRO_COMPAT_LIMITATIONS.map((limitation) => ` - ${limitation}`), - ].join('\n'); -} diff --git a/packages/maestro/src/plugin.test.ts b/packages/maestro/src/plugin.test.ts new file mode 100644 index 0000000000..f1abaeb694 --- /dev/null +++ b/packages/maestro/src/plugin.test.ts @@ -0,0 +1,114 @@ +import assert from 'node:assert/strict'; +import { beforeEach, expect, test, vi } from 'vitest'; +import type { ReplayBackendHost } from '@agent-device/contracts/replay-backend'; +import type { retainPngWorker } from '@agent-device/capture-kit/png-worker-client'; + +const state = vi.hoisted(() => ({ + engineLoads: 0, + retain: vi.fn(), +})); + +vi.mock('./replay-backend/replay-maestro-backend.ts', async (importOriginal) => { + state.engineLoads += 1; + return await importOriginal(); +}); + +vi.mock('@agent-device/capture-kit/png-worker-client', async (importOriginal) => ({ + ...(await importOriginal()), + retainPngWorker: state.retain, +})); + +const setupHost = { + env: {}, + options: {}, + clientVersion: '0.22.0-dev', + runHostCommand: async () => { + throw new Error('host command unused'); + }, + createError: () => { + throw new Error('setup must not use host services'); + }, +}; + +beforeEach(() => { + vi.resetModules(); + state.engineLoads = 0; + state.retain.mockReset(); +}); + +test('factory setup and unused disposal leave the engine and PNG worker unloaded', async () => { + const { default: maestroPlugin } = await import('./plugin.ts'); + const plugin = maestroPlugin(); + expect({ apiVersion: plugin.apiVersion, kind: plugin.kind, backend: plugin.backend }).toEqual({ + apiVersion: 2, + kind: 'replay-backend', + backend: 'maestro', + }); + + const setup = await plugin.setup(setupHost); + await setup.dispose?.(); + + expect(state.engineLoads).toBe(0); + expect(state.retain).not.toHaveBeenCalled(); +}); + +test('selected creation retains one worker, forwards its diagnostic to the host and releases it', async () => { + const sinks: Parameters[0][] = []; + const release = vi.fn(async () => {}); + state.retain.mockImplementation((sink) => { + sinks.push(sink); + return release; + }); + const host: ReplayBackendHost = { + emitDiagnostic: vi.fn(), + runCommand: async () => { + throw new Error('subprocess unused'); + }, + registerSensitiveValue: () => { + throw new Error('sensitive values unused'); + }, + appendTraceEvent: () => { + throw new Error('trace unused'); + }, + buildBuiltinVars: () => { + throw new Error('variables unused'); + }, + readScriptSourceFile: () => { + throw new Error('source reader unused'); + }, + readSnapshotClickabilityEvidence: () => undefined, + assertSnapshotScreenOrigin: () => Promise.reject(new Error('screen origin unused')), + scriptSourceRequiredMessage: '', + resolveTargetDevice: () => Promise.reject(new Error('device selection unused')), + requestSignal: () => undefined, + buildActionFailureResponse: () => Promise.reject(new Error('failure response unused')), + }; + const { default: maestroPlugin } = await import('./plugin.ts'); + const setup = await maestroPlugin().setup(setupHost); + const backend = await setup.replayBackend.create(host); + const nextBackend = await setup.replayBackend.create(host); + + expect(state.engineLoads).toBe(1); + expect(backend.id).toBe('maestro'); + expect( + nextBackend.inspectSource( + 'appId: com.example.app\nname: Checkout\n---\n- launchApp', + '/flow.yaml', + ), + ).toEqual({ title: 'Checkout', appTarget: 'com.example.app' }); + expect(state.retain).toHaveBeenCalledTimes(1); + expect(release).not.toHaveBeenCalled(); + + const reason = { kind: 'worker-exited', detail: 'exit code 1' } as const; + const onUnavailable = sinks[0]; + assert.ok(onUnavailable); + onUnavailable(reason); + expect(host.emitDiagnostic).toHaveBeenCalledExactlyOnceWith({ + level: 'warn', + phase: 'png_worker_unavailable', + data: { reason: reason.kind, detail: reason.detail }, + }); + + await setup.dispose?.(); + expect(release).toHaveBeenCalledTimes(1); +}); diff --git a/packages/maestro/src/plugin.ts b/packages/maestro/src/plugin.ts new file mode 100644 index 0000000000..3c861fe6c4 --- /dev/null +++ b/packages/maestro/src/plugin.ts @@ -0,0 +1,36 @@ +import type { ReplayEnginePlugin } from 'agent-device/plugins'; + +/** The managed entry is engine-free. Only a selected backend evaluates the implementation. */ +function maestroPlugin(): ReplayEnginePlugin<'maestro'> { + return { + apiVersion: 2, + kind: 'replay-backend', + backend: 'maestro', + setup: () => { + let releasePngWorker: (() => Promise) | undefined; + return { + replayBackend: { + create: async (host) => { + const [{ maestroReplayBackendPlugin }, { retainPngWorker }] = await Promise.all([ + import('./replay-backend/replay-maestro-backend.ts'), + import('@agent-device/capture-kit/png-worker-client'), + ]); + releasePngWorker ??= retainPngWorker((reason) => + host.emitDiagnostic({ + level: 'warn', + phase: 'png_worker_unavailable', + data: { reason: reason.kind, detail: reason.detail }, + }), + ); + return await maestroReplayBackendPlugin.create(host); + }, + }, + dispose: async () => { + await releasePngWorker?.(); + }, + }; + }, + }; +} + +export { maestroPlugin as default }; diff --git a/packages/maestro/src/replay-backend/__tests__/replay-maestro-backend.test.ts b/packages/maestro/src/replay-backend/__tests__/replay-maestro-backend.test.ts index 68e4237f19..7e3c5931ab 100644 --- a/packages/maestro/src/replay-backend/__tests__/replay-maestro-backend.test.ts +++ b/packages/maestro/src/replay-backend/__tests__/replay-maestro-backend.test.ts @@ -7,6 +7,15 @@ import { maestroReplayBackendPlugin } from '../replay-maestro-backend.ts'; // each test the behavior through the registry; what is pinned here is the adapter's own mapping. // None of these capabilities reach host services, so the host is never called. const unusedHost: ReplayBackendHost = { + runCommand: async () => { + throw new Error('Unexpected subprocess'); + }, + emitDiagnostic: () => { + throw new Error('host unused'); + }, + registerSensitiveValue: () => { + throw new Error('host unused'); + }, appendTraceEvent: () => { throw new Error('host unused'); }, @@ -16,6 +25,8 @@ const unusedHost: ReplayBackendHost = { readScriptSourceFile: () => { throw new Error('host unused'); }, + readSnapshotClickabilityEvidence: () => undefined, + assertSnapshotScreenOrigin: () => Promise.reject(new Error('host unused')), scriptSourceRequiredMessage: '', resolveTargetDevice: () => Promise.reject(new Error('host unused')), requestSignal: () => undefined, diff --git a/packages/maestro/src/replay-backend/__tests__/session-replay-maestro-failure.test.ts b/packages/maestro/src/replay-backend/__tests__/session-replay-maestro-failure.test.ts index 6617455911..4a59396c5b 100644 --- a/packages/maestro/src/replay-backend/__tests__/session-replay-maestro-failure.test.ts +++ b/packages/maestro/src/replay-backend/__tests__/session-replay-maestro-failure.test.ts @@ -78,9 +78,16 @@ test('the failure response hands the host the step, its warnings, and its sugges await buildTypedMaestroFailureResponse( { + runCommand: async () => { + throw new Error('Unexpected subprocess'); + }, + emitDiagnostic: () => {}, + registerSensitiveValue: () => {}, appendTraceEvent: () => {}, buildBuiltinVars: () => ({}), readScriptSourceFile: () => '', + readSnapshotClickabilityEvidence: () => undefined, + assertSnapshotScreenOrigin: () => Promise.reject(new Error('unused')), scriptSourceRequiredMessage: '', resolveTargetDevice: () => Promise.reject(new Error('unused')), requestSignal: () => undefined, diff --git a/packages/maestro/src/replay-backend/replay-maestro-backend.ts b/packages/maestro/src/replay-backend/replay-maestro-backend.ts index f0bc099c1d..6064337116 100644 --- a/packages/maestro/src/replay-backend/replay-maestro-backend.ts +++ b/packages/maestro/src/replay-backend/replay-maestro-backend.ts @@ -44,6 +44,6 @@ function createMaestroReplayBackend(host: ReplayBackendHost): ReplayBackend<'mae }; } -export const maestroReplayBackendPlugin: ReplayBackendPlugin<'maestro'> = { +export const maestroReplayBackendPlugin = { create: createMaestroReplayBackend, -}; +} satisfies ReplayBackendPlugin<'maestro'>; diff --git a/packages/maestro/src/replay-backend/replay-maestro-declaration.ts b/packages/maestro/src/replay-backend/replay-maestro-declaration.ts deleted file mode 100644 index e169ef4a08..0000000000 --- a/packages/maestro/src/replay-backend/replay-maestro-declaration.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { ReplayBackendDeclaration } from '@agent-device/contracts/replay-backend'; -import { - formatMaestroCompatibilityReference, - MAESTRO_COMPATIBILITY_ADR_URL, - MAESTRO_COMPATIBILITY_ISSUE_URL, -} from '../internal/support-matrix.ts'; - -export const maestroReplayBackendDeclaration: ReplayBackendDeclaration<'maestro'> = { - id: 'maestro', - help: { - summary: 'Supported Maestro YAML commands, grammar, and runtime boundaries', - body: `agent-device help maestro - -Run Maestro compatibility flows with replay --maestro or test --maestro. Bind an iOS or Android target with --platform or an existing session. - -${formatMaestroCompatibilityReference()} - -Unsupported syntax fails loudly rather than being skipped. Architecture, performance tradeoffs, and declared conformance divergences: ${MAESTRO_COMPATIBILITY_ADR_URL} -Focused compatibility request: ${MAESTRO_COMPATIBILITY_ISSUE_URL}`, - }, -}; diff --git a/packages/maestro/src/replay-backend/session-replay-maestro-runtime.ts b/packages/maestro/src/replay-backend/session-replay-maestro-runtime.ts index 451576385e..a0d795f9cf 100644 --- a/packages/maestro/src/replay-backend/session-replay-maestro-runtime.ts +++ b/packages/maestro/src/replay-backend/session-replay-maestro-runtime.ts @@ -116,6 +116,7 @@ async function executeTypedMaestroReplay( // for flows that did not arrive over the daemon's remote HTTP surface. const publicNetworkOnly = command.publicNetworkOnly === true; const port = createMaestroReplayPort({ + host, command, device: context.device, platform: context.platform, @@ -334,6 +335,7 @@ function buildTypedMaestroEnv(req: DaemonWireRequest, hostEnv: EnvMap): Record; @@ -349,6 +351,12 @@ function createMaestroReplayPort(params: { ...(command.dispatch ? { dispatch: command.dispatch } : {}), }; return createDaemonMaestroRuntimePort({ + readSnapshotClickabilityEvidence: params.host.readSnapshotClickabilityEvidence, + assertSnapshotScreenOrigin: params.host.assertSnapshotScreenOrigin, + host: command.host, + runCommand: params.host.runCommand, + emitDiagnostic: params.host.emitDiagnostic, + registerSensitiveValue: params.host.registerSensitiveValue, invoke: (operation) => invoke(maestroOperationDispatchRequest(replay, operation)), flags: maestroRuntimeDeviceFlags(device, platform, req.flags, publicNetworkOnly), publicNetworkOnly, diff --git a/packages/maestro/test/conformance/differential/flows/optional-scroll-and-wait.yaml b/packages/maestro/test/conformance/differential/flows/optional-scroll-and-wait.yaml index e1c36c7935..60562182cd 100644 --- a/packages/maestro/test/conformance/differential/flows/optional-scroll-and-wait.yaml +++ b/packages/maestro/test/conformance/differential/flows/optional-scroll-and-wait.yaml @@ -16,4 +16,4 @@ appId: com.callstack.agentdevicelab id: this-element-never-exists optional: true timeout: 1000 -- assertVisible: Agent Device Tester +- assertVisible: Home diff --git a/packages/maestro/test/package-artifact.test.mjs b/packages/maestro/test/package-artifact.test.mjs new file mode 100644 index 0000000000..75daa18f60 --- /dev/null +++ b/packages/maestro/test/package-artifact.test.mjs @@ -0,0 +1,57 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { run, assertPackagedRunScriptChildren } from './package-test-support.mjs'; + +const root = path.resolve(import.meta.dirname, '../../..'); + +test('packed managed plugin contains its factory and runs real script children without workspace dependencies', async () => { + const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-maestro-artifact-')); + try { + const pluginTarball = path.join(scratch, 'maestro.tgz'); + run('pnpm', ['pack', '--out', pluginTarball], path.join(root, 'packages/maestro')); + const store = path.join(scratch, 'store'); + fs.mkdirSync(store); + fs.writeFileSync(path.join(store, 'package.json'), '{"private":true,"type":"module"}'); + run('npm', ['install', '--ignore-scripts', '--no-audit', '--no-fund', pluginTarball], store); + const plugin = path.join(store, 'node_modules/@agent-device/maestro'); + const manifest = JSON.parse(fs.readFileSync(path.join(plugin, 'package.json'), 'utf8')); + assert.deepEqual(Object.keys(manifest.exports), ['./agent-device']); + assert.equal(manifest.dependencies, undefined); + assert.equal(manifest.peerDependencies, undefined); + assert.ok(!fs.existsSync(path.join(store, 'node_modules/agent-device'))); + for (const entry of [ + 'agent-device.mjs', + 'agent-device.d.mts', + 'png-worker.mjs', + 'run-script-child.mjs', + 'run-script-http-child.mjs', + ]) + assert.ok(fs.existsSync(path.join(plugin, 'dist', entry)), entry); + await assertPackagedRunScriptChildren(plugin, scratch); + run( + process.execPath, + [ + '--experimental-strip-types', + path.join(import.meta.dirname, 'packed-clickability.mjs'), + plugin, + scratch, + ], + root, + ); + run( + process.execPath, + [ + '--experimental-strip-types', + path.join(import.meta.dirname, 'packed-screen-origin.mjs'), + plugin, + scratch, + ], + root, + ); + } finally { + fs.rmSync(scratch, { recursive: true, force: true }); + } +}); diff --git a/packages/maestro/test/package-smoke.mjs b/packages/maestro/test/package-smoke.mjs new file mode 100644 index 0000000000..a7b275d1e3 --- /dev/null +++ b/packages/maestro/test/package-smoke.mjs @@ -0,0 +1,156 @@ +import { run } from './package-test-support.mjs'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; + +const root = path.resolve(import.meta.dirname, '../../..'); +function files(directory) { + return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const file = path.join(directory, entry.name); + return entry.isDirectory() ? files(file) : [file]; + }); +} + +test('packed core excludes the engine and the managed plugin works without workspace dependencies', async (t) => { + const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-maestro-package-')); + try { + const coreTarball = path.join( + scratch, + JSON.parse( + run('npm', ['pack', '--ignore-scripts', '--json', '--pack-destination', scratch], root), + )[0].filename, + ); + const pluginTarball = path.join(scratch, 'maestro.tgz'); + run('pnpm', ['pack', '--out', pluginTarball], path.join(root, 'packages/maestro')); + const integrity = `sha512-${crypto + .createHash('sha512') + .update(fs.readFileSync(pluginTarball)) + .digest('base64')}`; + const consumer = path.join(scratch, 'consumer'); + const home = path.join(scratch, 'home'); + fs.mkdirSync(consumer, { recursive: true }); + fs.writeFileSync(path.join(consumer, 'package.json'), '{"private":true,"type":"module"}'); + run('npm', ['install', '--ignore-scripts', '--no-audit', '--no-fund', coreTarball], consumer); + const core = path.join(consumer, 'node_modules/agent-device'); + const cli = path.join(core, 'bin/agent-device.mjs'); + const env = { + ...process.env, + AGENT_DEVICE_HOME: home, + AGENT_DEVICE_STATE_DIR: path.join(scratch, 'state'), + AGENT_DEVICE_NO_UPDATE: '1', + }; + const coreCode = files(path.join(core, 'dist')) + .filter((file) => file.endsWith('.js')) + .map((file) => fs.readFileSync(file, 'utf8')) + .join('\n'); + assert.ok(!coreCode.includes('Maestro runScript process exited without a result')); + assert.ok( + !files(path.join(core, 'dist')).some((file) => /run-script-(?:http-)?child\./.test(file)), + ); + const script = path.join(scratch, 'flow.ad'); + fs.writeFileSync(script, 'open com.example.app\n'); + assert.match( + run(process.execPath, [cli, 'help', 'maestro'], consumer, env), + /plugins add @agent-device\/maestro/, + ); + const missing = run( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import { spawnSync } from 'node:child_process'; + const result = spawnSync(process.execPath, ${JSON.stringify([cli, 'replay', 'export', script, '--json'])}, { encoding: 'utf8' }); + if (result.status === 0) throw new Error('missing plugin succeeded'); + process.stdout.write(result.stdout + result.stderr); + `, + ], + consumer, + env, + ); + assert.match(missing, /plugin-not-installed/); + assert.match(missing, /agent-device plugins add @agent-device\/maestro/); + const added = JSON.parse( + run(process.execPath, [cli, 'plugins', 'add', pluginTarball, '--json'], consumer, env), + ); + assert.equal(added.success, true); + const { artifact } = added.data; + assert.equal(artifact.name, '@agent-device/maestro'); + assert.equal(artifact.integrity, integrity); + assert.equal(artifact.compatibility, 'unchecked'); + assert.match(artifact.installation, /^[a-f0-9-]{36}$/); + assert.equal(added.data.restartRequired, true); + const listed = JSON.parse( + run(process.execPath, [cli, 'plugins', 'list', '--json'], consumer, env), + ); + assert.equal(listed.success, true); + assert.deepEqual(listed.data.plugins, [ + { + name: '@agent-device/maestro', + installation: artifact.installation, + integrity: artifact.integrity, + version: artifact.version, + backend: 'maestro', + compatible: true, + }, + ]); + const store = path.join(home, 'plugins', artifact.installation); + const plugin = path.join(store, 'node_modules/@agent-device/maestro'); + const manifest = JSON.parse(fs.readFileSync(path.join(plugin, 'package.json'), 'utf8')); + assert.equal(manifest.version, artifact.version); + const exported = JSON.parse( + run(process.execPath, [cli, 'replay', 'export', script, '--json'], consumer, env), + ); + assert.equal(exported.success, true); + assert.match(exported.data.yaml, /com.example.app/); + for (const mode of [ + 'diagnostics', + 'worker-ownership', + 'embedded-worker', + 'run-script-debug', + 'run-script-env', + ]) { + await t.test(`packed runtime ${mode}`, () => { + const output = run( + process.execPath, + [ + '--experimental-strip-types', + path.join(root, 'packages/maestro/test/packed-runtime.mjs'), + plugin, + scratch, + mode, + core, + ], + consumer, + env, + ); + process.stdout.write(output); + }); + } + const entry = manifest.exports['./agent-device'].import; + const broken = path.join(plugin, entry); + fs.renameSync(broken, `${broken}.missing`); + const failed = run( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import { spawnSync } from 'node:child_process'; + const result = spawnSync(process.execPath, ${JSON.stringify([cli, 'replay', 'export', script, '--json'])}, { encoding: 'utf8' }); + if (result.status === 0) throw new Error('broken plugin succeeded'); + process.stdout.write(result.stdout + result.stderr); + `, + ], + consumer, + env, + ); + assert.match(failed, /plugin_load_failed/); + assert.ok(!failed.includes('plugin-not-installed')); + } finally { + fs.rmSync(scratch, { recursive: true, force: true }); + } +}); diff --git a/packages/maestro/test/package-test-support.mjs b/packages/maestro/test/package-test-support.mjs new file mode 100644 index 0000000000..e88c41f817 --- /dev/null +++ b/packages/maestro/test/package-test-support.mjs @@ -0,0 +1,49 @@ +import { runCmdSync } from '@agent-device/host-kit/command'; +import http from 'node:http'; +import { promisify } from 'node:util'; +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; + +function run(command, args, cwd, env = process.env) { + return runCmdSync(command, args, { + cwd, + env, + timeoutMs: 120_000, + maxBuffer: 16 * 1024 * 1024, + }).stdout; +} +async function assertPackagedRunScriptChildren(plugin, scratch) { + const alias = path.join(scratch, 'plugin-alias'); + fs.symlinkSync(plugin, alias, process.platform === 'win32' ? 'junction' : 'dir'); + const server = http.createServer((_request, response) => + response.end('x'.repeat(2 * 1024 * 1024)), + ); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const scriptPath = path.join(scratch, 'http.js'); + fs.writeFileSync(scriptPath, 'output.size = http.post(SERVER_URL).body.length'); + for (const directory of [plugin, alias]) { + const result = promisify(execFile)( + process.execPath, + [path.join(directory, 'dist/run-script-child.mjs')], + { timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }, + ); + result.child.stdin.end( + JSON.stringify({ + scriptPath, + env: { SERVER_URL: `http://127.0.0.1:${server.address().port}/` }, + publicNetworkOnly: false, + }), + ); + assert.deepEqual(JSON.parse((await result).stdout), { + outputEnv: { 'output.size': String(2 * 1024 * 1024) }, + }); + } + } finally { + await new Promise((resolve) => server.close(resolve)); + } +} + +export { run, assertPackagedRunScriptChildren }; diff --git a/packages/maestro/test/packed-clickability.mjs b/packages/maestro/test/packed-clickability.mjs new file mode 100644 index 0000000000..df66440b27 --- /dev/null +++ b/packages/maestro/test/packed-clickability.mjs @@ -0,0 +1,102 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { + parseUiHierarchyTree, + buildUiHierarchySnapshot, +} from '../../platform-android/src/ui-hierarchy.ts'; +import { buildAndroidSnapshotClickabilityEvidence } from '../../platform-android/src/snapshot-clickability.ts'; +import { + createAndroidSnapshotCapture, + androidSnapshotPublicationInput, +} from '../../platform-android/src/snapshot-capture.ts'; +import { readSnapshotClickabilityEvidence } from '../../contracts/src/snapshot-private-evidence.ts'; +import { createReplayBackendHost } from '../../replay-port/src/daemon-port/replay-backend-host.ts'; + +const [plugin, scratch] = process.argv.slice(2); +const { default: maestroPlugin } = await import( + pathToFileURL(path.join(plugin, 'dist/agent-device.mjs')) +); +const target = 'maestro-clickable-first-target'; +const setup = maestroPlugin().setup(); +const host = { + ...createReplayBackendHost(), + resolveTargetDevice: () => { + throw new Error('explicit platform must not discover devices'); + }, + buildActionFailureResponse: (failure) => { + throw new Error(JSON.stringify(failure.error)); + }, +}; +const backend = await setup.replayBackend.create(host); + +try { + for (const indexed of [false, true]) { + let selection = 'none'; + const points = []; + const expectedPoint = indexed ? [20, 20] : [20, 80]; + const expectedSelection = indexed ? 'inert' : 'clickable'; + const entry = path.join(scratch, `clickability-${indexed}.yaml`); + const source = `appId: com.example.app\n---\n- tapOn:\n id: ${target}\n${indexed ? ' index: 0\n' : ''}- assertVisible:\n text: "Maestro selection: ${expectedSelection}"\n`; + const capture = () => { + const xml = ``; + const built = buildUiHierarchySnapshot(parseUiHierarchyTree(xml), undefined, {}); + const { sourceNodes: _sourceNodes, occlusionContext, ...snapshot } = built; + const data = androidSnapshotPublicationInput( + createAndroidSnapshotCapture( + { ...snapshot, createdAt: Date.now(), androidSnapshot: {} }, + { clickability: buildAndroidSnapshotClickabilityEvidence(built), occlusionContext }, + ), + ); + assert.equal(readSnapshotClickabilityEvidence(data)?.kind, 'exact'); + assert.ok(data.nodes.every((node) => !Object.hasOwn(node, 'clickable'))); + return data; + }; + const result = await backend.runReplay({ + request: { + command: 'replay', + positionals: [entry], + flags: { + platform: 'android', + replayBackend: 'maestro', + replayScriptSource: { entry, files: { [entry]: source } }, + }, + }, + host: { env: {}, cwd: scratch }, + session: { + name: 'packed-clickability', + logPath: path.join(scratch, 'clickability.log'), + store: { + get: () => undefined, + lookup: () => undefined, + resolveOpenRuntimeHints: () => undefined, + }, + }, + invoke: async (request) => { + if (request.command === 'snapshot') return { ok: true, data: capture() }; + if (request.command === 'runtime') + return { ok: true, data: { viewport: { x: 0, y: 0, width: 200, height: 200 } } }; + if (request.command === 'click') { + const point = request.positionals.map(Number); + points.push(point); + assert.deepEqual( + point, + expectedPoint, + indexed + ? 'explicit index must retain source order' + : 'no-index Maestro must select the clickable duplicate', + ); + selection = point[1] < 40 ? 'inert' : 'clickable'; + return { ok: true, data: {} }; + } + throw new Error(`unexpected native boundary command: ${request.command}`); + }, + }); + assert.equal(result.ok, true, JSON.stringify(result)); + assert.equal(result.data.replayed, 2); + assert.deepEqual(points, [expectedPoint]); + } + console.log('packed clickability: no-index and explicit-index contracts passed'); +} finally { + await setup.dispose(); +} diff --git a/packages/maestro/test/packed-runtime.mjs b/packages/maestro/test/packed-runtime.mjs new file mode 100644 index 0000000000..134c2dc5dc --- /dev/null +++ b/packages/maestro/test/packed-runtime.mjs @@ -0,0 +1,253 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import workerThreads from 'node:worker_threads'; +import { syncBuiltinESMExports } from 'node:module'; +import { Session } from 'node:inspector/promises'; +import { PNG } from 'pngjs'; +import { resolveProviderPlugins, startProviderRegistry } from '../../plugins/src/registry.ts'; +import { withDiagnosticsScope } from '../../host-kit/src/diagnostics.ts'; +import { createReplayBackendHost } from '../../replay-port/src/daemon-port/replay-backend-host.ts'; + +const [plugin, scratch, mode, core] = process.argv.slice(2); +const scriptTrace = mode.startsWith('run-script-'); +const secret = 'packed-script-secret-value'; +const workers = []; +const loadedPluginModules = []; +const imports = new Session(); +imports.connect(); +await imports.post('Debugger.enable'); +imports.on('Debugger.scriptParsed', ({ params }) => { + if (params.url.startsWith(pathToFileURL(fs.realpathSync(plugin)).href)) + loadedPluginModules.push(path.basename(params.url)); +}); +const OriginalWorker = workerThreads.Worker; +workerThreads.Worker = class extends OriginalWorker { + constructor(url, options) { + super(url, options); + if (String(url).includes('png-worker') && String(url).startsWith(fs.realpathSync(plugin))) { + const record = { url: String(url), exited: false, terminations: 0 }; + workers.push(record); + this.on('exit', () => { + record.exited = true; + }); + const terminate = this.terminate.bind(this); + this.terminate = () => { + record.terminations += 1; + return terminate(); + }; + } + } +}; +syncBuiltinESMExports(); +const { default: maestroPlugin } = await import( + pathToFileURL(path.join(plugin, 'dist/agent-device.mjs')) +); +async function registry() { + const registry = await startProviderRegistry( + await resolveProviderPlugins([{ source: 'embedder', load: () => maestroPlugin() }]), + { env: {}, cwd: '/' }, + { + adaptWebDriver: async () => { + throw new Error('not a provider'); + }, + }, + 'replay-backends', + ); + return { + close: registry.close, + select: (host) => registry.resolveReplayBackend('maestro', host), + }; +} +async function embedded(label) { + const { startAgentDevice } = await import(pathToFileURL(path.join(core, 'dist/src/index.js'))); + let backend; + const plugin = maestroPlugin(); + const runtime = await startAgentDevice({ + stateDir: path.join(scratch, `embedded-${label}`), + host: { + env: { + AGENT_DEVICE_HOME: path.join(scratch, 'empty-embedded-home'), + AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0', + }, + cwd: scratch, + }, + plugins: [ + { + ...plugin, + setup: async (host) => { + const setup = await plugin.setup(host); + return { + ...setup, + replayBackend: { + create: async (host) => { + backend = await setup.replayBackend.create(host); + return backend; + }, + }, + }; + }, + }, + ], + }); + return { + close: runtime.close, + select: async () => { + const entry = path.join(scratch, `embedded-${label}.yaml`); + fs.writeFileSync( + entry, + 'appId: com.example.app\n---\n- evalScript: ${output.value = "ok"}\n', + ); + assert.deepEqual(await runtime.client.sessions.list(), []); + await assert.rejects( + runtime.client.replay.test({ paths: [entry], backend: 'maestro', platform: 'ios' }), + (error) => { + assert.equal(error.code, 'INVALID_ARGS'); + assert.equal(error.details.reason, 'plugin-not-installed'); + assert.equal(error.details.package, '@agent-device/replay'); + assert.equal( + error.details.installCommand, + 'agent-device plugins add @agent-device/replay', + ); + return true; + }, + ); + assert.deepEqual(await runtime.client.sessions.list(), []); + const response = await runtime.client.replay.run({ + path: entry, + backend: 'maestro', + platform: 'ios', + }); + assert.equal(response.replayed, 1); + return backend; + }, + }; +} +const first = mode === 'embedded-worker' ? await embedded('first') : await registry(); +const second = mode === 'embedded-worker' ? await embedded('second') : await registry(); +assert.equal(workers.length, 0, 'unused plugin setup must not load/spawn the worker'); +assert.deepEqual( + loadedPluginModules, + ['agent-device.mjs'], + 'unused setup evaluates only the engine-free managed entry', +); +imports.disconnect(); +const traceLogPath = path.join(scratch, `host-${mode}.ndjson`); +const host = { + ...createReplayBackendHost(), + resolveTargetDevice: () => { + throw new Error('explicit platform needs no device discovery'); + }, + buildActionFailureResponse: (failure) => { + throw new Error(JSON.stringify(failure.error)); + }, +}; +const backend = await first.select(host); +const other = await second.select(host); +const entry = path.join(scratch, 'packed-runtime.yaml'); +const png = PNG.sync.write(new PNG({ width: 2, height: 2 })); +const calls = []; +async function run(selected) { + fs.writeFileSync(path.join(scratch, 'setup.js'), `output.value = SECRET === '${secret}'`); + const source = scriptTrace + ? `appId: com.example.app\n---\n- runScript:\n file: setup.js\n env:\n SECRET: ${secret}\n- assertTrue: \${output.value}\n` + : 'appId: com.example.app\n---\n- tapOn:\n point: "10,20"\n- waitForAnimationToEnd:\n timeout: 0\n'; + const debug = mode !== 'run-script-env'; + const env = { AGENT_DEVICE_EXEC_TRACE: debug ? undefined : '1' }; + const result = await withDiagnosticsScope({ debug, traceLogPath }, () => + selected.runReplay({ + request: { + command: 'replay', + positionals: [entry], + flags: { + platform: 'android', + replayBackend: 'maestro', + replayScriptSource: { entry, files: { [entry]: source } }, + }, + }, + host: { env, cwd: scratch }, + session: { + name: 'packed', + logPath: path.join(scratch, 'log'), + store: { + get: () => undefined, + lookup: () => undefined, + resolveOpenRuntimeHints: () => undefined, + }, + }, + invoke: async (request) => { + calls.push(request.command); + if (request.command === 'runtime') + return { ok: true, data: { viewport: { x: 0, y: 0, width: 400, height: 800 } } }; + if (request.command === 'screenshot') fs.writeFileSync(request.positionals[0], png); + return { ok: true, data: {} }; + }, + }), + ); + assert.equal(result.ok, true, JSON.stringify(result)); + assert.equal(result.data.replayed, 2); +} +try { + await run(backend); + if (!scriptTrace) { + assert.equal(workers.length, 1, 'comparison must use the actual packed PNG worker'); + assert.ok(workers[0].url.startsWith(fs.realpathSync(plugin)), workers[0].url); + assert.equal(workers[0].exited, false); + } + if (scriptTrace) { + const log = fs.readFileSync(traceLogPath, 'utf8'); + const events = log + .trim() + .split('\n') + .map((line) => JSON.parse(line)) + .filter((event) => event.phase === 'exec_command'); + for (const event of ['spawn_start', 'spawn', 'exit', 'close', 'settled']) + assert.ok( + events.some((row) => row.data.event === event), + `missing host exec_command ${event}`, + ); + assert.equal(new Set(events.map((row) => row.data.execId)).size, 1); + assert.equal(events.find((row) => row.data.event === 'settled').data.reason, 'success'); + assert.ok(events.find((row) => row.data.event === 'spawn').data.pid > 0); + assert.ok(!log.includes(secret), 'host trace must not expose subprocess secrets'); + assert.deepEqual(calls, [], 'runScript needs no device dispatch'); + } else if (mode === 'diagnostics') { + const events = fs + .readFileSync(traceLogPath, 'utf8') + .trim() + .split('\n') + .map((line) => JSON.parse(line)); + const tap = events.find((event) => event.phase === 'maestro_tap_dispatch'); + assert.equal(tap?.level, 'debug'); + assert.deepEqual(tap?.data, { kind: 'point', point: { x: 10, y: 20 } }); + const comparison = events.find((event) => event.phase === 'maestro_screenshot_compare'); + assert.equal(comparison?.data.purpose, 'animation'); + assert.equal(comparison?.data.result, 'stable'); + assert.equal(comparison?.data.differencePercent, 0); + assert.equal(calls.filter((command) => command === 'screenshot').length, 2); + assert.equal(calls.filter((command) => command === 'click').length, 1); + } else { + await first.close(); + await first.close(); + assert.equal(workers[0].exited, false, 'another registry still owns this worker'); + assert.equal(workers[0].terminations, 0); + await run(other); + assert.equal(workers.length, 1, 'remaining owner reuses the live worker'); + await second.close(); + await second.close(); + assert.equal(workers[0].exited, true, 'last owner waits for real worker exit'); + assert.equal(workers[0].terminations, 1, 'last owner terminates once'); + } + console.log( + JSON.stringify({ + mode, + hostLog: fs.existsSync(traceLogPath) ? fs.readFileSync(traceLogPath, 'utf8') : '', + workers, + calls, + }), + ); +} finally { + await first.close(); + await second.close(); +} diff --git a/packages/maestro/test/packed-screen-origin.mjs b/packages/maestro/test/packed-screen-origin.mjs new file mode 100644 index 0000000000..e3b82d68a2 --- /dev/null +++ b/packages/maestro/test/packed-screen-origin.mjs @@ -0,0 +1,108 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { createIosSnapshotAcquisition } from '../../capture-kit/src/ios-snapshot-acquisition.ts'; +import { presentIosSnapshotAcquisition } from '../../capture-kit/src/snapshot/ios-snapshot-runtime.ts'; +import { buildSnapshotState } from '../../capture-kit/src/snapshot-state.ts'; +import { createReplayBackendHost } from '../../replay-port/src/daemon-port/replay-backend-host.ts'; + +const [plugin, scratch] = process.argv.slice(2); +const { default: maestroPlugin } = await import( + pathToFileURL(path.join(plugin, 'dist/agent-device.mjs')) +); +const setup = maestroPlugin().setup(); +const backend = await setup.replayBackend.create({ + ...createReplayBackendHost(), + resolveTargetDevice: () => { + throw new Error('explicit platform must not discover devices'); + }, + buildActionFailureResponse: async ({ error }) => ({ ok: false, error }), +}); +const rect = { x: 0, y: 0, width: 390, height: 844 }; + +try { + for (const kind of ['derived', 'missing', 'reported']) { + for (const action of ['tap', 'scroll']) { + let dispatched = false; + const requests = []; + const nodes = [ + { index: 0, type: 'Application', rect }, + { index: 1, parentIndex: 0, type: 'ScrollView', identifier: 'container', rect }, + { + index: 2, + parentIndex: 1, + type: 'Button', + identifier: 'action', + label: 'Action', + rect: { x: 100, y: 100, width: 80, height: 40 }, + }, + ]; + const entry = path.join(scratch, `screen-origin-${kind}-${action}.yaml`); + const source = `appId: com.example.app\n---\n${action === 'tap' ? '- tapOn:\n id: action\n index: 0\n' : '- scrollUntilVisible:\n element: Found\n direction: DOWN\n timeout: 1000\n'}`; + const result = await backend.runReplay({ + request: { + command: 'replay', + positionals: [entry], + flags: { + platform: 'ios', + replayBackend: 'maestro', + replayScriptSource: { entry, files: { [entry]: source } }, + }, + }, + host: { env: {}, cwd: scratch }, + session: { + name: 'packed-screen-origin', + logPath: path.join(scratch, 'screen-origin.log'), + store: { + get: () => undefined, + lookup: () => undefined, + resolveOpenRuntimeHints: () => undefined, + }, + }, + invoke: async (request) => { + requests.push(request); + if (request.command === 'snapshot') { + const acquisition = createIosSnapshotAcquisition({ + producer: 'appium-source', + nodes: dispatched + ? [...nodes, { index: 3, parentIndex: 1, type: 'StaticText', label: 'Found', rect }] + : nodes, + viewport: kind === 'missing' ? { kind, reason: 'not-provided' } : { kind, rect }, + lineage: { targetId: 'ios-origin:com.example.app' }, + }); + return { + ok: true, + data: buildSnapshotState(presentIosSnapshotAcquisition(acquisition, { raw: true }), { + snapshotRaw: true, + }), + }; + } + if (request.command === 'runtime') return { ok: true, data: { viewport: rect } }; + if (request.command === 'click' || request.command === 'gesture') { + dispatched = true; + return { ok: true, data: {} }; + } + throw new Error(`unexpected native boundary command: ${request.command}`); + }, + }); + if (kind === 'reported') { + assert.equal(result.ok, true, JSON.stringify(result)); + assert.equal(result.data.replayed, 1); + assert.equal(dispatched, true, `${action} must dispatch with reported origin`); + const input = requests.find( + ({ command }) => command === (action === 'tap' ? 'click' : 'gesture'), + ); + assert.ok(input); + if (action === 'tap') assert.deepEqual(input.positionals, ['140', '120']); + } else { + assert.equal(dispatched, false, `${kind} ${action} must refuse before input`); + assert.equal(result.ok, false); + assert.equal(result.error.details.reason, 'window-origin-unknown'); + assert.equal(result.error.details.dispatched, 'no'); + } + } + } + console.log('packed screen origin: derived/missing refusal and reported tap/scroll passed'); +} finally { + await setup.dispose(); +} diff --git a/packages/maestro/tsconfig.json b/packages/maestro/tsconfig.json index 6614d7d44e..7f2044a219 100644 --- a/packages/maestro/tsconfig.json +++ b/packages/maestro/tsconfig.json @@ -6,17 +6,37 @@ "emitDeclarationOnly": true, "declaration": true, "declarationDir": "./dist-types", - "rootDir": "./src", - "tsBuildInfoFile": "./dist-types/index.tsbuildinfo" + "rootDir": ".", + "tsBuildInfoFile": "./dist-types/index.tsbuildinfo", + "paths": { + "agent-device/plugins": ["./node_modules/agent-device/src/sdk/plugins.ts"] + } }, "include": ["src"], "references": [ - { "path": "../ad-script" }, - { "path": "../capture-kit" }, - { "path": "../contracts" }, - { "path": "../host-kit" }, - { "path": "../kernel" }, - { "path": "../provision-kit" }, - { "path": "../selectors" } + { + "path": "../ad-script" + }, + { + "path": "../capture-kit" + }, + { + "path": "../contracts" + }, + { + "path": "../host-kit" + }, + { + "path": "../kernel" + }, + { + "path": "../provision-kit" + }, + { + "path": "../selectors" + }, + { + "path": "../test-kit" + } ] } diff --git a/packages/maestro/tsdown.config.ts b/packages/maestro/tsdown.config.ts new file mode 100644 index 0000000000..d1d1807d28 --- /dev/null +++ b/packages/maestro/tsdown.config.ts @@ -0,0 +1,29 @@ +import { defineConfig } from 'tsdown'; + +export default defineConfig({ + entry: { + 'agent-device': 'src/plugin.ts', + 'png-worker': '../capture-kit/src/png-worker.ts', + 'run-script-child': 'src/daemon-port/run-script-child.ts', + 'run-script-http-child': 'src/daemon-port/run-script-http-child.ts', + }, + outDir: 'dist', + tsconfig: '../../tsconfig.lib.json', + format: 'esm', + platform: 'node', + target: 'es2022', + minify: true, + dts: true, + hash: false, + deps: { + neverBundle: ['agent-device/plugins'], + alwaysBundle: [/^@agent-device\//], + onlyBundle: ['yaml', 'undici', 'ipaddr.js', 'pngjs', 'jpeg-js'], + }, + inputOptions: { + onLog(level, log, handler) { + if (log.code === 'UNRESOLVED_IMPORT') throw new Error(log.message); + handler(level, log); + }, + }, +}); diff --git a/packages/platform-android/src/__tests__/app-lifecycle-close.test.ts b/packages/platform-android/src/__tests__/app-lifecycle-close.test.ts index 4671aa6c9a..fe82e1ddc9 100644 --- a/packages/platform-android/src/__tests__/app-lifecycle-close.test.ts +++ b/packages/platform-android/src/__tests__/app-lifecycle-close.test.ts @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { closeAndroidApp, openAndroidApp } from '../app-lifecycle.ts'; import { withAndroidAdbProvider } from '../adb-executor.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { ANDROID_EMULATOR } from './test-utils/device-fixtures.ts'; import './test-utils/android-host-test-setup.ts'; @@ -217,6 +217,17 @@ test.each([ phase, packageName: 'com.example.app', timeoutMs, + ...(phase === 'foreground' + ? { + initialProcessCount: 1, + foregroundObservations: [1750, 1800, 1850, 1900, 1950].map((ms) => ({ + startMs: ms, + endMs: ms, + remainingMs: 2000 - ms, + result: 'target', + })), + } + : {}), }); return true; }, @@ -278,12 +289,14 @@ test.each([ : assert.rejects(close, (error: unknown) => { assert.ok(error instanceof AppError); assert.equal(error.code, 'COMMAND_FAILED'); - assert.deepEqual(error.details, { - reason: 'android-app-close-timeout', - phase, - packageName: 'com.example.app', - timeoutMs: 2_000, - }); + assert.equal(error.details?.reason, 'android-app-close-timeout'); + assert.equal(error.details?.phase, phase); + assert.equal(error.details?.timeoutMs, 2_000); + if (phase === 'foreground') { + assert.deepEqual(normalizeError(error).details?.foregroundObservations, [ + { startMs: 0, endMs: completionMs, remainingMs: 0, result: 'other' }, + ]); + } return true; }); await Promise.all([result, vi.runAllTimersAsync()]); @@ -528,3 +541,70 @@ test('closeAndroidApp reports an unanswered pidof after force-stop instead of an ); assert.equal(pidofCalls, 2); }); + +test('foreground probe failure retains bounded history in request diagnostics and rethrows the original error', async () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + const { withDiagnosticsScope, flushDiagnosticsToSessionFile } = + await import('@agent-device/host-kit/diagnostics'); + const fs = await import('node:fs'); + const path = await import('node:path'); + const { mkdtempForTestSync } = await import('@agent-device/test-kit'); + const logPath = path.join(mkdtempForTestSync('foreground-fence'), 'request.ndjson'); + const cause = new Error('underlying failure'); + const failure = new AppError('COMMAND_FAILED', 'probe failed', { reason: 'probe-failed' }, cause); + let probes = 0; + try { + await withDiagnosticsScope({ logPath }, async () => { + await withAndroidAdbProvider( + { + exec: async (args) => { + if (args[1] === 'dumpsys' && ++probes === 7) throw failure; + return { + stdout: + args[1] === 'dumpsys' + ? 'mCurrentFocus=Window{42 u0 com.example.app/.Main}\n' + : '123\n', + stderr: '', + exitCode: 0, + }; + }, + }, + { serial: ANDROID_EMULATOR.id }, + async () => { + const rejected = assert.rejects( + closeAndroidApp(ANDROID_EMULATOR, 'com.example.app'), + (error: unknown) => { + assert.equal(error, failure); + assert.equal(failure.cause, cause); + assert.equal(failure.details?.reason, 'probe-failed'); + return true; + }, + ); + await Promise.all([rejected, vi.runAllTimersAsync()]); + }, + ); + flushDiagnosticsToSessionFile({ force: true }); + }); + const events = fs + .readFileSync(logPath, 'utf8') + .trim() + .split('\n') + .map((line) => JSON.parse(line)); + const event = events.find((item) => item.phase === 'android_close_foreground_fence'); + assert.deepEqual(event.data, { + initialProcessCount: 1, + observations: [ + ...[100, 150, 200, 250].map((ms) => ({ + startMs: ms, + endMs: ms, + remainingMs: 2000 - ms, + result: 'target', + })), + { startMs: 300, endMs: 300, remainingMs: 1700, result: 'error' }, + ], + }); + } finally { + vi.useRealTimers(); + } +}); diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts index a082f7a19a..666b38eb2b 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts @@ -594,3 +594,38 @@ function countForceStops(options: SessionProviderOptions): number { function isHelperRuntimeForceStop(args: readonly string[]): boolean { return args.join(' ') === 'shell am force-stop com.callstack.agentdevice.snapshothelper'; } + +test('records a declined acquisition in its request diagnostics', async () => { + const dir = await mkdtempForTest('android-session-decline-'); + const logPath = path.join(dir, 'request.ndjson'); + try { + process.env.AGENT_DEVICE_ANDROID_SNAPSHOT_HELPER_SESSION = '0'; + const provider = createSessionProvider({ calls: [] }); + await withDiagnosticsScope( + { debug: true, logPath, session: 'fixture', requestId: 'req-decline', command: 'snapshot' }, + async () => { + assert.equal( + await captureAndroidSnapshotWithHelperSession({ + adb: provider.exec, + adbProvider: provider, + }), + undefined, + ); + }, + ); + const events = (await fs.readFile(logPath, 'utf8')) + .trim() + .split('\n') + .map((line) => JSON.parse(line)); + assert.ok( + events.some( + (event) => + event.phase === 'android_snapshot_helper_session_acquisition' && + event.data.outcome === 'disabled' && + event.requestId === 'req-decline', + ), + ); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +}); diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts index e835a98e9b..7db1f32cf3 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts @@ -11,7 +11,10 @@ import { import path from 'node:path'; import { promises as fs } from 'node:fs'; import { mkdtempForTest } from './test-utils/tmp-dir.ts'; -import { withDiagnosticsScope } from '@agent-device/host-kit/diagnostics'; +import { + withDiagnosticsScope, + registerDiagnosticSensitiveValue, +} from '@agent-device/host-kit/diagnostics'; beforeEach(async () => { await resetAndroidSnapshotHelperSessions(); @@ -285,16 +288,19 @@ test('the session fallback diagnostic reads the typed timeout reason', async () await withDiagnosticsScope( { debug: true, logPath, session: 'android-test', requestId: 'req-1', command: 'snapshot' }, async () => { + registerDiagnosticSensitiveValue('sensitive-device-value'); const output = await captureAndroidSnapshotWithHelperSession({ adb: provider.exec, adbProvider: provider, - deviceKey: 'android:emulator-5554', + deviceKey: 'android:sensitive-device-value', }); assert.equal(output, undefined); }, ); const log = await fs.readFile(logPath, 'utf8'); + assert.ok(!log.includes('sensitive-device-value')); + assert.ok(log.includes('req-1')); const fallback = log .split('\n') .filter(Boolean) diff --git a/packages/platform-android/src/app-lifecycle.ts b/packages/platform-android/src/app-lifecycle.ts index fb959c6049..0d2a7344ce 100644 --- a/packages/platform-android/src/app-lifecycle.ts +++ b/packages/platform-android/src/app-lifecycle.ts @@ -1,6 +1,7 @@ import { AppError } from '@agent-device/kernel/errors'; import type { AppStateRuntimeResult } from '@agent-device/contracts/app-state-runtime'; import { Deadline, sleep } from '@agent-device/host-kit/retry'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { isCommandTimeoutError } from '@agent-device/host-kit/command'; import type { AppsFilter } from '@agent-device/contracts/device'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -664,8 +665,10 @@ async function stopAndroidPackage(device: DeviceInfo, packageName: string): Prom throw androidPidofUnavailableError(packageName); } await runAndroidShell(device, ['am', 'force-stop', packageName]); - const expired = await waitForAndroidPackageStopped(device, packageName, killed); - if (expired) throw androidCloseTimeoutError(packageName, expired); + const observations: ForegroundObservation[] = []; + const expired = await waitForAndroidPackageStopped(device, packageName, killed, observations); + if (expired === 'foreground') emitForegroundFenceEvidence(observations, killed.size); + if (expired) throw androidCloseTimeoutError(packageName, expired, observations, killed.size); } /** @@ -729,8 +732,16 @@ async function waitForAndroidPackageStopped( device: DeviceInfo, packageName: string, killed: ReadonlySet, + observations: ForegroundObservation[], ): Promise { - if (!(await waitForAndroidPackageNotForeground(device, packageName))) return 'foreground'; + let notForeground: boolean; + try { + notForeground = await waitForAndroidPackageNotForeground(device, packageName, observations); + } catch (error) { + emitForegroundFenceEvidence(observations, killed.size); + throw error; + } + if (!notForeground) return 'foreground'; if (!(await waitForAndroidKilledProcessesExit(device, packageName, killed))) return 'exit'; if (!(await waitForAndroidPackageProcessGone(device, packageName))) return 'process'; return undefined; @@ -754,25 +765,53 @@ const ANDROID_CLOSE_TIMEOUTS: Record< }, }; -function androidCloseTimeoutError(packageName: string, phase: AndroidStopFencePhase): AppError { +function androidCloseTimeoutError( + packageName: string, + phase: AndroidStopFencePhase, + observations: ForegroundObservation[], + initialProcessCount: number, +): AppError { const { message, timeoutMs } = ANDROID_CLOSE_TIMEOUTS[phase]; return new AppError('COMMAND_FAILED', `Android app ${packageName} ${message}`, { reason: 'android-app-close-timeout', phase, packageName, timeoutMs, + ...(phase === 'foreground' + ? { foregroundObservations: observations, initialProcessCount } + : {}), + }); +} + +type ForegroundObservation = { + startMs: number; + endMs: number; + remainingMs: number; + result: 'target' | 'other' | 'unknown' | 'error'; +}; + +function emitForegroundFenceEvidence( + observations: ForegroundObservation[], + initialProcessCount: number, +): void { + emitDiagnostic({ + phase: 'android_close_foreground_fence', + data: { initialProcessCount, observations }, }); } function waitForAndroidPackageNotForeground( device: DeviceInfo, packageName: string, + observations?: ForegroundObservation[], ): Promise { return waitForAndroidForegroundPackage( device, Deadline.fromTimeoutMs(ANDROID_CLOSE_FOCUS_TIMEOUT_MS), ANDROID_CLOSE_FOCUS_POLL_MS, (foregroundPackage) => foregroundPackage !== packageName, + observations, + packageName, ); } @@ -782,9 +821,25 @@ async function waitForAndroidForegroundPackage( deadline: Deadline, pollMs: number, matches: (foregroundPackage: string | undefined) => boolean, + observations?: ForegroundObservation[], + targetPackage?: string, ): Promise { while (!deadline.isExpired()) { - const foreground = await probeBeforeDeadline(deadline, () => readAndroidForegroundApp(device)); + const foreground = await probeBeforeDeadline(deadline, async () => { + if (!observations) return await readAndroidForegroundApp(device); + const startMs = deadline.elapsedMs(); + let result: ForegroundObservation['result'] = 'error'; + try { + const value = await readAndroidForegroundApp(device); + result = !value ? 'unknown' : value.package === targetPackage ? 'target' : 'other'; + return value; + } finally { + const endedAt = Date.now(); + const endMs = deadline.elapsedMs(endedAt); + observations.push({ startMs, endMs, remainingMs: deadline.remainingMs(endedAt), result }); + if (observations.length > 5) observations.shift(); + } + }); if (!foreground) break; if (matches(foreground.value?.package)) return true; await sleep(pollMs); diff --git a/packages/platform-android/src/manifest.ts b/packages/platform-android/src/manifest.ts index a07e21468b..ffeb25a94c 100644 --- a/packages/platform-android/src/manifest.ts +++ b/packages/platform-android/src/manifest.ts @@ -24,28 +24,30 @@ const TYPE_STRING = 0x03; const NO_INDEX = 0xffffffff; const utf16Decoder = new TextDecoder('utf-16le'); -let aaptPathCache: string | null | undefined; export async function resolveAndroidArchivePackageName( archivePath: string, signal?: AbortSignal, + cwd?: string, ): Promise { for (const entry of ['AndroidManifest.xml', 'base/manifest/AndroidManifest.xml']) { - const manifest = await readZipEntry(archivePath, entry, signal); + const manifest = await readZipEntry(archivePath, entry, signal, cwd); if (!manifest) continue; const packageName = parseAndroidManifestPackageName(manifest); if (packageName) return packageName; } - return await resolveAndroidArchivePackageNameWithAapt(archivePath, signal); + return await resolveAndroidArchivePackageNameWithAapt(archivePath, signal, cwd); } async function readZipEntry( archivePath: string, entry: string, signal?: AbortSignal, + cwd?: string, ): Promise { try { const result = await runCmd('unzip', ['-p', archivePath, entry], { + cwd, allowFailure: true, binaryStdout: true, timeoutMs: ARCHIVE_INSPECTION_TIMEOUT_MS, @@ -324,11 +326,13 @@ function readUtf16Length(chunk: Buffer, offset: number): PoolLength | undefined async function resolveAndroidArchivePackageNameWithAapt( archivePath: string, signal?: AbortSignal, + cwd?: string, ): Promise { signal?.throwIfAborted(); const aaptPath = await resolveAaptPath(); if (!aaptPath) return undefined; const result = await runCmd(aaptPath, ['dump', 'badging', archivePath], { + cwd, allowFailure: true, timeoutMs: ARCHIVE_INSPECTION_TIMEOUT_MS, signal, @@ -339,10 +343,6 @@ async function resolveAndroidArchivePackageNameWithAapt( } async function resolveAaptPath(): Promise { - if (aaptPathCache !== undefined) { - return aaptPathCache ?? undefined; - } - try { const files = requireAndroidAdbHost().files; const { hostPlatform } = await import('@agent-device/host-kit/process'); @@ -357,7 +357,6 @@ async function resolveAaptPath(): Promise { const candidate = path.join(buildToolsDir, version, 'aapt'); // SDK roots can come from env vars; reject relative roots before returning an executable. if (path.isAbsolute(candidate) && (await files.isExecutable(candidate))) { - aaptPathCache = candidate; return candidate; } } @@ -369,6 +368,5 @@ async function resolveAaptPath(): Promise { // Ignore SDK lookup failures and fall back to undefined. } - aaptPathCache = null; return undefined; } diff --git a/packages/platform-android/src/snapshot-helper-session-lifecycle.ts b/packages/platform-android/src/snapshot-helper-session-lifecycle.ts index 712a66854c..4d0bf46c00 100644 --- a/packages/platform-android/src/snapshot-helper-session-lifecycle.ts +++ b/packages/platform-android/src/snapshot-helper-session-lifecycle.ts @@ -134,7 +134,18 @@ export async function acquireAndroidSnapshotHelperSession( adb: options.adb, signal: options.signal, }); - if (!isAndroidSnapshotHelperSessionEnabled() || !options.adbProvider?.spawn) { + if (!isAndroidSnapshotHelperSessionEnabled()) { + emitDiagnostic({ + phase: 'android_snapshot_helper_session_acquisition', + data: { outcome: 'disabled' }, + }); + return undefined; + } + if (!options.adbProvider?.spawn) { + emitDiagnostic({ + phase: 'android_snapshot_helper_session_acquisition', + data: { outcome: 'spawn-unavailable' }, + }); return undefined; } const callerResolved = resolveAndroidSnapshotHelperCaptureOptions(options); @@ -172,9 +183,21 @@ async function resolveAndroidSnapshotHelperSession(params: { resolved: AndroidSnapshotHelperResolvedCaptureOptions; startBudgetMs: number; }): Promise { - if (isAndroidSnapshotHelperSessionBackedOff(params.identity)) return undefined; + if (isAndroidSnapshotHelperSessionBackedOff(params.identity)) { + emitDiagnostic({ + phase: 'android_snapshot_helper_session_acquisition', + data: { outcome: 'backed-off' }, + }); + return undefined; + } await retireUnusableAndroidSnapshotHelperSession(params.deviceKey, params.identity); - return sessions().get(params.deviceKey) ?? (await tryStartAndroidSnapshotHelperSession(params)); + const existing = sessions().get(params.deviceKey); + const session = existing ?? (await tryStartAndroidSnapshotHelperSession(params)); + emitDiagnostic({ + phase: 'android_snapshot_helper_session_acquisition', + data: { outcome: existing ? 'reused' : session ? 'created' : 'start-failed' }, + }); + return session; } /** Drops a cached session this command cannot write to, so only its forward is left behind. */ diff --git a/packages/plugins/package.json b/packages/plugins/package.json index 319a6e2fb0..5bbe4534db 100644 --- a/packages/plugins/package.json +++ b/packages/plugins/package.json @@ -30,10 +30,6 @@ "types": "./src/load.ts", "default": "./src/load.ts" }, - "./manifest": { - "types": "./src/manifest.ts", - "default": "./src/manifest.ts" - }, "./registry": { "types": "./src/registry.ts", "default": "./src/registry.ts" @@ -45,6 +41,10 @@ "./credential-fingerprint": { "types": "./src/credential-fingerprint.ts", "default": "./src/credential-fingerprint.ts" + }, + "./replay-backend": { + "types": "./src/replay-backend.ts", + "default": "./src/replay-backend.ts" } }, "devDependencies": { diff --git a/packages/plugins/src/connection.ts b/packages/plugins/src/connection.ts index 021c297ce0..d91256e49f 100644 --- a/packages/plugins/src/connection.ts +++ b/packages/plugins/src/connection.ts @@ -2,23 +2,22 @@ import type { ConnectionProviderCapabilities } from '@agent-device/contracts/rem import { resolveUserConfigPath } from '@agent-device/host-kit/file'; import type { PluginInventoryEntry } from '@agent-device/contracts/plugin-inventory'; import type { PluginConnection, PluginConnectionContext } from './contract.ts'; -import { legacyStoreManifests, storePluginCandidates } from './store.ts'; +import { storePluginCandidates } from './store.ts'; /** A plugin's connection as the client calls it: the registry adds the `host` to each context. */ export type PluginConnectionCallbacks = Readonly<{ resolve(context: Omit): ReturnType; verify( - context: Omit, 'host'>, + context: Omit, 'host'>, ): ReturnType; }>; export type RegisteredConnection = PluginConnectionCallbacks & Readonly<{ capabilities: PluginConnection['capabilities'] }>; -// Capabilities live in the plugin, so a v2 store plugin answers only once its package has loaded. -// A client loads the store once per process through primePluginConnections; every synchronous -// reader below then answers from that registry alone. Before the store is primed, a v1 plugin -// answers from its manifest. +// A plugin declares its connection capabilities in code, so a store plugin answers only once its +// package has loaded. A client loads the store once per process through primePluginConnections; +// every synchronous reader below then answers from that registry alone. export type FailedPlugin = Extract; type PrimedStore = Readonly<{ @@ -69,16 +68,10 @@ export function pluginConnectionCapabilities( env: NodeJS.ProcessEnv, ): ConnectionProviderCapabilities | undefined { if (provider === undefined) return undefined; - const store = primed.get(resolveUserConfigPath(env)); - if (store) return store.connections.get(provider)?.capabilities; - return legacyStoreManifests(env).find((plugin) => plugin.agentDevicePlugin.provider === provider) - ?.agentDevicePlugin.connection; + return primed.get(resolveUserConfigPath(env))?.connections.get(provider)?.capabilities; } export function pluginConnectionNames(env: NodeJS.ProcessEnv): string[] { const store = primed.get(resolveUserConfigPath(env)); - if (store) return [...store.connections.keys()]; - return legacyStoreManifests(env) - .filter((plugin) => plugin.agentDevicePlugin.connection) - .map((plugin) => plugin.agentDevicePlugin.provider); + return store ? [...store.connections.keys()] : []; } diff --git a/packages/plugins/src/contract.ts b/packages/plugins/src/contract.ts index 956645453a..99037cddae 100644 --- a/packages/plugins/src/contract.ts +++ b/packages/plugins/src/contract.ts @@ -9,6 +9,9 @@ import type { ProviderPluginHost } from './host.ts'; /** The provider plugin contract version this module defines. */ export const PROVIDER_PLUGIN_API_VERSION = 2; +/** Provider ids that name daemon routing; no plugin can claim either of them. */ +export const ROUTING_PROVIDER_IDENTITIES: readonly string[] = ['cloud', 'proxy']; + /** * The environment variables a plugin reads credentials from. The host fingerprints their values to * refuse a lease when the shell holds different credentials than the daemon started with. List diff --git a/packages/plugins/src/credential-fingerprint.ts b/packages/plugins/src/credential-fingerprint.ts index f2797cd046..3249ecaf56 100644 --- a/packages/plugins/src/credential-fingerprint.ts +++ b/packages/plugins/src/credential-fingerprint.ts @@ -4,7 +4,6 @@ import { type PluginInventoryEntry, } from '@agent-device/contracts/plugin-inventory'; import type { EnvMap } from '@agent-device/kernel/source-value'; -import { legacyStoreManifests } from './store-legacy.ts'; type CredentialValues = Readonly>; @@ -12,7 +11,7 @@ type CredentialValues = Readonly>; * A versioned, non-reversible digest of the credentials a lease on `leaseBackend` reads from `env`, * or undefined when `env` holds none of them or the provider's credentials do not come from the * environment. Provider names are trimmed before lookup. Variable names come from the daemon's - * plugin inventory, then from v1 manifests. + * plugin inventory. */ export function providerCredentialFingerprint( provider: string, @@ -20,7 +19,7 @@ export function providerCredentialFingerprint( leaseBackend?: string, inventory?: readonly PluginInventoryEntry[], ): string | undefined { - const variables = declaredCredentialVariables(provider.trim(), env, leaseBackend, inventory); + const variables = declaredCredentialVariables(provider.trim(), leaseBackend, inventory); // Whitespace-only counts as unset and other values are kept as is, as the provider's requireEnv does. return variables ? digest( @@ -31,17 +30,14 @@ export function providerCredentialFingerprint( : undefined; } -// Read from the inventory or manifest, so neither the client nor the daemon evaluates provider code. +// Read from the inventory the daemon published, so neither the client nor the daemon evaluates +// provider code. function declaredCredentialVariables( provider: string, - env: EnvMap, leaseBackend: string | undefined, inventory: readonly PluginInventoryEntry[] | undefined, ): readonly string[] | undefined { - const published = inventory && pluginCredentialVariables(inventory, provider, leaseBackend); - if (published) return published; - return legacyStoreManifests(env).find((plugin) => plugin.agentDevicePlugin.provider === provider) - ?.agentDevicePlugin.credentialVariables; + return inventory && pluginCredentialVariables(inventory, provider, leaseBackend); } function digest(values: CredentialValues): string | undefined { diff --git a/packages/plugins/src/discovery.test.ts b/packages/plugins/src/discovery.test.ts index ff2299bb0c..31ea661dd9 100644 --- a/packages/plugins/src/discovery.test.ts +++ b/packages/plugins/src/discovery.test.ts @@ -120,11 +120,68 @@ test('package export resolution agrees with Node for each shape a plugin package entry.name, ); } else { - assert.deepEqual( - discoverPluginEntry(directory), - { kind: 'v2', file: path.join(directory, entry.loads) }, - entry.name, - ); + assert.equal(discoverPluginEntry(directory), path.join(directory, entry.loads), entry.name); } } }); + +test('a manifest entry never selects the loaded file', () => { + const root = fs.realpathSync(mkdtempForTestSync('agent-device-manifest-entry-')); + const directory = path.join(root, 'node_modules', 'declared'); + fs.mkdirSync(directory, { recursive: true }); + fs.writeFileSync( + path.join(directory, 'package.json'), + JSON.stringify({ + name: 'declared', + version: '1.0.0', + type: 'module', + main: './main.js', + agentDevicePlugin: { apiVersion: 1, provider: 'declared', entry: './legacy.js' }, + }), + ); + for (const file of ['main.js', 'legacy.js']) + fs.writeFileSync(path.join(directory, file), 'export {};'); + + assert.equal(discoverPluginEntry(directory), path.join(directory, 'main.js')); +}); + +test('an entry outside the installed package is refused', () => { + const root = mkdtempForTestSync('agent-device-entry-containment-'); + const outside = path.join(root, 'outside.js'); + fs.writeFileSync(outside, 'export {};'); + + const escaped = path.join(root, 'node_modules', 'traversal'); + fs.mkdirSync(escaped, { recursive: true }); + fs.writeFileSync( + path.join(escaped, 'package.json'), + JSON.stringify({ + name: 'traversal', + version: '1.0.0', + type: 'module', + exports: { './agent-device': './../../outside.js' }, + }), + ); + assert.throws( + () => discoverPluginEntry(escaped), + (error: unknown) => + (error as { details?: { reason?: string } }).details?.reason === 'plugin_load_failed', + ); + + const linked = path.join(root, 'node_modules', 'symlinked'); + fs.mkdirSync(linked, { recursive: true }); + fs.writeFileSync( + path.join(linked, 'package.json'), + JSON.stringify({ + name: 'symlinked', + version: '1.0.0', + type: 'module', + exports: { './agent-device': './plugin.js' }, + }), + ); + fs.symlinkSync(outside, path.join(linked, 'plugin.js')); + assert.throws( + () => discoverPluginEntry(linked), + (error: unknown) => + (error as { details?: { reason?: string } }).details?.reason === 'plugin_load_failed', + ); +}); diff --git a/packages/plugins/src/discovery.ts b/packages/plugins/src/discovery.ts index d052660a03..b44c4ef0c3 100644 --- a/packages/plugins/src/discovery.ts +++ b/packages/plugins/src/discovery.ts @@ -2,7 +2,6 @@ import fs from 'node:fs'; import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; -import { readPluginManifest, resolvePluginEntry, type PluginManifest } from './manifest.ts'; const PROVIDER_ID = /^[a-z][a-z0-9-]*$/; @@ -10,29 +9,19 @@ export function isProviderId(value: unknown): value is string { return typeof value === 'string' && PROVIDER_ID.test(value); } -/** The subpath a v2 plugin package exports; its default export is the plugin factory. */ +/** The subpath a plugin package exports; its default export is the plugin factory. */ const PLUGIN_ENTRY_SUBPATH = './agent-device'; -export type PluginPackageEntry = - | Readonly<{ kind: 'v2'; file: string }> - | Readonly<{ kind: 'v1'; manifest: PluginManifest }>; - /** - * Chooses how an installed package loads, without evaluating it. The `./agent-device` export wins; - * a package that lacks that subpath and declares `agentDevicePlugin` is a v1 plugin dispatched by - * its manifest; any other package falls back to its root export. A subpath that exists but does - * not resolve is an error, never a reason to fall back. + * Chooses the file an installed package loads, without evaluating it. The `./agent-device` export + * wins; a package that lacks that subpath falls back to its root export. A subpath that exists but + * does not resolve is an error, never a reason to fall back. */ -export function discoverPluginEntry(directory: string): PluginPackageEntry { +export function discoverPluginEntry(directory: string): string { const manifest = readPackageJson(directory); const subpath = resolveExport(manifest.exports, PLUGIN_ENTRY_SUBPATH); - if (subpath.status === 'resolved') { - return { kind: 'v2', file: resolvePluginEntry(directory, subpath.target) }; - } + if (subpath.status === 'resolved') return resolvePluginEntry(directory, subpath.target); if (subpath.status === 'blocked') throw unresolvableEntry(directory, PLUGIN_ENTRY_SUBPATH); - if (manifest.agentDevicePlugin !== undefined) { - return { kind: 'v1', manifest: readPluginManifest(directory) }; - } const root = resolveExport(manifest.exports, '.'); if (root.status === 'blocked') throw unresolvableEntry(directory, '.'); const target = @@ -43,7 +32,30 @@ export function discoverPluginEntry(directory: string): PluginPackageEntry { ? `./${path.posix.normalize(manifest.main)}` : undefined; if (target === undefined) throw missingEntry(directory, PLUGIN_ENTRY_SUBPATH); - return { kind: 'v2', file: resolvePluginEntry(directory, target) }; + return resolvePluginEntry(directory, target); +} + +/** + * The entry a plugin package names: a readable file inside the package directory it is installed + * in. Traversal and a symlink out of that directory are refused. + */ +function resolvePluginEntry(directory: string, target: string): string { + try { + const root = fs.realpathSync(directory); + const resolved = fs.realpathSync(path.resolve(directory, target)); + if ( + target.startsWith('./') && + resolved.startsWith(`${root}${path.sep}`) && + fs.statSync(resolved).isFile() + ) { + return resolved; + } + } catch {} + throw new AppError('INVALID_ARGS', 'Plugin entry must be a readable file inside its package', { + reason: 'plugin_load_failed', + directory, + entry: target, + }); } export function readPackageJson(directory: string): Record { diff --git a/packages/plugins/src/host-command.test.ts b/packages/plugins/src/host-command.test.ts new file mode 100644 index 0000000000..8f0ffe6c3b --- /dev/null +++ b/packages/plugins/src/host-command.test.ts @@ -0,0 +1,147 @@ +import { expect, test } from 'vitest'; +import { withCommandExecutorOverride } from '@agent-device/host-kit/command'; +import { createPluginHost } from './host.ts'; + +test('plugin host runs commands with the AWS command bounds', async () => { + await withCommandExecutorOverride( + async (command, args, options) => { + expect(command).toBe('aws'); + expect(args).toEqual(['devicefarm', 'get-project']); + expect(options.maxBuffer).toBe(10 * 1024 * 1024); + expect(options.timeoutMs).toBe(30_000); + return { stdout: '{"project":{}}', stderr: '', exitCode: 0 }; + }, + async () => { + await expect( + createPluginHost({ env: {}, cwd: '/' }, undefined).runHostCommand('aws', [ + 'devicefarm', + 'get-project', + ]), + ).resolves.toEqual({ stdout: '{"project":{}}' }); + }, + ); +}); + +test('commands use the supplied host and overlay request environment without ambient values', async () => { + const { mkdtempForTestSync } = await import('@agent-device/test-kit'); + const { realpathSync } = await import('node:fs'); + const { withCommandHost } = await import('@agent-device/host-kit/command'); + const cwd = realpathSync(mkdtempForTestSync('plugin-command-host-')); + const host = { cwd, env: { PLUGIN_VALUE: 'host', HOST_ONLY: 'present' } }; + const pluginHost = createPluginHost(host, undefined); + const args = [ + '-e', + 'process.stdout.write(JSON.stringify({cwd:process.cwd(), value:process.env.PLUGIN_VALUE, hostOnly:process.env.HOST_ONLY, ambient:process.env.PLUGIN_AMBIENT}))', + ]; + const previous = process.env.PLUGIN_AMBIENT; + process.env.PLUGIN_AMBIENT = 'ambient'; + try { + const plain = await pluginHost.runHostCommand(process.execPath, args); + expect(JSON.parse(plain.stdout)).toEqual({ cwd, value: 'host', hostOnly: 'present' }); + const scoped = await withCommandHost({ host, requestEnv: { PLUGIN_VALUE: 'request' } }, () => + pluginHost.runHostCommand(process.execPath, args), + ); + expect(JSON.parse(scoped.stdout)).toEqual({ cwd, value: 'request', hostOnly: 'present' }); + } finally { + if (previous === undefined) delete process.env.PLUGIN_AMBIENT; + else process.env.PLUGIN_AMBIENT = previous; + } +}); + +test('connection resolve and verify use each call host independently', async () => { + const { mkdtempForTestSync } = await import('@agent-device/test-kit'); + const { realpathSync } = await import('node:fs'); + const { resolveProviderPlugins } = await import('./registry.ts'); + const dirs = [ + realpathSync(mkdtempForTestSync('plugin-resolve-')), + realpathSync(mkdtempForTestSync('plugin-verify-')), + ]; + const observed: unknown[] = []; + const run = async (host: import('./host.ts').ProviderPluginHost) => { + const result = await host.runHostCommand(process.execPath, [ + '-e', + 'process.stdout.write(JSON.stringify([process.cwd(), process.env.CONNECTION_VALUE]))', + ]); + observed.push(JSON.parse(result.stdout)); + }; + const { connections } = await resolveProviderPlugins([ + { + source: 'embedder', + load: () => ({ + apiVersion: 2, + provider: 'example', + credentials: { variables: [] }, + setup: () => ({}), + connection: { + capabilities: { + leaseKind: 'direct-device-provider', + requiresAppAttachment: false, + requiresRemoteDaemon: false, + supportsArtifacts: true, + supportsDeferredAppSelection: false, + supportsDirectPortReverse: false, + usesCloudWebDriverLease: true, + }, + resolve: async ({ host }: { host: import('./host.ts').ProviderPluginHost }) => { + await run(host); + return { profile: { leaseProvider: 'example', platform: 'ios' } }; + }, + verify: async ({ host }: { host: import('./host.ts').ProviderPluginHost }) => { + await run(host); + return { provider: 'example', service: 'example', verificationMessage: 'ok' }; + }, + }, + }), + }, + ]); + const connection = connections.get('example')!; + const flags = { json: false, help: false, version: false }; + await connection.resolve({ + flags, + stateDir: dirs[0]!, + cwd: dirs[0]!, + env: { CONNECTION_VALUE: 'resolve' }, + }); + await connection.verify({ flags, cwd: dirs[1]!, env: { CONNECTION_VALUE: 'verify' } }); + expect(observed).toEqual([ + [dirs[0], 'resolve'], + [dirs[1], 'verify'], + ]); +}); + +test('provider registry setup receives its supplied command host', async () => { + const { mkdtempForTestSync } = await import('@agent-device/test-kit'); + const { realpathSync } = await import('node:fs'); + const { resolveProviderPlugins, startProviderRegistry } = await import('./registry.ts'); + const cwd = realpathSync(mkdtempForTestSync('plugin-setup-host-')); + let observed: unknown; + const resolved = await resolveProviderPlugins([ + { + source: 'embedder', + load: () => ({ + apiVersion: 2, + provider: 'example', + credentials: { variables: [] }, + setup: async (host: import('./host.ts').ProviderPluginHost) => { + const result = await host.runHostCommand(process.execPath, [ + '-e', + 'process.stdout.write(JSON.stringify([process.cwd(), process.env.SETUP_VALUE]))', + ]); + observed = JSON.parse(result.stdout); + return { webDriver: { provider: 'example' } }; + }, + }), + }, + ]); + const registry = await startProviderRegistry( + resolved, + { cwd, env: { SETUP_VALUE: 'supplied' } }, + { + adaptWebDriver: async () => { + throw new Error('not needed for host assertion'); + }, + }, + ); + expect(observed).toEqual([cwd, 'supplied']); + await registry.close(); +}); diff --git a/packages/plugins/src/host.ts b/packages/plugins/src/host.ts index 19ac09c688..0fe45a78c8 100644 --- a/packages/plugins/src/host.ts +++ b/packages/plugins/src/host.ts @@ -1,21 +1,42 @@ +import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { AppError, type AppErrorCode, type AppErrorDetails } from '@agent-device/kernel/errors'; import { readVersion } from '@agent-device/host-kit/version'; +export type HostCommandResult = Readonly<{ stdout: string }>; + +export type RunHostCommand = ( + command: string, + args: readonly string[], +) => Promise; + export type ProviderPluginHost = Readonly<{ + /** Host-supplied command environment. Include PATH, HOME and provider inputs when needed. */ env: Readonly>; options: Readonly>; clientVersion: string; createError(code: AppErrorCode, message: string, details?: AppErrorDetails): AppError; + /** Runs in the supplied host cwd/env; ambient process values are not added. */ + runHostCommand: RunHostCommand; }>; export function createPluginHost( - env: NodeJS.ProcessEnv, + host: HostEnvironment, options: Record | undefined, ): ProviderPluginHost { return Object.freeze({ - env: Object.freeze({ ...env }), + env: Object.freeze({ ...host.env }), options: Object.freeze({ ...options }), clientVersion: readVersion(), createError: (code, message, details) => new AppError(code, message, details), + runHostCommand: async (command, args) => { + const { runCmd } = await import('@agent-device/host-kit/command'); + const { stdout } = await runCmd(command, [...args], { + cwd: host.cwd, + env: host.env, + maxBuffer: 10 * 1024 * 1024, + timeoutMs: 30_000, + }); + return { stdout }; + }, } satisfies ProviderPluginHost); } diff --git a/packages/plugins/src/legacy.ts b/packages/plugins/src/legacy.ts deleted file mode 100644 index 2a61fddea4..0000000000 --- a/packages/plugins/src/legacy.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { pathToFileURL } from 'node:url'; -import { AppError } from '@agent-device/kernel/errors'; -import { isRecord } from '@agent-device/kernel/record'; -import type { EnvMap } from '@agent-device/kernel/source-value'; -import type { ProviderDeviceRuntime } from '@agent-device/contracts/device'; -import { - PROVIDER_PLUGIN_API_VERSION, - type AgentDevicePlugin, - type PluginConnection, - type PluginSetupResult, -} from './contract.ts'; -import { createPluginHost, type ProviderPluginHost } from './host.ts'; -import { resolvePluginEntry, type PluginManifest } from './manifest.ts'; - -type LegacyConnection = Pick; - -/** - * Presents a v1 plugin as a v2 plugin until 0.22 removes v1. The manifest still declares the - * provider, connection capabilities and credential variables, and the v1 factory still runs with - * the host and returns `{ runtime, platformModule }` or `{ webDriver }`, so no v1 plugin changes. - */ -export function adaptLegacyPlugin( - manifest: PluginManifest, - directory: string, - options: Record | undefined, -): AgentDevicePlugin { - const declaration = manifest.agentDevicePlugin; - const runFactory = async (host: ProviderPluginHost): Promise => { - const module = await import( - pathToFileURL(resolvePluginEntry(directory, declaration.entry)).href - ); - if (typeof module.default !== 'function') - throw new AppError('INVALID_ARGS', `Plugin must export a default factory: ${manifest.name}`, { - reason: 'invalid_plugin', - }); - return await (module.default as (host: ProviderPluginHost) => unknown)(host); - }; - const withConnection = async ( - env: EnvMap, - run: (connection: LegacyConnection) => Promise | T, - ): Promise => { - const result = await runFactory(createPluginHost(env, options)); - try { - const connection = isRecord(result) ? result.connection : undefined; - if ( - !isRecord(connection) || - !isFunction(connection.resolve) || - !isFunction(connection.verify) - ) { - throw new AppError( - 'INVALID_ARGS', - `Plugin connection must provide resolve and verify: ${manifest.name}`, - { reason: 'invalid_plugin' }, - ); - } - return await run(connection as LegacyConnection); - } finally { - const runtime = isRecord(result) - ? (result.runtime as ProviderDeviceRuntime | undefined) - : undefined; - if (isFunction(runtime?.shutdown)) await Promise.allSettled([runtime.shutdown()]); - } - }; - return { - apiVersion: PROVIDER_PLUGIN_API_VERSION, - provider: declaration.provider, - credentials: { variables: declaration.credentialVariables ?? [] }, - ...(declaration.connection - ? { - connection: { - capabilities: declaration.connection, - resolve: async (context) => - await withConnection(context.env, (connection) => connection.resolve(context)), - verify: async (context) => - await withConnection(context.env, (connection) => connection.verify(context)), - }, - } - : {}), - setup: async (host) => { - const result = await runFactory(host); - return ( - isRecord(result) && 'webDriver' in result ? { webDriver: result.webDriver } : result - ) as PluginSetupResult; - }, - }; -} - -function isFunction(value: unknown): value is (...args: never[]) => unknown { - return typeof value === 'function'; -} diff --git a/packages/plugins/src/load.test.ts b/packages/plugins/src/load.test.ts index 1da14a14eb..7d3eefc12d 100644 --- a/packages/plugins/src/load.test.ts +++ b/packages/plugins/src/load.test.ts @@ -5,14 +5,11 @@ import { test } from 'vitest'; import { withPluginConnection } from './load.ts'; import { pluginHome, - registrationSource, - selectPlugin, selectV2Plugin, v2RegistrationSource, webDriverPluginSource, } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; -import type { ProviderPluginHost } from './host.ts'; import type { PluginRegistryPolicy } from './registry.ts'; import type { ProviderDeviceRuntime } from '@agent-device/contracts/device'; @@ -48,20 +45,30 @@ async function startStore(env: NodeJS.ProcessEnv, builtin: readonly string[] = [ ...claimProviderIds(builtin), ...(await storePluginCandidates(env)), ]); - return await startProviderRegistry(resolved, env, FAKE_POLICY); + return await startProviderRegistry(resolved, { env, cwd: '/' }, FAKE_POLICY); } -test('a v1 store plugin loads through the adapter with options and the host error constructor', async () => { +test('a store plugin loads its factory with the selection options and the host error constructor', async () => { const { home, env } = pluginHome(); - selectPlugin(home, 'example', 'example', registrationSource('example')); + selectV2Plugin( + home, + '@example/v2', + v2RegistrationSource('example').replace( + 'options, hostEnv: host.env }', + 'options, hostEnv: host.env, createError: host.createError }', + ), + ); const registry = await startStore(env); - const runtime = registry.registrations[0]!.runtime as ProviderDeviceRuntime & ProviderPluginHost; + const runtime = registry.registrations[0]!.runtime as ProviderDeviceRuntime & { + options: unknown; + createError: (code: 'INVALID_ARGS', message: string) => unknown; + }; assert.deepEqual(runtime.options, { region: 'eu' }); assert.ok(runtime.createError('INVALID_ARGS', 'bad profile') instanceof AppError); await registry.close(); }); -test('a v2 store plugin loads its factory with the selection options', async () => { +test('a plugin package loads its factory with the selection options', async () => { const { home, env } = pluginHome(); selectV2Plugin(home, '@example/v2', v2RegistrationSource('example')); const registry = await startStore(env); @@ -84,10 +91,10 @@ test('a v2 store plugin loads its factory with the selection options', async () await registry.close(); }); -test('v1 and v2 store plugins register in package-name order whichever version they are', async () => { +test('store plugins register in package-name order', async () => { const { home, env } = pluginHome(); selectV2Plugin(home, 'b-plugin', v2RegistrationSource('second')); - selectPlugin(home, 'a-plugin', 'first', registrationSource('first')); + selectV2Plugin(home, 'a-plugin', v2RegistrationSource('first')); const registry = await startStore(env); assert.deepEqual( registry.inventory.map(({ provider, source, package: name }) => [provider, source, name]), @@ -118,7 +125,17 @@ test('a broken plugin is listed as failed while its working neighbor registers', 'e-setup-fails', `export default () => ({ apiVersion: 2, provider: 'setup-fails', credentials: { variables: [] }, setup: async () => { throw new Error('setup failed'); } });`, ); - selectPlugin(home, 'f-bad-owner', 'bad-owner', registrationSource('other-id')); + selectV2Plugin( + home, + 'f-bad-owner', + `export default () => ({ + apiVersion: 2, provider: 'declared-id', credentials: { variables: [] }, + setup: async () => ({ + runtime: { provider: 'other-id', ownsDevice: () => false, getInteractor: () => undefined, + deviceInventoryProvider: async () => [], leaseLifecycle: {}, shutdown: async () => {} }, + platformModule: { owner: { kind: 'provider-runtime', provider: 'other-id', instance: 'test' }, loadRuntime: async () => { throw new Error('lazy'); } } }) + });`, + ); const registry = await startStore(env); assert.deepEqual( @@ -167,16 +184,16 @@ test('the first plugin to name a provider claims it even when it fails, and late await registry.close(); }); -test('a v1 manifest is dispatched before any factory runs and an incompatible one is only listed', async () => { +test('a package whose factory returns the v1 shape is listed as incompatible', async () => { const { home, env } = pluginHome(); - const marker = path.join(home, 'evaluated'); - selectPlugin( + selectV2Plugin( home, - 'one', - 'one', - `import fs from 'node:fs'; fs.writeFileSync(${JSON.stringify(marker)}, 'yes');`, + 'v1-factory', + `export default () => ({ + runtime: { provider: 'v1-factory', ownsDevice: () => false, getInteractor: () => undefined, + deviceInventoryProvider: async () => [], leaseLifecycle: {}, shutdown: async () => {} }, + platformModule: { owner: { kind: 'provider-runtime', provider: 'v1-factory', instance: 'test' }, loadRuntime: async () => { throw new Error('lazy'); } } });`, ); - selectPlugin(home, 'two', 'other', 'throw new Error("evaluated");', 2); const { resolveProviderPlugins, claimProviderIds } = await import('./registry.ts'); const { storePluginCandidates } = await import('./store.ts'); const resolved = await resolveProviderPlugins([ @@ -184,13 +201,11 @@ test('a v1 manifest is dispatched before any factory runs and an incompatible on ...(await storePluginCandidates(env)), ]); - assert.ok(!fs.existsSync(marker)); + // A v1 package used to be dispatched from its manifest and registered; the contract version is + // now the only way in, so it is listed and skipped like any other incompatible plugin. assert.deepEqual( resolved.inventory().map(({ package: name, state, error }) => [name, state, error?.reason]), - [ - ['one', 'active', undefined], - ['two', 'failed', 'incompatible_plugin'], - ], + [['v1-factory', 'failed', 'incompatible_plugin']], ); }); @@ -231,16 +246,16 @@ test('entry discovery prefers ./agent-device and falls back to the root export o }); test('startup failure of one plugin cleans up its constructed runtime and keeps the others', async () => { - for (const instance of ["'test'", 'undefined', '42', '" "']) { + for (const instance of ['null', 'undefined', '42', '" "']) { const { home, env } = pluginHome(); const first = path.join(home, 'first-shutdown'); const invalid = path.join(home, 'invalid-shutdown'); - selectPlugin(home, 'one', 'one', registrationSource('one', first)); - const source = registrationSource(instance === "'test'" ? 'wrong' : 'two', invalid).replace( + selectV2Plugin(home, 'one', v2RegistrationSource('one', { shutdownFile: first })); + const source = v2RegistrationSource('two', { shutdownFile: invalid }).replace( "instance: 'test'", `instance: ${instance}`, ); - selectPlugin(home, 'two', 'two', source); + selectV2Plugin(home, 'two', source); const registry = await startStore(env); assert.deepEqual( registry.registrations.map(({ provider }) => provider), @@ -307,49 +322,7 @@ test('a frozen runtime registers untouched, serves its facets, and is shut down assert.equal(fs.readFileSync(log, 'utf8'), 'runtime;dispose;'); }); -test('connection callbacks run from a v1 plugin and always release its runtime', async () => { - const { home, env } = pluginHome(); - const marker = path.join(home, 'shutdown'); - const source = registrationSource('example', marker).replace( - 'platformModule:', - "connection: { resolve: () => ({ profile: { leaseProvider: 'example', platform: 'android' } }), verify: async () => { throw host.createError('COMMAND_FAILED', 'verification failed'); } }, platformModule:", - ); - selectPlugin(home, 'example', 'example', source); - selectPlugin(home, 'unrelated', 'unrelated', 'throw new Error("unrelated plugin evaluated");'); - const manifestPath = path.join( - home, - 'plugins', - JSON.parse(fs.readFileSync(path.join(home, 'config.json'), 'utf8')).plugins.example - .installation, - 'node_modules/example/package.json', - ); - const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); - manifest.agentDevicePlugin.connection = LOCAL_CONNECTION; - fs.writeFileSync(manifestPath, JSON.stringify(manifest)); - const flags = { json: false, help: false, version: false }; - - const profile = await withPluginConnection( - 'example', - ['limrun'], - env, - async (connection) => await connection.resolve({ flags, stateDir: home, cwd: home, env }), - ); - assert.equal(profile.profile.platform, 'android'); - assert.ok(fs.existsSync(marker)); - fs.unlinkSync(marker); - await assert.rejects( - withPluginConnection( - 'example', - ['limrun'], - env, - async (connection) => await connection.verify({ flags, env }), - ), - { code: 'COMMAND_FAILED' }, - ); - assert.ok(fs.existsSync(marker)); -}); - -test('a v2 plugin connection runs without setting up any runtime', async () => { +test('a plugin connection runs without setting up any runtime', async () => { const { home, env } = pluginHome(); const marker = path.join(home, 'setup-ran'); selectV2Plugin( @@ -397,7 +370,7 @@ const LOCAL_CONNECTION = { test('a WebDriver descriptor is adapted by the policy, and a mismatched provider never reaches it', async () => { const { home, env } = pluginHome(); const source = webDriverPluginSource('example'); - selectPlugin(home, 'example', 'example', source); + selectV2Plugin(home, 'example', source); const registry = await startStore(env, []); assert.deepEqual( registry.registrations.map(({ provider, runtime }) => [provider, runtime.provider]), @@ -408,7 +381,12 @@ test('a WebDriver descriptor is adapted by the policy, and a mismatched provider adaptedDescriptors.length = 0; const other = pluginHome(); - selectPlugin(other.home, 'example', 'wrong', source); + selectV2Plugin( + other.home, + 'example', + // The descriptor names a provider the plugin did not declare. + source.replace('"provider":"example","endpoint"', '"provider":"wrong","endpoint"'), + ); const mismatched = await startStore(other.env, []); assert.deepEqual(mismatched.registrations, []); assert.equal(mismatched.inventory[0]!.error?.reason, 'invalid_plugin'); @@ -418,7 +396,7 @@ test('a WebDriver descriptor is adapted by the policy, and a mismatched provider test('a factory returning a primitive is listed as an invalid plugin', async () => { for (const value of ['42', '"runtime"', 'true']) { const { home, env } = pluginHome(); - selectPlugin(home, 'example', 'example', `export default () => ${value};`); + selectV2Plugin(home, 'example', `export default () => ${value};`); const registry = await startStore(env, []); assert.deepEqual(registry.registrations, []); assert.equal(registry.inventory[0]!.state, 'failed'); diff --git a/packages/plugins/src/manifest.test.ts b/packages/plugins/src/manifest.test.ts deleted file mode 100644 index e676087558..0000000000 --- a/packages/plugins/src/manifest.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; -import { test } from 'vitest'; -import { readPluginManifest } from './manifest.ts'; -import { pluginHome, writePlugin } from '@agent-device/test-kit'; - -test('manifest compatibility is checked without evaluating plugin code', () => { - const { home } = pluginHome(); - const directory = writePlugin(home); - assert.equal(readPluginManifest(directory).agentDevicePlugin.provider, 'example'); - writePlugin(home, '@example/provider', 2); - assert.throws(() => readPluginManifest(directory), { - code: 'INVALID_ARGS', - details: { - reason: 'incompatible_plugin', - apiVersion: 1, - hint: 'Install a plugin release supporting agentDevicePlugin.apiVersion 1.', - }, - }); -}); - -test('manifest refuses traversal and symlink entries outside the installed package', () => { - const { home } = pluginHome(); - const directory = writePlugin(home); - const outside = path.join(home, 'outside.js'); - fs.writeFileSync(outside, 'throw new Error("outside");'); - fs.unlinkSync(path.join(directory, 'plugin.js')); - fs.symlinkSync(outside, path.join(directory, 'plugin.js')); - assert.throws(() => readPluginManifest(directory), { code: 'INVALID_ARGS' }); - const manifest = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf8')); - manifest.agentDevicePlugin.entry = '../../../outside.js'; - fs.writeFileSync(path.join(directory, 'package.json'), JSON.stringify(manifest)); - assert.throws(() => readPluginManifest(directory), { code: 'INVALID_ARGS' }); -}); - -test('connection metadata admits local providers and rejects malformed or remote policies', () => { - const { home } = pluginHome(); - const directory = writePlugin(home); - const file = path.join(directory, 'package.json'); - const manifest = JSON.parse(fs.readFileSync(file, 'utf8')); - const connection = { - leaseKind: 'direct-device-provider', - requiresAppAttachment: true, - requiresRemoteDaemon: false, - supportsArtifacts: true, - supportsDeferredAppSelection: false, - supportsDirectPortReverse: false, - usesCloudWebDriverLease: true, - }; - const read = (policy: unknown) => { - manifest.agentDevicePlugin.connection = policy; - fs.writeFileSync(file, JSON.stringify(manifest)); - return readPluginManifest(directory); - }; - assert.deepEqual(read(connection).agentDevicePlugin.connection, connection); - const cloud = { ...connection, holdsCloudDevice: true, forgetsEndedConnectionLease: true }; - assert.deepEqual(read(cloud).agentDevicePlugin.connection, cloud); - for (const invalid of [ - null, - {}, - { ...connection, leaseKind: 'remote-daemon' }, - { ...connection, requiresRemoteDaemon: true }, - { ...connection, supportsArtifacts: 'true' }, - { ...connection, supportsDeferredAppSelection: undefined }, - { ...connection, holdsCloudDevice: 'false' }, - { ...connection, forgetsEndedConnectionLease: 'false' }, - ]) { - assert.throws(() => read(invalid), { code: 'INVALID_ARGS' }); - } -}); - -test('credential variables are optional environment variable names', () => { - const { home } = pluginHome(); - const directory = writePlugin(home); - const file = path.join(directory, 'package.json'); - const manifest = JSON.parse(fs.readFileSync(file, 'utf8')); - const read = (credentialVariables: unknown) => { - manifest.agentDevicePlugin.credentialVariables = credentialVariables; - fs.writeFileSync(file, JSON.stringify(manifest)); - return readPluginManifest(directory); - }; - assert.equal(read(undefined).agentDevicePlugin.credentialVariables, undefined); - assert.deepEqual(read(['EXAMPLE_USER', '_KEY_2']).agentDevicePlugin.credentialVariables, [ - 'EXAMPLE_USER', - '_KEY_2', - ]); - for (const invalid of [null, 'EXAMPLE_USER', {}, [''], ['example_user'], ['2KEY'], ['A-B'], [1]]) - assert.throws(() => read(invalid), { code: 'INVALID_ARGS' }, JSON.stringify(invalid)); -}); diff --git a/packages/plugins/src/manifest.ts b/packages/plugins/src/manifest.ts deleted file mode 100644 index 0422c38cee..0000000000 --- a/packages/plugins/src/manifest.ts +++ /dev/null @@ -1,118 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { AppError } from '@agent-device/kernel/errors'; -import type { ConnectionProviderCapabilities } from '@agent-device/contracts/remote'; - -/** Provider ids that name daemon routing, not a runtime a plugin can supply. */ -export const ROUTING_PROVIDER_IDENTITIES: readonly string[] = ['cloud', 'proxy']; - -const V1_PLUGIN_API_VERSION = 1; - -/** A v1 plugin package: the manifest declares what the host reads before any plugin code runs. */ -export type PluginManifest = { - name: string; - version: string; - agentDevicePlugin: { - apiVersion: number; - provider: string; - entry: string; - connection?: ConnectionProviderCapabilities; - credentialVariables?: string[]; - }; -}; - -const ENVIRONMENT_VARIABLE = /^[A-Z_][A-Z0-9_]*$/; - -function invalidManifest(message: string): AppError { - return new AppError('INVALID_ARGS', message, { reason: 'invalid_plugin' }); -} - -export function assertLocalConnectionCapabilities( - policy: ConnectionProviderCapabilities | undefined, -): void { - if (policy === undefined) return; - if ( - !policy || - typeof policy !== 'object' || - policy.leaseKind !== 'direct-device-provider' || - [ - 'requiresAppAttachment', - 'requiresRemoteDaemon', - 'supportsArtifacts', - 'supportsDeferredAppSelection', - 'supportsDirectPortReverse', - 'usesCloudWebDriverLease', - ].some((key) => typeof policy[key as keyof ConnectionProviderCapabilities] !== 'boolean') || - (policy.holdsCloudDevice !== undefined && typeof policy.holdsCloudDevice !== 'boolean') || - (policy.forgetsEndedConnectionLease !== undefined && - typeof policy.forgetsEndedConnectionLease !== 'boolean') || - policy.requiresRemoteDaemon - ) { - throw invalidManifest('Plugin connection must declare local provider capabilities'); - } -} - -export function assertCredentialVariables(variables: unknown): void { - if ( - variables !== undefined && - (!Array.isArray(variables) || - !variables.every((name) => typeof name === 'string' && ENVIRONMENT_VARIABLE.test(name))) - ) { - throw invalidManifest('Plugin credential variables must list environment variable names'); - } -} - -export function readPluginManifest(directory: string): PluginManifest { - let manifest: PluginManifest; - try { - const file = path.join(directory, 'package.json'); - manifest = JSON.parse(fs.readFileSync(file, 'utf8')) as PluginManifest; - } catch (error) { - throw new AppError( - 'INVALID_ARGS', - `Cannot read plugin manifest: ${directory}`, - {}, - error as Error, - ); - } - const declaration = manifest?.agentDevicePlugin; - if ( - typeof manifest?.name !== 'string' || - typeof manifest?.version !== 'string' || - !declaration || - declaration.apiVersion !== V1_PLUGIN_API_VERSION || - typeof declaration.provider !== 'string' || - !/^[a-z][a-z0-9-]*$/.test(declaration.provider) || - typeof declaration.entry !== 'string' || - !declaration.entry.startsWith('./') - ) { - throw new AppError('INVALID_ARGS', 'Package does not declare a compatible provider plugin', { - reason: 'incompatible_plugin', - apiVersion: V1_PLUGIN_API_VERSION, - hint: `Install a plugin release supporting agentDevicePlugin.apiVersion ${V1_PLUGIN_API_VERSION}.`, - }); - } - resolvePluginEntry(directory, declaration.entry); - assertLocalConnectionCapabilities(declaration.connection); - assertCredentialVariables(declaration.credentialVariables); - return manifest as PluginManifest; -} - -export function resolvePluginEntry(directory: string, target: string): string { - try { - const root = fs.realpathSync(directory); - const resolved = fs.realpathSync(path.resolve(directory, target)); - if ( - target.startsWith('./') && - resolved.startsWith(`${root}${path.sep}`) && - fs.statSync(resolved).isFile() - ) { - return resolved; - } - } catch {} - throw new AppError('INVALID_ARGS', 'Plugin entry must be a readable file inside its package', { - reason: 'plugin_load_failed', - directory, - entry: target, - }); -} diff --git a/packages/plugins/src/registry.ts b/packages/plugins/src/registry.ts index e5b2e9cb90..a83201326b 100644 --- a/packages/plugins/src/registry.ts +++ b/packages/plugins/src/registry.ts @@ -1,3 +1,15 @@ +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { NATIVE_REPLAY_BACKEND } from '@agent-device/contracts/replay-execution'; +import type { + ReplayExecution, + ReplayExecutionResolver, +} from '@agent-device/contracts/replay-execution'; +import type { ReplayBackend } from '@agent-device/contracts/replay-backend'; +import type { + ReplayEnginePlugin, + ReplayEngineSetup, + ReplayBackendResolver, +} from './replay-backend.ts'; import { AppError } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import type { ProviderDeviceRuntime } from '@agent-device/contracts/device'; @@ -20,8 +32,16 @@ import { } from '@agent-device/contracts/plugin-inventory'; import { describePluginFailure } from './inventory.ts'; import { isProviderId } from './discovery.ts'; -import { ROUTING_PROVIDER_IDENTITIES } from './manifest.ts'; -import { assertProviderRuntime, invalidPlugin, validateAgentDevicePlugin } from './validate.ts'; +import { ROUTING_PROVIDER_IDENTITIES } from './contract.ts'; +import { + assertProviderRuntime, + invalidPlugin, + validateAgentDevicePlugin, + validateReplayEnginePlugin, + validateReplayEngineSetup, + validateReplayBackend, + validateReplayExecution, +} from './validate.ts'; /** * One plugin a source offers the registry. Sources differ only in how a candidate loads; the @@ -31,11 +51,12 @@ export type PluginCandidate = Readonly<{ source: PluginSource; package?: string; version?: string; - /** Known before the plugin loads, such as a v1 manifest; a load failure still claims it. */ + selectionStamp?: string; + /** Claims `provider` before its load settles, so a later candidate with that id is a duplicate. Dormant candidates claim it without loading. */ provider?: string; /** Claims `provider` without registering or listing: a built-in that is not configured. */ dormant?: boolean; - /** The `options` the store passes to the host, which a v1 plugin reads. */ + /** The `options` the store passes to the host when it calls the factory. */ hostOptions?: Record; /** Returns the unvalidated plugin, or throws the reason it cannot load. */ load(): Promise | unknown; @@ -56,6 +77,7 @@ export function claimProviderIds(providers: readonly string[]): PluginCandidate[ * plugin's `{ webDriver }` descriptor becomes a runtime. */ export type PluginRegistryPolicy = Readonly<{ + assertReplaySelectionCurrent?(packageName: string): void; adaptWebDriver( descriptor: WebDriverDescriptor, context: Readonly<{ clientVersion: string }>, @@ -75,6 +97,12 @@ type Slot = { candidate: PluginCandidate; provider?: string; plugin?: AgentDevicePlugin; + backend?: string; + replayPlugin?: ReplayEnginePlugin; + replaySetup?: ReplayEngineSetup; + replayLoading?: Promise; + replayFailure?: unknown; + executionLoading?: Promise; failure?: unknown; registration?: ProviderRegistration; }; @@ -92,6 +120,8 @@ export type ResolvedProviderPlugins = Readonly<{ export type ProviderRegistry = Readonly<{ registrations: readonly ProviderRegistration[]; + resolveReplayBackend: ReplayBackendResolver; + resolveReplayExecution: ReplayExecutionResolver; claimedProviders: readonly string[]; inventory: readonly PluginInventoryEntry[]; /** @@ -112,6 +142,7 @@ export async function resolveProviderPlugins( ): Promise { const slots: Slot[] = []; const claimed = new Set(); + const claimedBackends = new Set(); for (const candidate of candidates) { const slot: Slot = { candidate, provider: candidate.provider }; slots.push(slot); @@ -119,23 +150,11 @@ export async function resolveProviderPlugins( if (candidate.provider !== undefined) claimed.add(candidate.provider); continue; } - try { - const raw = await candidate.load(); - slot.provider = readProviderId(raw) ?? candidate.provider; - slot.plugin = validateAgentDevicePlugin(raw); - } catch (error) { - slot.failure = asPluginFailure(error, 'plugin_load_failed'); - } - if (slot.provider === undefined || ROUTING_PROVIDER_IDENTITIES.includes(slot.provider)) - continue; - if (claimed.has(slot.provider)) { - slot.plugin = undefined; - slot.failure ??= new AppError('INVALID_ARGS', `Duplicate provider plugin: ${slot.provider}`, { - reason: 'duplicate_provider', - provider: slot.provider, - }); - } else claimed.add(slot.provider); + await loadSlot(slot); + claimBackend(slot, claimedBackends); + claimProvider(slot, claimed); } + return Object.freeze({ connections: new Map( slots.flatMap(({ plugin, candidate }) => @@ -161,13 +180,15 @@ export async function resolveProviderPlugins( */ export async function startProviderRegistry( resolved: ResolvedProviderPlugins, - env: NodeJS.ProcessEnv, + host: HostEnvironment, policy: PluginRegistryPolicy, + scope: 'all' | 'replay-backends' = 'all', ): Promise { for (const slot of resolved.slots) { - if (!slot.plugin || slot.failure !== undefined) continue; + if (slot.failure !== undefined) continue; try { - await setUpSlot(slot, slot.plugin, env, policy); + if (slot.replayPlugin) await setUpReplaySlot(slot, slot.replayPlugin, host); + else if (slot.plugin && scope === 'all') await setUpSlot(slot, slot.plugin, host, policy); } catch (error) { slot.failure = asPluginFailure(error, 'plugin_setup_failed'); slot.registration = undefined; @@ -176,14 +197,209 @@ export async function startProviderRegistry( const registrations = resolved.slots.flatMap(({ registration }) => registration ? [registration] : [], ); + let closed = false; + const inventory = [...resolved.inventory()]; return Object.freeze({ registrations, claimedProviders: resolved.claimedProviders, - inventory: resolved.inventory(), - close: once(async () => await Promise.all(registrations.map(cleanUp))), + inventory, + resolveReplayBackend: async (id, host, packageName) => { + if (closed) + throw new AppError('COMMAND_FAILED', 'Plugin registry is closed', { + reason: 'plugin-registry-closed', + }); + const slot = requireReplaySlot( + resolved, + id, + packageName, + policy.assertReplaySelectionCurrent, + ); + return await resolveRegisteredReplayBackend(resolved, slot, inventory, id, host); + }, + resolveReplayExecution: async (packageName) => { + if (closed) + throw new AppError('COMMAND_FAILED', 'Plugin registry is closed', { + reason: 'plugin-registry-closed', + }); + const slot = requireReplaySlot( + resolved, + NATIVE_REPLAY_BACKEND, + packageName, + policy.assertReplaySelectionCurrent, + ); + if (slot.failure !== undefined) throw replaySlotError(slot); + const execution = slot.replaySetup?.execution; + if (!execution) throw invalidPlugin('Native replay plugin must provide execution.create()'); + return await (slot.executionLoading ??= Promise.resolve().then(async () => { + try { + const runtime = validateReplayExecution(await execution.create()); + slot.replayFailure = undefined; + inventory.splice(0, inventory.length, ...resolved.inventory()); + return runtime; + } catch (error) { + slot.executionLoading = undefined; + slot.replayFailure = asPluginFailure(error, 'plugin_load_failed'); + inventory.splice(0, inventory.length, ...resolved.inventory()); + throw replaySlotError(slot); + } + })); + }, + close: once(async () => { + closed = true; + const [providers, backends] = await Promise.all([ + Promise.all(registrations.map(cleanUp)), + Promise.all(resolved.slots.map(cleanUpReplaySlot)), + ]); + return [...providers, ...backends.flat()]; + }), }); } +async function loadSlot(slot: Slot): Promise { + try { + const raw = await slot.candidate.load(); + if (isRecord(raw) && raw.kind === 'replay-backend') { + slot.provider = undefined; + slot.backend = typeof raw.backend === 'string' ? raw.backend : undefined; + slot.replayPlugin = validateReplayEnginePlugin(raw); + } else { + slot.provider = readProviderId(raw) ?? slot.candidate.provider; + slot.plugin = validateAgentDevicePlugin(raw); + } + } catch (error) { + slot.failure = asPluginFailure(error, 'plugin_load_failed'); + } +} + +function claimBackend(slot: Slot, claimed: Set): void { + if (slot.backend === undefined) return; + if (!claimed.has(slot.backend)) { + claimed.add(slot.backend); + return; + } + slot.replayPlugin = undefined; + slot.failure ??= new AppError('INVALID_ARGS', `Duplicate replay backend: ${slot.backend}`, { + reason: 'duplicate_replay_backend', + backend: slot.backend, + }); +} + +function claimProvider(slot: Slot, claimed: Set): void { + if (slot.provider === undefined || ROUTING_PROVIDER_IDENTITIES.includes(slot.provider)) return; + if (!claimed.has(slot.provider)) { + claimed.add(slot.provider); + return; + } + slot.plugin = undefined; + slot.failure ??= new AppError('INVALID_ARGS', `Duplicate provider plugin: ${slot.provider}`, { + reason: 'duplicate_provider', + provider: slot.provider, + }); +} + +async function setUpReplaySlot( + slot: Slot, + plugin: ReplayEnginePlugin, + host: HostEnvironment, +): Promise { + const result = await plugin.setup(createPluginHost(host, slot.candidate.hostOptions)); + try { + slot.replaySetup = validateReplayEngineSetup(result, plugin.backend); + } catch (error) { + await cleanUpRejectedSetup(result); + throw error; + } +} + +async function resolveRegisteredReplayBackend( + resolved: ResolvedProviderPlugins, + slot: Slot, + inventory: PluginInventoryEntry[], + id: string, + host: import('@agent-device/contracts/replay-backend').ReplayBackendHost, +): Promise { + if (slot.failure !== undefined) throw replaySlotError(slot); + const replayBackend = slot.replaySetup?.replayBackend; + if (!replayBackend) throw invalidPlugin(`Replay backend was not set up: ${id}`); + return await (slot.replayLoading ??= Promise.resolve().then(async () => { + try { + const backend = validateReplayBackend(id, await replayBackend.create(host)); + slot.replayFailure = undefined; + inventory.splice(0, inventory.length, ...resolved.inventory()); + return backend; + } catch (error) { + slot.replayLoading = undefined; + slot.replayFailure = asPluginFailure(error, 'plugin_load_failed'); + inventory.splice(0, inventory.length, ...resolved.inventory()); + throw replaySlotError(slot); + } + })); +} + +function requireReplaySlot( + resolved: ResolvedProviderPlugins, + id: string, + packageName: string | undefined, + assertSelectionCurrent?: (packageName: string) => void, +): Slot { + const slot = + resolved.slots.find((slot) => slot.backend === id) ?? + resolved.slots.find( + (slot) => + packageName !== undefined && + slot.candidate.package === packageName && + slot.backend === undefined && + slot.failure !== undefined, + ); + if (slot) { + if (slot.candidate.source === 'store' && slot.candidate.package) + assertSelectionCurrent?.(slot.candidate.package); + return slot; + } + if (packageName) assertSelectionCurrent?.(packageName); + throw new AppError('INVALID_ARGS', `Replay backend is not installed: ${id}`, { + reason: 'plugin-not-installed', + backend: id, + }); +} + +function replaySlotError(slot: Slot): AppError { + const error = asPluginFailure(slot.failure ?? slot.replayFailure, 'plugin_load_failed'); + const packageName = slot.candidate.package; + return new AppError( + error.code, + error.message, + { + ...error.details, + ...(packageName + ? { + package: packageName, + updateCommand: `agent-device plugins update ${packageName}`, + hint: `Repair or update ${packageName} on this host, then restart the daemon and retry the original invocation with all its arguments.`, + } + : { + hint: 'Repair the supplied replay plugin, then close and recreate the embedded runtime. Retry the original invocation with all its arguments.', + }), + }, + error, + ); +} + +async function cleanUpReplaySlot(slot: Slot): Promise { + const setup = slot.replaySetup; + const plugin = slot.replayPlugin; + if (!setup || !plugin) return []; + await (slot.replayLoading ?? slot.executionLoading)?.catch(() => {}); + return [ + { + backend: plugin.backend, + source: slot.candidate.source, + shutdown: { status: 'ok' }, + dispose: await attempt(async () => await setup.dispose?.()), + }, + ]; +} + function withConnectionHost( connection: PluginConnection, hostOptions: Record | undefined, @@ -191,25 +407,31 @@ function withConnectionHost( return { capabilities: connection.capabilities, resolve: (context) => - connection.resolve({ ...context, host: createPluginHost(context.env, hostOptions) }), + connection.resolve({ + ...context, + host: createPluginHost({ env: context.env, cwd: context.cwd }, hostOptions), + }), verify: (context) => - connection.verify({ ...context, host: createPluginHost(context.env, hostOptions) }), + connection.verify({ + ...context, + host: createPluginHost({ env: context.env, cwd: context.cwd }, hostOptions), + }), }; } async function setUpSlot( slot: Slot, plugin: AgentDevicePlugin, - env: NodeJS.ProcessEnv, + host: HostEnvironment, policy: PluginRegistryPolicy, ): Promise { - const host = createPluginHost(env, slot.candidate.hostOptions); - const result = await plugin.setup(host); + const pluginHost = createPluginHost(host, slot.candidate.hostOptions); + const result = await plugin.setup(pluginHost); try { const { runtime, platformModule } = await buildRegistration( plugin, result, - host.clientVersion, + pluginHost.clientVersion, policy, ); const dispose = result.dispose?.bind(result); @@ -287,16 +509,21 @@ function describeSlot(slot: Slot): PluginInventoryEntry[] { if (candidate.dormant) return []; const base = { ...(slot.provider !== undefined ? { provider: slot.provider } : {}), + ...(slot.backend !== undefined ? { backend: slot.backend } : {}), source: candidate.source, ...(candidate.package !== undefined ? { package: candidate.package } : {}), ...(candidate.version !== undefined ? { version: candidate.version } : {}), }; - if (slot.failure !== undefined || !plugin) { + if ( + slot.failure !== undefined || + slot.replayFailure !== undefined || + (!plugin && !slot.replayPlugin) + ) { return [ { ...base, state: 'failed', - error: describePluginFailure(slot.failure), + error: describePluginFailure(slot.failure ?? slot.replayFailure), credentials: NO_PLUGIN_CREDENTIALS, }, ]; @@ -306,9 +533,9 @@ function describeSlot(slot: Slot): PluginInventoryEntry[] { ...base, state: 'active', credentials: { - variables: [...plugin.credentials.variables], + variables: [...(plugin?.credentials.variables ?? [])], byBackend: Object.fromEntries( - Object.entries(plugin.credentials.byBackend ?? {}).map(([backend, names]) => [ + Object.entries(plugin?.credentials.byBackend ?? {}).map(([backend, names]) => [ backend, [...names], ]), diff --git a/packages/plugins/src/replay-backend.test.ts b/packages/plugins/src/replay-backend.test.ts new file mode 100644 index 0000000000..603b929790 --- /dev/null +++ b/packages/plugins/src/replay-backend.test.ts @@ -0,0 +1,413 @@ +import { expect, test, vi } from 'vitest'; +import { resolveProviderPlugins, startProviderRegistry } from './registry.ts'; +import type { PluginCandidate, PluginRegistryPolicy } from './registry.ts'; +import type { ReplayBackend, ReplayBackendHost } from '@agent-device/contracts/replay-backend'; +import { validateReplayEngineSetup } from './validate.ts'; +import type { ReplayExecution } from '@agent-device/contracts/replay-execution'; +import type { ProviderPluginHost } from './host.ts'; +import type { ReplayEnginePlugin } from './replay-backend.ts'; + +const host = {} as ReplayBackendHost; +const policy: PluginRegistryPolicy = { + adaptWebDriver: async () => { + throw new Error('no provider'); + }, +}; +function candidate(plugin: unknown): PluginCandidate { + return { source: 'embedder', load: () => plugin }; +} +function engine(backend = 'maestro') { + const runtime: ReplayBackend = { + id: backend, + collectSourceFiles: ({ entryPath, entrySource }) => ({ [entryPath]: entrySource }), + inspectSource: () => ({ title: 'flow', appTarget: 'com.example.app' }), + runReplay: vi.fn(async () => ({ ok: true as const, data: { replayed: 1 } })), + exportReplayScript: () => ({ yaml: '- launchApp\n', warnings: [] }), + }; + const create = vi.fn(async () => runtime); + const dispose = vi.fn(); + const setup = vi.fn((_host: ProviderPluginHost) => ({ replayBackend: { create }, dispose })); + return { + plugin: { apiVersion: 2, kind: 'replay-backend', backend, setup } satisfies ReplayEnginePlugin, + runtime, + create, + dispose, + setup, + }; +} + +test('managed replay setup stays lazy and retains one backend and one cleanup owner', async () => { + const e = engine(); + const resolved = await resolveProviderPlugins([candidate(e.plugin)]); + const registry = await startProviderRegistry( + resolved, + { env: { TOKEN: 'host-value' }, cwd: '/' }, + policy, + ); + expect(e.create).not.toHaveBeenCalled(); + expect(e.setup.mock.calls[0]?.[0]).toMatchObject({ env: { TOKEN: 'host-value' } }); + expect(registry.registrations).toEqual([]); + expect(registry.inventory).toMatchObject([{ backend: 'maestro', state: 'active' }]); + const [one, two] = await Promise.all([ + registry.resolveReplayBackend('maestro', host), + registry.resolveReplayBackend('maestro', host), + ]); + expect(one).toBe(e.runtime); + expect(two).toBe(one); + expect(e.create).toHaveBeenCalledExactlyOnceWith(host); + expect(await one.runReplay({} as never)).toMatchObject({ + ok: true as const, + data: { replayed: 1 }, + }); + expect(await registry.close()).toEqual([ + { + backend: 'maestro', + source: 'embedder', + shutdown: { status: 'ok' }, + dispose: { status: 'ok' }, + }, + ]); + await registry.close(); + expect(e.dispose).toHaveBeenCalledTimes(1); + await expect(registry.resolveReplayBackend('maestro', host)).rejects.toMatchObject({ + details: { reason: 'plugin-registry-closed' }, + }); +}); + +test('backend identity is separate from provider identity and first failure claims the backend', async () => { + const bad = { ...engine().plugin, apiVersion: 99 }; + const other = engine('other'); + const resolved = await resolveProviderPlugins([ + candidate(bad), + candidate(engine().plugin), + candidate(other.plugin), + ]); + const registry = await startProviderRegistry(resolved, { env: {}, cwd: '/' }, policy); + expect(registry.claimedProviders).toEqual([]); + expect(registry.inventory).toMatchObject([ + { backend: 'maestro', state: 'failed', error: { reason: 'incompatible_plugin' } }, + { backend: 'maestro', state: 'failed', error: { reason: 'duplicate_replay_backend' } }, + { backend: 'other', state: 'active' }, + ]); + await expect(registry.resolveReplayBackend('maestro', host)).rejects.toMatchObject({ + details: { reason: 'incompatible_plugin' }, + }); + expect((await registry.resolveReplayBackend('other', host)).inspectSource('', '')).toEqual({ + title: 'flow', + appTarget: 'com.example.app', + }); + await registry.close(); +}); + +test('setup failures stay permanent while failed lazy loads can retry without fallback', async () => { + const setup = engine('setup'); + setup.setup.mockImplementation(() => { + throw new Error('setup refused'); + }); + const load = engine('load'); + load.create.mockRejectedValueOnce(new Error('engine failed')); + const registry = await startProviderRegistry( + await resolveProviderPlugins([candidate(setup.plugin), candidate(load.plugin)]), + { env: {}, cwd: '/' }, + policy, + ); + await expect(registry.resolveReplayBackend('absent', host)).rejects.toMatchObject({ + details: { reason: 'plugin-not-installed' }, + }); + await expect(registry.resolveReplayBackend('setup', host)).rejects.toMatchObject({ + details: { reason: 'plugin_setup_failed' }, + }); + await expect(registry.resolveReplayBackend('load', host)).rejects.toMatchObject({ + message: 'engine failed', + details: { reason: 'plugin_load_failed' }, + }); + expect(registry.inventory[1]).toMatchObject({ + state: 'failed', + error: { reason: 'plugin_load_failed' }, + }); + const [one, two] = await Promise.all([ + registry.resolveReplayBackend('load', host), + registry.resolveReplayBackend('load', host), + ]); + expect(one).toBe(load.runtime); + expect(two).toBe(one); + expect(await registry.resolveReplayBackend('load', host)).toBe(one); + expect(load.create).toHaveBeenCalledTimes(2); + expect(registry.inventory[1]).toMatchObject({ state: 'active' }); + await expect(registry.resolveReplayBackend('setup', host)).rejects.toMatchObject({ + details: { reason: 'plugin_setup_failed' }, + }); + expect(setup.setup).toHaveBeenCalledTimes(1); + await registry.close(); + expect(load.dispose).toHaveBeenCalledTimes(1); +}); + +test('the registry rejects the wrong runtime id and cleans up an invalid setup', async () => { + const wrong = engine('wrong'); + wrong.create.mockResolvedValue({ ...wrong.runtime, id: 'different' }); + const dispose = vi.fn(); + const invalid = { ...engine('invalid').plugin, setup: () => ({ replayBackend: {}, dispose }) }; + const registry = await startProviderRegistry( + await resolveProviderPlugins([candidate(wrong.plugin), candidate(invalid)]), + { env: {}, cwd: '/' }, + policy, + ); + await expect(registry.resolveReplayBackend('wrong', host)).rejects.toMatchObject({ + details: { reason: 'invalid_plugin' }, + }); + await expect(registry.resolveReplayBackend('invalid', host)).rejects.toMatchObject({ + details: { reason: 'invalid_plugin' }, + }); + expect(dispose).toHaveBeenCalledTimes(1); + await registry.close(); +}); + +test('one backend disposer cannot delay another backend disposer', async () => { + const first = engine('first'); + const second = engine('second'); + let release!: () => void; + first.dispose.mockImplementation( + () => + new Promise((resolve) => { + release = resolve; + }), + ); + const registry = await startProviderRegistry( + await resolveProviderPlugins([candidate(first.plugin), candidate(second.plugin)]), + { env: {}, cwd: '/' }, + policy, + ); + const closing = registry.close(); + await Promise.resolve(); + expect(second.dispose).toHaveBeenCalledTimes(1); + release(); + expect(await closing).toHaveLength(2); +}); + +test('native execution retries failed lazy loads while sharing claims, caching and disposal', async () => { + const execution: ReplayExecution = { + inspectAdReplay: vi.fn(() => { + throw new Error('inspection is outside registry ownership'); + }), + runAdReplay: vi.fn(async () => { + throw new Error('dispatch is outside registry ownership'); + }), + runReplayTestSuite: vi.fn(async () => { + throw new Error('scheduling is outside registry ownership'); + }), + }; + const create = vi + .fn(async () => execution) + .mockRejectedValueOnce(new Error('native engine failed')); + const competing = { setup: vi.fn(() => ({ execution: { create } })) }; + const competingPlugin = { + apiVersion: 2, + kind: 'replay-backend', + backend: 'ad', + setup: competing.setup, + }; + const dispose = vi.fn(); + const registry = await startProviderRegistry( + await resolveProviderPlugins([ + candidate({ + apiVersion: 2, + kind: 'replay-backend', + backend: 'ad', + setup: () => ({ execution: { create }, dispose }), + }), + candidate(competingPlugin), + ]), + { env: {}, cwd: '/' }, + policy, + ); + expect(registry.inventory).toMatchObject([ + { backend: 'ad', state: 'active' }, + { backend: 'ad', state: 'failed', error: { reason: 'duplicate_replay_backend' } }, + ]); + expect(competing.setup).not.toHaveBeenCalled(); + await expect(registry.resolveReplayBackend('ad', host)).rejects.toMatchObject({ + details: { reason: 'invalid_plugin' }, + }); + expect(registry.inventory[0]).toMatchObject({ backend: 'ad', state: 'active' }); + expect(create).not.toHaveBeenCalled(); + await expect(registry.resolveReplayExecution()).rejects.toMatchObject({ + message: 'native engine failed', + details: { reason: 'plugin_load_failed' }, + }); + expect(create).toHaveBeenCalledTimes(1); + expect(registry.inventory[0]).toMatchObject({ + state: 'failed', + error: { reason: 'plugin_load_failed' }, + }); + const [one, two] = await Promise.all([ + registry.resolveReplayExecution(), + registry.resolveReplayExecution(), + ]); + expect(one).toBe(two); + expect(one).toBe(execution); + expect(await registry.resolveReplayExecution()).toBe(one); + expect(create).toHaveBeenCalledTimes(2); + expect(registry.inventory[0]).toMatchObject({ backend: 'ad', state: 'active' }); + expect(registry.inventory[0]?.error).toBeUndefined(); + await registry.close(); + expect(dispose).toHaveBeenCalledTimes(1); + await expect(registry.resolveReplayExecution()).rejects.toMatchObject({ + details: { reason: 'plugin-registry-closed' }, + }); +}); + +test.each([ + [{ apiVersion: 99 }, 'incompatible_plugin'], + [{ setup: () => ({ execution: {} }) }, 'invalid_plugin'], + [ + { + setup: () => { + throw new Error('failed setup'); + }, + }, + 'plugin_setup_failed', + ], + [{ setup: () => ({ execution: { create: () => ({}) } }) }, 'invalid_plugin'], +])( + 'selected native execution failures preserve their typed cause: %s', + async (override, reason) => { + const registry = await startProviderRegistry( + await resolveProviderPlugins([ + candidate({ + apiVersion: 2, + kind: 'replay-backend', + backend: 'ad', + setup: () => ({ execution: { create: () => ({}) } }), + ...override, + }), + ]), + { env: {}, cwd: '/' }, + policy, + ); + await expect(registry.resolveReplayExecution()).rejects.toMatchObject({ details: { reason } }); + await registry.close(); + }, +); + +test.each([ + ['ad', { replayBackend: { create: vi.fn() } }], + ['maestro', { execution: { create: vi.fn() } }], + ['custom', { execution: { create: vi.fn() } }], +])('setup validates the factory against backend %s', (backend, setup) => { + expect(() => validateReplayEngineSetup(setup, backend)).toThrow( + expect.objectContaining({ details: { reason: 'invalid_plugin' } }), + ); +}); + +test('wrong native capability fails inventory, disposes setup and keeps its first claim', async () => { + const wrong = engine('ad'); + const laterSetup = vi.fn(() => ({ execution: { create: vi.fn() } })); + const registry = await startProviderRegistry( + await resolveProviderPlugins([ + candidate(wrong.plugin), + candidate({ apiVersion: 2, kind: 'replay-backend', backend: 'ad', setup: laterSetup }), + candidate(engine('maestro').plugin), + ]), + { env: {}, cwd: '/' }, + policy, + ); + expect(registry.inventory).toMatchObject([ + { backend: 'ad', state: 'failed', error: { reason: 'invalid_plugin' } }, + { backend: 'ad', state: 'failed', error: { reason: 'duplicate_replay_backend' } }, + { backend: 'maestro', state: 'active' }, + ]); + expect(wrong.dispose).toHaveBeenCalledOnce(); + expect(wrong.create).not.toHaveBeenCalled(); + expect(laterSetup).not.toHaveBeenCalled(); + await expect(registry.resolveReplayExecution()).rejects.toMatchObject({ + details: { reason: 'invalid_plugin' }, + }); + await registry.close(); + expect(wrong.dispose).toHaveBeenCalledOnce(); +}); + +test('a package name cannot select an active foreign backend for native execution', async () => { + const maestro = engine(); + const packageName = '@agent-device/maestro'; + const registry = await startProviderRegistry( + await resolveProviderPlugins([ + { ...candidate(maestro.plugin), package: packageName }, + { + source: 'store', + package: '@agent-device/replay', + load: () => { + throw new Error('selected native package is unreadable'); + }, + }, + ]), + { env: {}, cwd: '/' }, + policy, + ); + try { + await expect(registry.resolveReplayExecution(packageName)).rejects.toMatchObject({ + details: { reason: 'plugin-not-installed', backend: 'ad' }, + }); + await expect(registry.resolveReplayExecution('@agent-device/replay')).rejects.toMatchObject({ + details: { reason: 'plugin_load_failed' }, + }); + expect(maestro.create).not.toHaveBeenCalled(); + expect(await registry.resolveReplayBackend('maestro', host, packageName)).toBe(maestro.runtime); + } finally { + await registry.close(); + } +}); + +test('a selected native package load failure cannot masquerade as absence by its message', async () => { + const registry = await startProviderRegistry( + await resolveProviderPlugins([ + { + source: 'store', + package: '@agent-device/replay', + load: () => { + throw new Error('Replay backend is not installed: ad'); + }, + }, + ]), + { env: {}, cwd: '/' }, + policy, + ); + try { + await expect(registry.resolveReplayExecution('@agent-device/replay')).rejects.toMatchObject({ + details: { + reason: 'plugin_load_failed', + package: '@agent-device/replay', + updateCommand: 'agent-device plugins update @agent-device/replay', + }, + }); + } finally { + await registry.close(); + } +}); + +test('replay setup receives the supplied command host', async () => { + const { mkdtempForTestSync } = await import('@agent-device/test-kit'); + const { realpathSync } = await import('node:fs'); + const cwd = realpathSync(mkdtempForTestSync('plugin-replay-host-')); + let result = ''; + const e = engine(); + const plugin = { + ...e.plugin, + setup: async (pluginHost: ProviderPluginHost) => { + result = ( + await pluginHost.runHostCommand(process.execPath, [ + '-e', + 'process.stdout.write(JSON.stringify([process.cwd(), process.env.REPLAY_HOST_VALUE]))', + ]) + ).stdout; + return e.setup(pluginHost); + }, + }; + const registry = await startProviderRegistry( + await resolveProviderPlugins([candidate(plugin)]), + { cwd, env: { REPLAY_HOST_VALUE: 'supplied' } }, + policy, + 'replay-backends', + ); + expect(JSON.parse(result)).toEqual([cwd, 'supplied']); + await registry.close(); +}); diff --git a/packages/plugins/src/replay-backend.ts b/packages/plugins/src/replay-backend.ts new file mode 100644 index 0000000000..937419a8cd --- /dev/null +++ b/packages/plugins/src/replay-backend.ts @@ -0,0 +1,30 @@ +import type { ReplayBackendPlugin } from '@agent-device/contracts/replay-backend'; +import type { + NATIVE_REPLAY_BACKEND, + ReplayExecutionPlugin, +} from '@agent-device/contracts/replay-execution'; +import type { ProviderPluginHost } from './host.ts'; + +/** A managed v2 replay engine. The host retains sessions, dispatch, cancellation and cleanup. */ +export type ReplayEnginePlugin = Readonly<{ + apiVersion: 2; + kind: 'replay-backend'; + backend: TBackend; + setup( + host: ProviderPluginHost, + ): Promise> | ReplayEngineSetup; +}>; + +type NativeExecutionSetup = { execution: ReplayExecutionPlugin; replayBackend?: never }; +type FormatBackendSetup = { replayBackend: ReplayBackendPlugin; execution?: never }; + +/** Native execution belongs to ad; other backend ids supply a format engine. */ +export type ReplayEngineSetup = Readonly< + { dispose?(): Promise | void } & (TBackend extends typeof NATIVE_REPLAY_BACKEND + ? NativeExecutionSetup + : string extends TBackend + ? NativeExecutionSetup | FormatBackendSetup + : FormatBackendSetup) +>; + +export type { ReplayBackendResolver } from '@agent-device/contracts/replay-backend'; diff --git a/packages/plugins/src/store-artifact.test.ts b/packages/plugins/src/store-artifact.test.ts new file mode 100644 index 0000000000..1d38413ce7 --- /dev/null +++ b/packages/plugins/src/store-artifact.test.ts @@ -0,0 +1,352 @@ +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { test, vi } from 'vitest'; +import * as command from '@agent-device/host-kit/command'; +import { tryAcquireProcessLock } from '@agent-device/host-kit/file'; +import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; +import { AppError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync, pluginHome, v2RegistrationSource } from '@agent-device/test-kit'; +import { + addPluginArtifact, + changePlugin, + createPluginSelectionGuard, + listPlugins, + storePluginCandidates, +} from './store.ts'; + +function packFixture( + root: string, + name: string, + exportsField: unknown = { './agent-device': './plugin.mjs' }, + factoryGate?: string, +) { + const source = path.join(root, name); + fs.mkdirSync(source, { recursive: true }); + const sentinel = path.join(root, `${name}-executed`); + fs.writeFileSync( + path.join(source, 'package.json'), + JSON.stringify({ + name, + version: '1.2.3', + type: 'module', + exports: exportsField, + scripts: { + preinstall: `node sentinel.cjs`, + install: `node sentinel.cjs`, + postinstall: `node sentinel.cjs`, + }, + }), + ); + fs.writeFileSync( + path.join(source, 'sentinel.cjs'), + `require('node:fs').writeFileSync(${JSON.stringify(sentinel)}, 'script')`, + ); + let pluginSource = v2RegistrationSource(name).replace( + 'export default (options = {}) => (', + `export default (options = {}) => (fs.writeFileSync(${JSON.stringify(sentinel)}, 'factory'), `, + ); + if (factoryGate) { + pluginSource = pluginSource.replace('export default ', 'const createPlugin = '); + pluginSource += `\nexport default async (options) => { + const gate = globalThis[Symbol.for(${JSON.stringify(factoryGate)})]; + gate.enter(); + await gate.resume; + return createPlugin(options); + };`; + } + fs.writeFileSync(path.join(source, 'plugin.mjs'), pluginSource); + const packed = command.runCmdSync( + 'npm', + ['pack', '--ignore-scripts', '--json', '--pack-destination', root], + { cwd: source }, + ); + assert.equal(packed.exitCode, 0, packed.stderr); + return { archive: path.join(root, JSON.parse(packed.stdout)[0].filename), sentinel }; +} + +test('artifact installation preserves immutable identity, isolation, collision and stale guard', async () => { + const root = mkdtempForTestSync('plugin-artifact-'); + const fixture = packFixture(root, 'fixture-provider'); + const { home, env: isolated } = pluginHome(); + const env = { ...process.env, ...isolated }; + const other = pluginHome(); + const expected = `sha512-${crypto.createHash('sha512').update(fs.readFileSync(fixture.archive)).digest('base64')}`; + const result = await addPluginArtifact(path.basename(fixture.archive), { cwd: root, env }); + assert.equal(result.integrity, expected); + assert.equal(result.name, 'fixture-provider'); + assert.equal(result.version, '1.2.3'); + assert.equal(fs.existsSync(fixture.sentinel), false); + assert.ok(fs.existsSync(fixture.archive)); + assert.deepEqual(await listPlugins(other.env, []), []); + const guard = createPluginSelectionGuard(await storePluginCandidates(env), env); + const configPath = path.join(home, 'config.json'); + const before = fs.readFileSync(configPath, 'utf8'); + await assert.rejects(addPluginArtifact(fixture.archive, { cwd: root, env }), { + code: 'INVALID_ARGS', + }); + await assert.rejects(changePlugin('update', result.name, env), { code: 'INVALID_ARGS' }); + await assert.rejects(changePlugin('add', result.name, env), { code: 'INVALID_ARGS' }); + assert.equal(fs.readFileSync(configPath, 'utf8'), before); + assert.equal(fs.readdirSync(path.join(home, 'plugins')).length, 1); + const [listed] = await listPlugins(env, []); + assert.equal(listed?.version, '1.2.3'); + assert.equal(listed?.integrity, expected); + assert.equal(listed?.installation, result.installation); + assert.equal(fs.readFileSync(fixture.sentinel, 'utf8'), 'factory'); + const config = JSON.parse(before); + config.plugins[result.name].artifact.integrity = + `sha512-${Buffer.alloc(64, 1).toString('base64')}`; + fs.writeFileSync(configPath, JSON.stringify(config)); + assert.throws( + () => guard(result.name), + (error: unknown) => + (error as { details?: { reason?: string } }).details?.reason === 'daemon-plugin-set-stale', + ); +}); + +test('invalid artifact and missing export roll back without disturbing selections', async () => { + const root = mkdtempForTestSync('plugin-artifact-invalid-'); + const { home, env: isolated } = pluginHome(); + const env = { ...process.env, ...isolated }; + const valid = packFixture(root, 'fixture-valid'); + await addPluginArtifact(valid.archive, { cwd: root, env }); + const before = fs.readFileSync(path.join(home, 'config.json'), 'utf8'); + const missing = packFixture(root, 'fixture-missing', { '.': './plugin.mjs' }); + await assert.rejects(addPluginArtifact(missing.archive, { cwd: root, env })); + const bad = path.join(root, 'bad.tgz'); + fs.writeFileSync(bad, 'not an archive'); + await assert.rejects(addPluginArtifact(bad, { cwd: root, env })); + assert.equal(fs.readFileSync(path.join(home, 'config.json'), 'utf8'), before); + assert.equal(fs.readdirSync(path.join(home, 'plugins')).length, 1); + assert.equal(fs.existsSync(missing.sentinel), false); +}); + +test('concurrent artifact additions preserve both selections', async () => { + const root = mkdtempForTestSync('plugin-artifact-concurrent-'); + const one = packFixture(root, 'fixture-one'); + const two = packFixture(root, 'fixture-two'); + const { env: isolated } = pluginHome(); + const env = { ...process.env, ...isolated }; + await Promise.all( + [one, two].map(({ archive }) => addPluginArtifact(archive, { cwd: root, env })), + ); + assert.deepEqual( + (await listPlugins(env, [])).map((plugin) => plugin.name), + ['fixture-one', 'fixture-two'], + ); + assert.equal(fs.existsSync(one.sentinel), true); +}); + +test('npm staging rejects an escaping symlink entry and leaves external files untouched', async () => { + const { default: tar } = await import('tar-stream'); + const { gzipSync } = await import('node:zlib'); + const root = mkdtempForTestSync('plugin-artifact-symlink-'); + const outside = path.join(root, 'outside.mjs'); + fs.writeFileSync(outside, 'outside'); + const archive = path.join(root, 'malicious.tgz'); + const stream = tar.pack(); + const chunks: Buffer[] = []; + stream.on('data', (chunk: Buffer) => chunks.push(chunk)); + stream.entry( + { name: 'package/package.json' }, + JSON.stringify({ + name: 'fixture-escape', + version: '1.0.0', + exports: { './agent-device': './plugin.mjs' }, + }), + ); + stream.entry({ name: 'package/plugin.mjs', type: 'symlink', linkname: outside }); + stream.entry({ name: 'package/../../escape' }, 'escaped'); + const finished = new Promise((resolve, reject) => { + stream.on('end', resolve); + stream.on('error', reject); + }); + stream.finalize(); + await finished; + fs.writeFileSync(archive, gzipSync(Buffer.concat(chunks))); + const { home, env: isolated } = pluginHome(); + await assert.rejects( + addPluginArtifact(archive, { cwd: root, env: { ...process.env, ...isolated } }), + ); + assert.equal(fs.readFileSync(outside, 'utf8'), 'outside'); + assert.equal(fs.existsSync(path.join(home, 'escape')), false); + assert.equal(fs.existsSync(path.join(home, 'config.json')), false); +}); + +test('artifact installation rejects replacement bytes consumed by npm', async () => { + const root = mkdtempForTestSync('plugin-artifact-replaced-'); + const originalRoot = path.join(root, 'original'); + const replacementRoot = path.join(root, 'replacement'); + const original = packFixture(originalRoot, 'fixture-replaced'); + const replacement = packFixture(replacementRoot, 'fixture-replaced'); + assert.notDeepEqual(fs.readFileSync(original.archive), fs.readFileSync(replacement.archive)); + const { home, env: isolated } = pluginHome(); + const env = { ...process.env, ...isolated }; + const runCmd = command.runCmd; + let replaced = false; + const spy = vi.spyOn(command, 'runCmd').mockImplementation(async (program, args, options) => { + if (program === 'npm' && args[0] === 'install' && args.at(-2) === '--') { + fs.copyFileSync(replacement.archive, args.at(-1)!); + replaced = true; + } + return runCmd(program, args, options); + }); + try { + await assert.rejects(addPluginArtifact(original.archive, { cwd: root, env }), { + code: 'INVALID_ARGS', + details: { reason: 'artifact_integrity_mismatch' }, + }); + assert.equal(replaced, true); + assert.equal(fs.existsSync(path.join(home, 'config.json')), false); + assert.deepEqual(fs.readdirSync(path.join(home, 'plugins')), []); + assert.equal(fs.existsSync(replacement.sentinel), false); + } finally { + spy.mockRestore(); + } +}); + +test('inventory retains one selection snapshot while a factory awaits', async () => { + const root = mkdtempForTestSync('plugin-artifact-inventory-'); + const key = `agent-device.artifact-inventory.${crypto.randomUUID()}`; + const first = packFixture(path.join(root, 'first'), 'fixture-inventory', undefined, key); + const second = packFixture(path.join(root, 'second'), 'fixture-inventory'); + const { env: isolated } = pluginHome(); + const env = { ...process.env, ...isolated }; + const original = await addPluginArtifact(first.archive, { cwd: root, env }); + let enter!: () => void; + let continueListing!: () => void; + const entered = new Promise((resolve) => { + enter = resolve; + }); + const resume = new Promise((resolve) => { + continueListing = resolve; + }); + const gates = globalThis as typeof globalThis & Record; + gates[Symbol.for(key)] = { enter, resume }; + const listing = listPlugins(env, []); + try { + await entered; + await changePlugin('remove', original.name, env); + const replacement = await addPluginArtifact(second.archive, { cwd: root, env }); + assert.notEqual(replacement.integrity, original.integrity); + continueListing(); + const [entry] = await listing; + assert.deepEqual(entry, { + name: original.name, + installation: original.installation, + integrity: original.integrity, + version: original.version, + provider: 'fixture-inventory', + compatible: true, + }); + const [current] = await listPlugins(env, []); + assert.equal(current?.installation, replacement.installation); + assert.equal(current?.integrity, replacement.integrity); + } finally { + continueListing(); + await listing; + delete gates[Symbol.for(key)]; + } +}); + +test.each([undefined, '~/plugin-store'])( + 'missing HOME does not preempt archive validation (%s)', + async (override) => { + const root = mkdtempForTestSync('plugin-artifact-home-'); + await assert.rejects( + addPluginArtifact(path.join(root, 'missing.tgz'), { + cwd: root, + env: { HOME: undefined, AGENT_DEVICE_HOME: override }, + }), + { code: 'ENOENT' }, + ); + }, +); + +test('failed staging cleanup reports both failures and releases the live store lock', async () => { + const root = mkdtempForTestSync('plugin-artifact-cleanup-'); + const archive = path.join(root, 'broken.tgz'); + fs.writeFileSync(archive, 'invalid archive'); + const { home, env: isolated } = pluginHome(); + const env = { ...process.env, ...isolated }; + const plugins = path.join(fs.realpathSync(home), 'plugins'); + const installError = new AppError('INVALID_ARGS', 'installation failed'); + const cleanupError = new Error('staging cleanup failed'); + const run = vi.spyOn(command, 'runCmd').mockRejectedValue(installError); + const rm = fs.rmSync.bind(fs); + const cleanup = vi.spyOn(fs, 'rmSync').mockImplementation((target, options) => { + if (typeof target === 'string' && path.dirname(target) === plugins) throw cleanupError; + return rm(target, options); + }); + let failure: unknown; + try { + try { + await addPluginArtifact(archive, { cwd: root, env }); + assert.fail('installation should fail'); + } catch (error) { + failure = error; + } + } finally { + cleanup.mockRestore(); + run.mockRestore(); + } + const attempt = tryAcquireProcessLock({ + lockDirPath: path.join(fs.realpathSync(home), 'plugins.lock'), + owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() }, + description: 'plugin installation', + }); + if (attempt.status === 'acquired') await attempt.acquisition.release(); + assert.equal(attempt.status, 'acquired', 'the still-live host must not retain the lock'); + assert.ok(failure instanceof AppError); + assert.equal(failure.code, 'COMMAND_FAILED'); + assert.equal(failure.details?.reason, 'plugin_cleanup_failed'); + assert.deepEqual( + (({ code, message }) => ({ code, message }))( + failure.details?.installationError as { code: string; message: string }, + ), + { code: 'INVALID_ARGS', message: installError.message }, + ); + assert.deepEqual( + (({ code, message }) => ({ code, message }))( + failure.details?.cleanupError as { code: string; message: string }, + ), + { code: 'UNKNOWN', message: cleanupError.message }, + ); + assert.equal(failure.cause, installError); +}); + +test('successful staging cleanup preserves the original installation error', async () => { + const root = mkdtempForTestSync('plugin-artifact-cleanup-success-'); + const archive = path.join(root, 'broken.tgz'); + fs.writeFileSync(archive, 'invalid archive'); + const { home, env: isolated } = pluginHome(); + const installError = new AppError('INVALID_ARGS', 'installation failed'); + const run = vi.spyOn(command, 'runCmd').mockRejectedValue(installError); + try { + await assert.rejects( + addPluginArtifact(archive, { cwd: root, env: { ...process.env, ...isolated } }), + (error: unknown) => error === installError, + ); + assert.deepEqual(fs.readdirSync(path.join(home, 'plugins')), []); + } finally { + run.mockRestore(); + } +}); + +test('malformed configuration fails before artifact staging', async () => { + const root = mkdtempForTestSync('plugin-artifact-invalid-config-'); + const archive = path.join(root, 'invalid.tgz'); + fs.writeFileSync(archive, 'not a valid archive'); + const { home, env } = pluginHome(); + fs.writeFileSync(path.join(home, 'config.json'), '{'); + const spy = vi.spyOn(command, 'runCmd'); + try { + await assert.rejects(addPluginArtifact(archive, { cwd: root, env }), { code: 'INVALID_ARGS' }); + assert.equal(spy.mock.calls.length, 0); + assert.equal(fs.existsSync(path.join(home, 'plugins')), false); + } finally { + spy.mockRestore(); + } +}); diff --git a/packages/plugins/src/store-legacy.ts b/packages/plugins/src/store-legacy.ts deleted file mode 100644 index 8d82695809..0000000000 --- a/packages/plugins/src/store-legacy.ts +++ /dev/null @@ -1,83 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { AppError } from '@agent-device/kernel/errors'; -import { isRecord } from '@agent-device/kernel/record'; -import { resolveUserConfigPath } from '@agent-device/host-kit/file'; -import { readPluginManifest, type PluginManifest } from './manifest.ts'; - -export type PluginSelection = { - installation: string; - version?: string; - options?: Record; -}; -type PluginConfig = Record & { plugins?: Record }; -export function readPluginConfig(env: NodeJS.ProcessEnv): PluginConfig { - const configPath = resolveUserConfigPath(env); - try { - const config = JSON.parse(fs.readFileSync(configPath, 'utf8')) as PluginConfig; - if (!isRecord(config) || (config.plugins !== undefined && !isRecord(config.plugins))) - throw new AppError('INVALID_ARGS', 'Plugin config must contain an object'); - return config; - } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {}; - if (error instanceof SyntaxError) - throw new AppError('INVALID_ARGS', `Invalid plugin JSON: ${configPath}`, {}, error); - throw error; - } -} - -export function validatePluginSelection(name: string, selection: PluginSelection): void { - if ( - !isPackageName(name) || - !isRecord(selection) || - typeof selection.installation !== 'string' || - !/^[a-f0-9-]{36}$/.test(selection.installation) || - (selection.version !== undefined && !isVersionSelector(selection.version)) || - (selection.options !== undefined && !isRecord(selection.options)) - ) { - throw new AppError('INVALID_ARGS', `Invalid plugin selection: ${name}`); - } -} - -export function storeHome(env: NodeJS.ProcessEnv): string { - return path.dirname(resolveUserConfigPath(env)); -} - -export function installationDirectory(home: string, name: string, installation: string): string { - return path.join(home, 'plugins', installation, 'node_modules', name); -} - -/** - * The v1 manifests in the store, read without executing anything, including those of a package - * that also exports `./agent-device`; unreadable selections are skipped. - */ -export function legacyStoreManifests(env: NodeJS.ProcessEnv): PluginManifest[] { - const home = storeHome(env); - let selections: [string, PluginSelection][]; - try { - selections = Object.entries(readPluginConfig(env).plugins ?? {}); - } catch { - return []; - } - return selections.flatMap(([name, selection]) => { - try { - validatePluginSelection(name, selection); - const manifest = readPluginManifest( - installationDirectory(home, name, selection.installation), - ); - return manifest.name === name ? [manifest] : []; - } catch { - return []; - } - }); -} - -function isPackageName(value: string): boolean { - return /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(value); -} - -export function isVersionSelector(value: unknown): value is string { - return ( - typeof value === 'string' && /^[a-zA-Z0-9*^~<>=| .+-]+$/.test(value) && value.trim().length > 0 - ); -} diff --git a/packages/plugins/src/store.test.ts b/packages/plugins/src/store.test.ts index 0a46f95f82..628d6183e6 100644 --- a/packages/plugins/src/store.test.ts +++ b/packages/plugins/src/store.test.ts @@ -3,14 +3,16 @@ import fs from 'node:fs'; import path from 'node:path'; import { afterEach, test, vi } from 'vitest'; import { runCmd } from '@agent-device/host-kit/command'; -import { changePlugin, legacyStoreManifests, listPlugins } from './store.ts'; +import { tryAcquireProcessLock } from '@agent-device/host-kit/file'; +import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; +import { AppError } from '@agent-device/kernel/errors'; import { - pluginHome, - selectPlugin, - selectV2Plugin, - v2RegistrationSource, - writePlugin, -} from '@agent-device/test-kit'; + changePlugin, + listPlugins, + createPluginSelectionGuard, + storePluginCandidates, +} from './store.ts'; +import { pluginHome, selectV2Plugin, v2RegistrationSource } from '@agent-device/test-kit'; vi.mock('@agent-device/host-kit/command', () => ({ runCmd: vi.fn() })); afterEach(() => vi.mocked(runCmd).mockReset()); @@ -33,7 +35,8 @@ function installedPlugins(env: NodeJS.ProcessEnv) { }); } -function installFixture(name = packageName, apiVersion = 1, provider = 'example') { +/** Stands in for `npm install`: writes a v2 plugin package into the staged project. */ +function installFixture(name = packageName, provider = 'example') { vi.mocked(runCmd).mockImplementation(async (command, argv, options) => { assert.equal(command, 'npm'); assert.equal(argv[argv.indexOf('--prefix') + 1], options!.cwd); @@ -41,7 +44,18 @@ function installFixture(name = packageName, apiVersion = 1, provider = 'example' assert.ok(argv.includes('--ignore-scripts')); assert.ok(argv.includes('--workspaces=false')); assert.ok(argv.includes('--package-lock=true')); - writePlugin(options!.cwd!, name, apiVersion, provider); + const directory = path.join(options!.cwd!, 'node_modules', name); + fs.mkdirSync(directory, { recursive: true }); + fs.writeFileSync( + path.join(directory, 'package.json'), + JSON.stringify({ + name, + version: '1.2.3', + type: 'module', + exports: { './agent-device': { import: './plugin.mjs' } }, + }), + ); + fs.writeFileSync(path.join(directory, 'plugin.mjs'), v2RegistrationSource(provider)); return { stdout: '', stderr: '', exitCode: 0 }; }); } @@ -50,13 +64,13 @@ test('add, pinned update and remove preserve flags, options and old installation const { home, env } = pluginHome(); fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify({ platform: 'android' })); installFixture(); - await changePlugin('add', `${packageName}@1.2.3`, env, []); + await changePlugin('add', `${packageName}@1.2.3`, env); const [first] = installedPlugins(env); const config = readPluginConfig(env); config.plugins![packageName]!.options = { region: 'eu' }; config.plugins![packageName]!.installation = '../damaged'; fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify(config)); - await changePlugin('update', packageName, env, []); + await changePlugin('update', packageName, env); const [second] = installedPlugins(env); assert.notEqual(first!.directory, second!.directory); assert.deepEqual(second!.selection.options, { region: 'eu' }); @@ -66,7 +80,7 @@ test('add, pinned update and remove preserve flags, options and old installation { [packageName]: '1.2.3' }, ); assert.equal(readPluginConfig(env).platform, 'android'); - await changePlugin('remove', packageName, env, []); + await changePlugin('remove', packageName, env); assert.deepEqual(installedPlugins(env), []); assert.ok(fs.existsSync(first!.directory)); assert.ok(fs.existsSync(second!.directory)); @@ -75,31 +89,83 @@ test('add, pinned update and remove preserve flags, options and old installation test('failed npm install and incompatible replacement preserve the active selection', async () => { const { home, env } = pluginHome(); installFixture(); - await changePlugin('add', packageName, env, []); + await changePlugin('add', packageName, env); const before = fs.readFileSync(path.join(home, 'config.json'), 'utf8'); vi.mocked(runCmd).mockRejectedValue(new Error('npm failed')); - await assert.rejects(changePlugin('update', packageName, env, []), /npm failed/); + await assert.rejects(changePlugin('update', packageName, env), /npm failed/); assert.equal(fs.readFileSync(path.join(home, 'config.json'), 'utf8'), before); - installFixture(packageName, 2); - await assert.rejects(changePlugin('update', packageName, env, []), { code: 'INVALID_ARGS' }); + // The replacement exports neither ./agent-device nor a root entry, so it is not a plugin package. + vi.mocked(runCmd).mockImplementation(async (_command, _argv, options) => { + const directory = path.join(options!.cwd!, 'node_modules', packageName); + fs.mkdirSync(directory, { recursive: true }); + fs.writeFileSync( + path.join(directory, 'package.json'), + JSON.stringify({ + name: packageName, + version: '2.0.0', + type: 'module', + exports: { './tools': './tools.js' }, + }), + ); + fs.writeFileSync(path.join(directory, 'tools.js'), 'export {};'); + return { stdout: '', stderr: '', exitCode: 0 }; + }); + await assert.rejects(changePlugin('update', packageName, env), { code: 'INVALID_ARGS' }); assert.equal(fs.readFileSync(path.join(home, 'config.json'), 'utf8'), before); assert.equal(fs.readdirSync(path.join(home, 'plugins')).length, 1); }); +test('a factory shaped for the removed v1 contract still installs', async () => { + const { env } = pluginHome(); + vi.mocked(runCmd).mockImplementation(async (_command, _argv, options) => { + const directory = path.join(options!.cwd!, 'node_modules', packageName); + fs.mkdirSync(directory, { recursive: true }); + fs.writeFileSync( + path.join(directory, 'package.json'), + JSON.stringify({ + name: packageName, + version: '1.2.3', + type: 'module', + exports: { './agent-device': { import: './plugin.mjs' } }, + }), + ); + fs.writeFileSync(path.join(directory, 'plugin.mjs'), 'export default () => ({ register: 1 });'); + return { stdout: '', stderr: '', exitCode: 0 }; + }); + // Installation only needs a loadable default export; the registry rejects the shape later. + await changePlugin('add', packageName, env); + const [listed] = await listPlugins(env, []); + assert.deepEqual( + { name: listed?.name, compatible: listed?.compatible }, + { name: packageName, compatible: false }, + ); +}); + test('concurrent additions serialize without dropping the other package', async () => { const { env } = pluginHome(); vi.mocked(runCmd).mockImplementation(async (_, __, options) => { const { dependencies } = JSON.parse( fs.readFileSync(path.join(options!.cwd!, 'package.json'), 'utf8'), ); - const name = Object.keys(dependencies)[0]!; - writePlugin(options!.cwd!, name, 1, name); + const name: string = Object.keys(dependencies)[0]!; + const directory = path.join(options!.cwd!, 'node_modules', name); + fs.mkdirSync(directory, { recursive: true }); + fs.writeFileSync( + path.join(directory, 'package.json'), + JSON.stringify({ + name, + version: '1.2.3', + type: 'module', + exports: { './agent-device': { import: './plugin.mjs' } }, + }), + ); + fs.writeFileSync( + path.join(directory, 'plugin.mjs'), + v2RegistrationSource(name.toLowerCase().replaceAll(/[^a-z0-9-]/g, '-')), + ); return { stdout: '', stderr: '', exitCode: 0 }; }); - await Promise.all([ - changePlugin('add', 'constructor', env, []), - changePlugin('add', 'two', env, []), - ]); + await Promise.all([changePlugin('add', 'constructor', env), changePlugin('add', 'two', env)]); assert.deepEqual( installedPlugins(env) .map(({ name }) => name) @@ -117,43 +183,52 @@ test('invalid package sources and damaged selections fail before invoking npm', 'plugin@npm:other', 'https://example.com/plugin', ]) { - await assert.rejects(changePlugin('add', name, env, []), { code: 'INVALID_ARGS' }); + await assert.rejects(changePlugin('add', name, env), { code: 'INVALID_ARGS' }); } fs.writeFileSync( path.join(home, 'config.json'), JSON.stringify({ plugins: { one: { installation: '../other' } } }), ); assert.equal((await listPlugins(env, []))[0]?.compatible, false); - await changePlugin('remove', 'one', env, []); + await changePlugin('remove', 'one', env); assert.deepEqual(await listPlugins(env, []), []); fs.writeFileSync( path.join(home, 'config.json'), JSON.stringify({ plugins: { UPPERCASE: null } }), ); - await changePlugin('remove', 'UPPERCASE', env, []); + await changePlugin('remove', 'UPPERCASE', env); assert.deepEqual(await listPlugins(env, []), []); assert.equal(vi.mocked(runCmd).mock.calls.length, 0); }); -test('provider collisions refuse activation and preserve existing selections', async () => { - const { env } = pluginHome(); - installFixture(); - await assert.rejects(changePlugin('add', packageName, env, ['example']), { - code: 'INVALID_ARGS', - }); - assert.deepEqual(installedPlugins(env), []); - await changePlugin('add', packageName, env, []); - installFixture('other'); - await assert.rejects(changePlugin('add', 'other', env, []), { code: 'INVALID_ARGS' }); - assert.equal(installedPlugins(env).length, 1); +test('a duplicate provider id is settled by the registry when the store composes', async () => { + const { home, env } = pluginHome(); + selectV2Plugin(home, 'first', v2RegistrationSource('example')); + selectV2Plugin(home, 'second', v2RegistrationSource('example')); + const listed = await listPlugins(env, []); + assert.deepEqual( + listed.map(({ name, compatible, error }) => [name, compatible, error?.reason]), + [ + ['first', true, undefined], + ['second', false, 'duplicate_provider'], + ], + ); + // A dormant built-in claims the id first, so a store package cannot take it either. + const { home: otherHome, env: otherEnv } = pluginHome(); + selectV2Plugin(otherHome, 'limrun-plugin', v2RegistrationSource('limrun')); + const limrun = await listPlugins(otherEnv, ['limrun']); + assert.deepEqual( + limrun.map(({ name, compatible, error }) => [name, compatible, error?.reason]), + [['limrun-plugin', false, 'duplicate_provider']], + ); }); test('broken siblings do not block pinned updates or unrelated additions', async () => { - for (const damage of ['missing', 'json', 'abi']) { + for (const damage of ['missing', 'json', 'load']) { const { home, env } = pluginHome(); installFixture(); - await changePlugin('add', `${packageName}@1.2.3`, env, []); - selectPlugin(home, 'broken', 'broken', 'throw new Error("must not evaluate");', 2); + await changePlugin('add', `${packageName}@1.2.3`, env); + selectV2Plugin(home, 'broken', 'throw new Error("must not evaluate");'); const config = readPluginConfig(env); config.plugins![packageName]!.options = { region: 'eu' }; fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify(config)); @@ -161,13 +236,13 @@ test('broken siblings do not block pinned updates or unrelated additions', async if (damage === 'missing') fs.rmSync(directory, { recursive: true }); if (damage === 'json') fs.writeFileSync(path.join(directory, 'node_modules/broken/package.json'), '{'); - await changePlugin('update', packageName, env, []); + await changePlugin('update', packageName, env); const repaired = readPluginConfig(env).plugins![packageName]!; assert.deepEqual(repaired.options, { region: 'eu' }); assert.equal(repaired.version, '1.2.3'); assert.deepEqual(readPluginConfig(env).plugins!.broken, config.plugins!.broken); - installFixture('other', 1, 'other'); - await changePlugin('add', 'other', env, []); + installFixture('other', 'other'); + await changePlugin('add', 'other', env); const listed = await listPlugins(env, []); assert.deepEqual( listed.map(({ name, compatible }) => [name, compatible]), @@ -180,27 +255,175 @@ test('broken siblings do not block pinned updates or unrelated additions', async } }); -test('a package that declares the v1 manifest and exports ./agent-device still supplies its manifest', () => { +test('a fixed daemon detects replacement of a selected replay installation without importing it', async () => { + const { home, env } = pluginHome(); + const name = '@agent-device/replay'; + selectV2Plugin(home, name, 'throw new Error("selection checks must not import this package");'); + const guard = createPluginSelectionGuard(await storePluginCandidates(env), env); + assert.doesNotThrow(() => guard(name)); + selectV2Plugin(home, '@example/unrelated', 'throw new Error("unrelated");'); + assert.doesNotThrow(() => guard(name)); + selectV2Plugin(home, name, 'throw new Error("replacement, same npm version");'); + assert.throws( + () => guard(name), + (error: unknown) => { + assert.equal( + (error as { details?: { reason?: string } }).details?.reason, + 'daemon-plugin-set-stale', + ); + return true; + }, + ); +}); + +test('a null replay selection is invalid configuration rather than an absent package', () => { const { home, env } = pluginHome(); - const directory = selectV2Plugin(home, 'dual', v2RegistrationSource('dual'), { - manifest: { - agentDevicePlugin: { - apiVersion: 1, - provider: 'dual', - entry: './plugin.mjs', - credentialVariables: ['DUAL_KEY'], - }, + fs.writeFileSync( + path.join(home, 'config.json'), + JSON.stringify({ plugins: { '@agent-device/replay': null } }), + ); + const guard = createPluginSelectionGuard([], env); + assert.throws( + () => guard('@agent-device/replay'), + (error: unknown) => { + assert.equal((error as { details?: { reason?: string } }).details?.reason, 'invalid_plugin'); + return true; }, + ); +}); + +test('equivalent nested option key order keeps the daemon selection current', async () => { + const { home, env } = pluginHome(); + const name = '@agent-device/replay'; + selectV2Plugin(home, name, 'throw new Error("must not import");'); + const config = readPluginConfig(env); + const selection = config.plugins[name]; + selection.options = { region: 'eu', nested: { retries: 2, labels: ['a', 'b'] } }; + fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify(config)); + const guard = createPluginSelectionGuard(await storePluginCandidates(env), env); + config.plugins[name] = { + options: { nested: { labels: ['a', 'b'], retries: 2 }, region: 'eu' }, + installation: selection.installation, + }; + fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify(config, null, 2)); + assert.doesNotThrow(() => guard(name)); + config.plugins[name].options.nested.labels.reverse(); + fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify(config)); + assert.throws( + () => guard(name), + (error: unknown) => { + assert.equal( + (error as { details?: { reason?: string } }).details?.reason, + 'daemon-plugin-set-stale', + ); + return true; + }, + ); +}); + +test.each([ + ['1.2.3-01', false], + ['1.2.3-rc.01', false], + ['1.2.3-00', false], + ['1.2.3-0', true], + ['1.2.3-01a', true], + ['1.2.3-1a.0+001', true], + ['1.2.3+01', true], +] as const)('artifact selection validates exact SemVer %s', async (version, valid) => { + const { home, env } = pluginHome(); + selectV2Plugin(home, 'example', v2RegistrationSource('example'), { manifest: { version } }); + const config = readPluginConfig(env); + config.plugins.example.artifact = { + version, + integrity: `sha512-${Buffer.alloc(64).toString('base64')}`, + }; + fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify(config)); + const [entry] = await listPlugins(env, []); + assert.equal(entry?.compatible, valid); + if (valid) assert.equal(entry?.version, version); + assert.equal(vi.mocked(runCmd).mock.calls.length, 0); +}); + +test('registry staging cleanup failure reports both errors and releases the store lock', async () => { + const { home, env } = pluginHome(); + const plugins = path.join(fs.realpathSync(home), 'plugins'); + const installError = new AppError('INVALID_ARGS', 'registry install failed'); + const cleanupError = new Error('registry cleanup failed'); + vi.mocked(runCmd).mockRejectedValue(installError); + const rm = fs.rmSync.bind(fs); + const spy = vi.spyOn(fs, 'rmSync').mockImplementation((target, options) => { + if (typeof target === 'string' && path.dirname(target) === plugins) throw cleanupError; + return rm(target, options); }); - selectV2Plugin(home, 'v2-only', v2RegistrationSource('v2-only')); - assert.deepEqual( - legacyStoreManifests(env).map((manifest) => manifest.agentDevicePlugin.credentialVariables), - [['DUAL_KEY']], + let failure: unknown; + try { + await changePlugin('add', packageName, env); + } catch (error) { + failure = error; + } finally { + spy.mockRestore(); + } + const attempt = tryAcquireProcessLock({ + lockDirPath: path.join(fs.realpathSync(home), 'plugins.lock'), + owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() }, + }); + if (attempt.status === 'acquired') await attempt.acquisition.release(); + assert.equal(attempt.status, 'acquired'); + assert.ok(failure instanceof AppError); + assert.equal(failure.code, 'COMMAND_FAILED'); + assert.ok(failure.details); + assert.equal(failure.details.reason, 'plugin_cleanup_failed'); + assert.equal( + (failure.details.installationError as { message: string }).message, + installError.message, ); + assert.equal((failure.details.cleanupError as { message: string }).message, cleanupError.message); + assert.equal(failure.cause, installError); +}); - // An installation that holds another package supplies nothing under this selection's name. - const manifestPath = path.join(directory, 'package.json'); - const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); - fs.writeFileSync(manifestPath, JSON.stringify({ ...manifest, name: 'someone-else' })); - assert.deepEqual(legacyStoreManifests(env), []); +test('removal does not create or remove a staging project', async () => { + const { home, env } = pluginHome(); + selectV2Plugin(home, 'example', v2RegistrationSource('example')); + const before = fs.readdirSync(path.join(home, 'plugins')); + const spy = vi.spyOn(fs, 'rmSync'); + try { + await changePlugin('remove', 'example', env); + assert.deepEqual(fs.readdirSync(path.join(home, 'plugins')), before); + assert.equal( + spy.mock.calls.filter( + ([target]) => + typeof target === 'string' && + path.dirname(target) === path.join(fs.realpathSync(home), 'plugins'), + ).length, + 0, + ); + assert.deepEqual(readPluginConfig(env).plugins, {}); + } finally { + spy.mockRestore(); + } +}); + +test('a release failure after publication preserves the selected installation', async () => { + const { home, env } = pluginHome(); + installFixture(); + const lock = path.join(fs.realpathSync(home), 'plugins.lock'); + const rmdir = fs.rmdirSync.bind(fs); + const spy = vi.spyOn(fs, 'rmdirSync').mockImplementation((target, options) => { + if (target === lock) throw new Error('release failed'); + return rmdir(target, options); + }); + try { + await assert.rejects( + changePlugin('add', packageName, env), + (error: unknown) => + error instanceof AppError && + error.code === 'COMMAND_FAILED' && + error.details?.ownerReleaseUnverified === true, + ); + const [selected] = installedPlugins(env); + assert.ok(selected); + assert.ok(fs.existsSync(path.join(selected.directory, 'package.json'))); + } finally { + spy.mockRestore(); + } }); diff --git a/packages/plugins/src/store.ts b/packages/plugins/src/store.ts index db1dcd0af3..0e9aac6e2b 100644 --- a/packages/plugins/src/store.ts +++ b/packages/plugins/src/store.ts @@ -1,37 +1,138 @@ -import { - legacyStoreManifests, - readPluginConfig, - validatePluginSelection, - storeHome, - installationDirectory, - isVersionSelector, - type PluginSelection, -} from './store-legacy.ts'; import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { isRecord } from '@agent-device/kernel/record'; -import { AppError } from '@agent-device/kernel/errors'; +import { canonicalJson } from '@agent-device/kernel/collections'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { runCmd } from '@agent-device/host-kit/command'; import { acquireProcessLock, publishFileSync, resolveUserConfigPath, + withProcessLock, } from '@agent-device/host-kit/file'; import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; -import type { PluginPackageEntry } from './discovery.ts'; -import { ROUTING_PROVIDER_IDENTITIES, type PluginManifest } from './manifest.ts'; import type { PluginCandidate } from './registry.ts'; -export { legacyStoreManifests }; +export type PluginSelection = { + installation: string; + version?: string; + options?: Record; + artifact?: { integrity: string; version: string }; +}; +type PluginConfig = Record & { plugins?: Record }; + +function readPluginConfig(env: NodeJS.ProcessEnv): PluginConfig { + const configPath = resolveUserConfigPath(env); + try { + const config = JSON.parse(fs.readFileSync(configPath, 'utf8')) as PluginConfig; + if (!isRecord(config) || (config.plugins !== undefined && !isRecord(config.plugins))) + throw new AppError('INVALID_ARGS', 'Plugin config must contain an object'); + return config; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {}; + if (error instanceof SyntaxError) + throw new AppError('INVALID_ARGS', `Invalid plugin JSON: ${configPath}`, {}, error); + throw error; + } +} + +function validatePluginSelection(name: string, selection: PluginSelection): void { + if ( + !isPackageName(name) || + !isRecord(selection) || + typeof selection.installation !== 'string' || + !/^[a-f0-9-]{36}$/.test(selection.installation) || + (selection.version !== undefined && !isVersionSelector(selection.version)) || + (selection.options !== undefined && !isRecord(selection.options)) || + (selection.artifact !== undefined && + (!isRecord(selection.artifact) || + typeof selection.artifact.integrity !== 'string' || + !/^sha512-[A-Za-z0-9+/]{86}==$/.test(selection.artifact.integrity) || + !isExactVersion(selection.artifact.version))) + ) { + throw new AppError('INVALID_ARGS', `Invalid plugin selection: ${name}`); + } +} + +function selectionStamp(selection: PluginSelection | undefined): string { + return crypto + .createHash('sha256') + .update(canonicalJson(selection ?? null)) + .digest('hex'); +} + +/** Checks a daemon's fixed store selection without importing or replacing executable code. */ +export function createPluginSelectionGuard( + candidates: readonly PluginCandidate[], + env: NodeJS.ProcessEnv, +): (packageName: string) => void { + const selected = new Map( + candidates.flatMap((candidate) => + candidate.package ? [[candidate.package, candidate.selectionStamp] as const] : [], + ), + ); + return (packageName) => { + let current: PluginSelection | undefined; + try { + current = readPluginConfig(env).plugins?.[packageName]; + if (current !== undefined) validatePluginSelection(packageName, current); + } catch (error) { + throw new AppError( + 'INVALID_ARGS', + 'Cannot read the selected replay plugin configuration', + { + reason: 'invalid_plugin', + package: packageName, + hint: 'Repair the plugin configuration on the daemon host, then restart it after finishing your sessions.', + }, + error, + ); + } + if ((selected.get(packageName) ?? selectionStamp(undefined)) !== selectionStamp(current)) + throw new AppError('INVALID_ARGS', 'The running daemon retains an older plugin set.', { + reason: 'daemon-plugin-set-stale', + package: packageName, + hint: 'Finish your sessions and restart the daemon on its host, then retry the original invocation with all its arguments.', + }); + }; +} + +function storeHome(env: NodeJS.ProcessEnv): string { + return path.dirname(resolveUserConfigPath(env)); +} + +function installationDirectory(home: string, name: string, installation: string): string { + return path.join(home, 'plugins', installation, 'node_modules', name); +} + +function isPackageName(value: string): boolean { + return /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(value); +} + +function isVersionSelector(value: unknown): value is string { + return ( + typeof value === 'string' && /^[a-zA-Z0-9*^~<>=| .+-]+$/.test(value) && value.trim().length > 0 + ); +} + +function isExactVersion(value: unknown): value is string { + if (typeof value !== 'string') return false; + const match = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec( + value, + ); + if (!match) return false; + return match[4]?.split('.').every((identifier) => !/^0\d+$/.test(identifier)) ?? true; +} type StoreInstallation = { name: string; version: string; directory: string; selection: PluginSelection; - entry: PluginPackageEntry; + entry: string; }; async function describeInstallation( @@ -49,6 +150,15 @@ async function describeInstallation( reason: 'invalid_plugin', }); } + if ( + selection.artifact && + (version !== selection.artifact.version || + !isRecord(packageJson.exports) || + !Object.hasOwn(packageJson.exports, './agent-device')) + ) + throw new AppError('INVALID_ARGS', `Invalid artifact plugin metadata: ${name}`, { + reason: 'invalid_plugin', + }); return { name, version, directory, selection, entry: discoverPluginEntry(directory) }; } @@ -61,12 +171,8 @@ async function readInstallation(home: string, name: string, selection: PluginSel ); } -async function loadInstallation({ name, directory, selection, entry }: StoreInstallation) { - if (entry.kind === 'v1') { - const { adaptLegacyPlugin } = await import('./legacy.ts'); - return adaptLegacyPlugin(entry.manifest, directory, selection.options); - } - const module = await import(pathToFileURL(entry.file).href); +async function loadInstallation({ name, entry, selection }: StoreInstallation) { + const module = await import(pathToFileURL(entry).href); if (typeof module.default !== 'function') throw new AppError('INVALID_ARGS', `Plugin must export a default factory: ${name}`, { reason: 'invalid_plugin', @@ -77,28 +183,34 @@ async function loadInstallation({ name, directory, selection, entry }: StoreInst /** * The store's contribution to the provider registry, in package-name order. Nothing here runs * plugin code: a selection or package that cannot be read becomes a candidate that fails when - * loaded, so one damaged installation never hides the others. + * loaded, so one damaged installation never hides the others. A store package names its provider + * only once its factory runs, and the registry settles a duplicate then. */ export async function storePluginCandidates(env: NodeJS.ProcessEnv): Promise { + return (await readPluginSnapshot(env)).candidates; +} + +async function readPluginSnapshot(env: NodeJS.ProcessEnv): Promise<{ + candidates: PluginCandidate[]; + selections: Record; +}> { const home = storeHome(env); let selections: [string, PluginSelection][]; try { selections = Object.entries(readPluginConfig(env).plugins ?? {}); } catch (error) { - return [{ source: 'store', load: () => Promise.reject(error) }]; + return { candidates: [{ source: 'store', load: () => Promise.reject(error) }], selections: {} }; } const ordered = selections.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)); - return await Promise.all( + const candidates = await Promise.all( ordered.map(async ([name, selection]): Promise => { try { const installation = await readInstallation(home, name, selection); return { source: 'store', package: name, + selectionStamp: selectionStamp(selection), version: installation.version, - ...(installation.entry.kind === 'v1' - ? { provider: installation.entry.manifest.agentDevicePlugin.provider } - : {}), ...(selection.options ? { hostOptions: selection.options } : {}), load: () => loadInstallation(installation), }; @@ -106,12 +218,14 @@ export async function storePluginCandidates(env: NodeJS.ProcessEnv): Promise Promise.reject(error), }; } }), ); + return { candidates, selections: Object.fromEntries(ordered) }; } // Only a selection that passed validation names a directory this process may read. @@ -134,14 +248,22 @@ async function readSelectionVersion( export async function listPlugins(env: NodeJS.ProcessEnv, builtinProviders: readonly string[]) { const { claimProviderIds, resolveProviderPlugins } = await import('./registry.ts'); + const { candidates, selections } = await readPluginSnapshot(env); const resolved = await resolveProviderPlugins([ ...claimProviderIds(builtinProviders), - ...(await storePluginCandidates(env)), + ...candidates, ]); return resolved.inventory().map((entry) => ({ name: entry.package, + ...(entry.package && selections[entry.package]?.artifact + ? { + installation: selections[entry.package]!.installation, + integrity: selections[entry.package]!.artifact!.integrity, + } + : {}), ...(entry.version !== undefined ? { version: entry.version } : {}), ...(entry.provider !== undefined ? { provider: entry.provider } : {}), + ...(entry.backend !== undefined ? { backend: entry.backend } : {}), compatible: entry.state === 'active', ...(entry.error ? { error: entry.error } : {}), })); @@ -164,118 +286,210 @@ function parsePluginRequest(action: PluginAction, input: string) { return { name: match[1], version: match[2] }; } +async function installInProject(project: string, env: NodeJS.ProcessEnv, artifact?: string) { + await runCmd( + 'npm', + [ + 'install', + '--ignore-scripts', + '--no-audit', + '--no-fund', + '--global=false', + '--prefix', + project, + '--workspaces=false', + '--package-lock=true', + ...(artifact ? ['--', artifact] : []), + ], + { cwd: project, env, timeoutMs: 120_000 }, + ); +} + +type PluginStage = { home: string; installation: string; project: string }; +type SelectionMutation = + | { + kind: 'install'; + apply: (selections: Record, stage: PluginStage) => Promise; + } + | { kind: 'remove'; apply: (selections: Record) => Promise }; + +async function transactSelection( + env: NodeJS.ProcessEnv, + mutation: SelectionMutation, +): Promise { + const configPath = resolveUserConfigPath(env); + fs.mkdirSync(path.dirname(configPath), { recursive: true, mode: 0o700 }); + const home = fs.realpathSync(path.dirname(configPath)); + return withProcessLock({ + acquire: () => + acquireProcessLock({ + lockDirPath: path.join(home, 'plugins.lock'), + owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() }, + description: 'plugin installation', + }), + task: async () => { + const config = readPluginConfig(env); + const selections = { ...config.plugins }; + let stage: PluginStage | undefined; + try { + let result: T; + if (mutation.kind === 'install') { + const installation = crypto.randomUUID(); + stage = { home, installation, project: path.join(home, 'plugins', installation) }; + result = await mutation.apply(selections, stage); + } else { + result = await mutation.apply(selections); + } + publishFileSync({ + destination: configPath, + contents: `${JSON.stringify({ ...config, plugins: selections }, null, 2)}\n`, + mode: 0o600, + }); + return result; + } catch (error) { + if (stage) { + try { + fs.rmSync(stage.project, { recursive: true, force: true }); + } catch (cleanupError) { + throw new AppError( + 'COMMAND_FAILED', + 'Plugin installation and staging cleanup failed', + { + reason: 'plugin_cleanup_failed', + installationError: normalizeError(error), + cleanupError: normalizeError(cleanupError), + }, + error, + ); + } + } + throw error; + } + }, + }); +} + async function stagePlugin( - home: string, + stage: PluginStage, name: string, version: string | undefined, env: NodeJS.ProcessEnv, ) { - const installation = crypto.randomUUID(); - const project = path.join(home, 'plugins', installation); - fs.mkdirSync(project, { recursive: true, mode: 0o700 }); - try { - fs.writeFileSync( - path.join(project, 'package.json'), - JSON.stringify({ private: true, dependencies: { [name]: version ?? 'latest' } }), - ); - await runCmd( - 'npm', - [ - 'install', - '--ignore-scripts', - '--no-audit', - '--no-fund', - '--global=false', - '--prefix', - project, - '--workspaces=false', - '--package-lock=true', - ], - { cwd: project, env, timeoutMs: 120_000 }, - ); - const staged = await describeInstallation( - name, - installationDirectory(home, name, installation), - { - installation, - }, - ); - return { installation, project, entry: staged.entry }; - } catch (error) { - fs.rmSync(project, { recursive: true, force: true }); - throw error; - } + fs.mkdirSync(stage.project, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + path.join(stage.project, 'package.json'), + JSON.stringify({ private: true, dependencies: { [name]: version ?? 'latest' } }), + ); + await installInProject(stage.project, env); + await describeInstallation(name, installationDirectory(stage.home, name, stage.installation), { + installation: stage.installation, + }); } +/** + * Installs, updates or removes one plugin selection. Install checks the staged package's identity + * and version and resolves its entry to a readable file; the factory first runs when the daemon next + * composes its plugins. A provider-id clash with another plugin or a built-in is the registry's to + * settle then, by first claim. + */ export async function changePlugin( action: PluginAction, input: string, env: NodeJS.ProcessEnv, - reservedProviders: readonly string[], ): Promise { const { name, version } = parsePluginRequest(action, input); - const configPath = resolveUserConfigPath(env); - const home = path.dirname(configPath); - fs.mkdirSync(home, { recursive: true, mode: 0o700 }); - const release = await acquireProcessLock({ - lockDirPath: path.join(home, 'plugins.lock'), - owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() }, - description: 'plugin installation', - }); - let staged: Awaited> | undefined; - try { - const config = readPluginConfig(env); - const selections = { ...config.plugins }; - const previous = Object.hasOwn(selections, name) ? selections[name] : undefined; - if (action !== 'add' && !Object.hasOwn(selections, name)) - throw new AppError('INVALID_ARGS', `Plugin is not installed: ${name}`); - if (action === 'remove') delete selections[name]; - else { + if (action === 'remove') { + await transactSelection(env, { + kind: 'remove', + apply: async (selections) => { + if (!Object.hasOwn(selections, name)) + throw new AppError('INVALID_ARGS', `Plugin is not installed: ${name}`); + delete selections[name]; + }, + }); + return; + } + await transactSelection(env, { + kind: 'install', + apply: async (selections, stage) => { + const previous = Object.hasOwn(selections, name) ? selections[name] : undefined; + if (action === 'update' && !Object.hasOwn(selections, name)) + throw new AppError('INVALID_ARGS', `Plugin is not installed: ${name}`); + if (previous?.artifact) + throw new AppError( + 'INVALID_ARGS', + `Artifact plugin cannot be updated from the registry: ${name}`, + { reason: 'artifact_update_requires_remove' }, + ); const requested = action === 'update' && isVersionSelector(previous?.version) ? previous.version : version; - staged = await stagePlugin(home, name, requested, env); - assertUniqueLegacyProviders( - [ - ...legacyStoreManifests(env).filter((manifest) => manifest.name !== name), - ...(staged.entry.kind === 'v1' ? [staged.entry.manifest] : []), - ], - reservedProviders, - ); + await stagePlugin(stage, name, requested, env); selections[name] = { - installation: staged.installation, + installation: stage.installation, version: requested, ...(isRecord(previous?.options) ? { options: previous.options } : {}), }; - } - publishFileSync({ - destination: configPath, - contents: `${JSON.stringify({ ...config, plugins: selections }, null, 2)}\n`, - mode: 0o600, - }); - } catch (error) { - if (staged) fs.rmSync(staged.project, { recursive: true, force: true }); - throw error; - } finally { - await release(); - } + }, + }); } -// A v1 manifest names its provider before any code runs, so a clash is refused at install time. A -// v2 package names its provider only once loaded; the registry records a clash then. -function assertUniqueLegacyProviders( - manifests: readonly PluginManifest[], - reserved: readonly string[], -): void { - const providers = new Set([...ROUTING_PROVIDER_IDENTITIES, ...reserved]); - for (const { agentDevicePlugin } of manifests) { - if (providers.has(agentDevicePlugin.provider)) - throw new AppError( - 'INVALID_ARGS', - `Duplicate provider plugin: ${agentDevicePlugin.provider}`, - { - reason: 'duplicate_provider', - }, - ); - providers.add(agentDevicePlugin.provider); - } +/** Install immutable local package bytes through the managed store. */ +export async function addPluginArtifact( + input: string, + host: { env: Record; cwd: string }, +): Promise<{ name: string; version: string; installation: string; integrity: string }> { + if (!input.endsWith('.tgz') || !path.isAbsolute(host.cwd)) + throw new AppError('INVALID_ARGS', 'Expected a local .tgz path and an absolute host cwd'); + const bytes = fs.readFileSync(path.resolve(host.cwd, input)); + const integrity = `sha512-${crypto.createHash('sha512').update(bytes).digest('base64')}`; + return transactSelection(host.env, { + kind: 'install', + apply: async (selections, { home, installation, project }) => { + fs.mkdirSync(project, { recursive: true, mode: 0o700 }); + const artifact = path.join(project, 'artifact.tgz'); + fs.writeFileSync(artifact, bytes, { mode: 0o600, flag: 'wx' }); + fs.writeFileSync(path.join(project, 'package.json'), JSON.stringify({ private: true })); + await installInProject(project, host.env, artifact); + const lock = JSON.parse(fs.readFileSync(path.join(project, 'package-lock.json'), 'utf8')); + const names = Object.keys(lock.packages?.['']?.dependencies ?? {}); + if (names.length !== 1 || !isPackageName(names[0]!)) + throw new AppError('INVALID_ARGS', 'Artifact has an invalid package name', { + reason: 'invalid_plugin', + }); + const name = names[0]!; + if (lock.packages?.[`node_modules/${name}`]?.integrity !== integrity) + throw new AppError('INVALID_ARGS', 'Artifact contents changed during installation', { + reason: 'artifact_integrity_mismatch', + }); + const directory = installationDirectory(home, name, installation); + const root = fs.realpathSync(project); + const actualDirectory = fs.realpathSync(directory); + if (!actualDirectory.startsWith(`${root}${path.sep}`)) + throw new AppError('INVALID_ARGS', 'Artifact package escaped its installation', { + reason: 'invalid_plugin', + }); + const manifestPath = fs.realpathSync(path.join(directory, 'package.json')); + if (!manifestPath.startsWith(`${actualDirectory}${path.sep}`)) + throw new AppError('INVALID_ARGS', 'Artifact manifest escaped its package', { + reason: 'invalid_plugin', + }); + const { readPackageJson } = await import('./discovery.ts'); + const manifest = readPackageJson(directory); + if (manifest.name !== name || !isExactVersion(manifest.version)) + throw new AppError('INVALID_ARGS', `Invalid artifact package identity: ${name}`, { + reason: 'invalid_plugin', + }); + const selection: PluginSelection = { + installation, + artifact: { integrity, version: manifest.version }, + }; + await describeInstallation(name, directory, selection); + if (Object.hasOwn(selections, name)) + throw new AppError('INVALID_ARGS', `Plugin is already installed: ${name}`, { + reason: 'plugin_already_installed', + }); + selections[name] = selection; + return { name, version: manifest.version, installation, integrity }; + }, + }); } diff --git a/packages/plugins/src/validate.ts b/packages/plugins/src/validate.ts index 9c573d495a..cc776900c6 100644 --- a/packages/plugins/src/validate.ts +++ b/packages/plugins/src/validate.ts @@ -1,15 +1,20 @@ +import { NATIVE_REPLAY_BACKEND } from '@agent-device/contracts/replay-execution'; +import type { ReplayExecution } from '@agent-device/contracts/replay-execution'; +import type { ReplayBackend } from '@agent-device/contracts/replay-backend'; +import type { ReplayEnginePlugin, ReplayEngineSetup } from './replay-backend.ts'; import { AppError } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import { isProviderId } from './discovery.ts'; -import { - assertCredentialVariables, - assertLocalConnectionCapabilities, - ROUTING_PROVIDER_IDENTITIES, -} from './manifest.ts'; import type { ConnectionProviderCapabilities } from '@agent-device/contracts/remote'; import type { ProviderDeviceRuntime } from '@agent-device/contracts/device'; import type { PlatformRuntimeProviderModule } from '@agent-device/contracts/platform-runtime-operations'; -import { PROVIDER_PLUGIN_API_VERSION, type AgentDevicePlugin } from './contract.ts'; +import { + PROVIDER_PLUGIN_API_VERSION, + ROUTING_PROVIDER_IDENTITIES, + type AgentDevicePlugin, +} from './contract.ts'; + +const ENVIRONMENT_VARIABLE = /^[A-Z_][A-Z0-9_]*$/; /** The one validation of what a plugin factory returned, whichever source produced it. */ export function validateAgentDevicePlugin(value: unknown): AgentDevicePlugin { @@ -53,6 +58,15 @@ function assertCredentials(credentials: unknown): void { } } +function assertCredentialVariables(variables: unknown): void { + if ( + !Array.isArray(variables) || + !variables.every((name) => typeof name === 'string' && ENVIRONMENT_VARIABLE.test(name)) + ) { + throw invalidPlugin('Plugin credential variables must list environment variable names'); + } +} + function assertConnection(connection: unknown): void { if ( !isRecord(connection) || @@ -65,6 +79,31 @@ function assertConnection(connection: unknown): void { assertLocalConnectionCapabilities(connection.capabilities as ConnectionProviderCapabilities); } +function assertLocalConnectionCapabilities( + policy: ConnectionProviderCapabilities | undefined, +): void { + if (policy === undefined) return; + if ( + !policy || + typeof policy !== 'object' || + policy.leaseKind !== 'direct-device-provider' || + [ + 'requiresAppAttachment', + 'requiresRemoteDaemon', + 'supportsArtifacts', + 'supportsDeferredAppSelection', + 'supportsDirectPortReverse', + 'usesCloudWebDriverLease', + ].some((key) => typeof policy[key as keyof ConnectionProviderCapabilities] !== 'boolean') || + (policy.holdsCloudDevice !== undefined && typeof policy.holdsCloudDevice !== 'boolean') || + (policy.forgetsEndedConnectionLease !== undefined && + typeof policy.forgetsEndedConnectionLease !== 'boolean') || + policy.requiresRemoteDaemon + ) { + throw invalidPlugin('Plugin connection must declare local provider capabilities'); + } +} + /** The runtime a plugin built must answer to the provider id it registered. */ export function assertProviderRuntime( provider: string, @@ -99,3 +138,67 @@ function hasProviderFacets(runtime: ProviderDeviceRuntime): boolean { export function invalidPlugin(message: string): AppError { return new AppError('INVALID_ARGS', message, { reason: 'invalid_plugin' }); } + +export function validateReplayEnginePlugin(value: unknown): ReplayEnginePlugin { + if (!isRecord(value) || value.kind !== 'replay-backend') + throw invalidPlugin('Plugin must declare kind: replay-backend'); + if (value.apiVersion !== 2) + throw new AppError('INVALID_ARGS', 'Replay plugin requires apiVersion 2', { + reason: 'incompatible_plugin', + apiVersion: 2, + }); + if ( + value.provider !== undefined || + value.connection !== undefined || + value.credentials !== undefined + ) + throw invalidPlugin( + 'Replay plugins cannot declare provider identity, connection or credentials', + ); + if (!isProviderId(value.backend) || typeof value.setup !== 'function') + throw invalidPlugin('Replay plugin must declare a backend id and setup(host)'); + return value as ReplayEnginePlugin; +} + +export function validateReplayEngineSetup( + value: unknown, + backend: TBackend, +): ReplayEngineSetup { + if (!isRecord(value) || (value.dispose !== undefined && typeof value.dispose !== 'function')) + throw invalidPlugin('Replay plugin setup must provide a factory and optional dispose()'); + const native = backend === NATIVE_REPLAY_BACKEND; + const factory = native ? value.execution : value.replayBackend; + const other = native ? value.replayBackend : value.execution; + if (other !== undefined || !isRecord(factory) || typeof factory.create !== 'function') + throw invalidPlugin( + native + ? 'Native ad backend setup must provide execution.create()' + : 'Format backend setup must provide replayBackend.create(host)', + ); + return value as ReplayEngineSetup; +} + +export function validateReplayExecution(value: unknown): ReplayExecution { + if ( + !isRecord(value) || + (['inspectAdReplay', 'runAdReplay', 'runReplayTestSuite'] as const).some( + (name) => typeof value[name] !== 'function', + ) + ) + throw invalidPlugin( + 'Native replay execution must provide inspection, replay and suite execution', + ); + return value as ReplayExecution; +} + +export function validateReplayBackend(id: string, value: unknown): ReplayBackend { + if ( + !isRecord(value) || + value.id !== id || + (['collectSourceFiles', 'inspectSource', 'runReplay', 'exportReplayScript'] as const).some( + (name) => typeof value[name] !== 'function', + ) + ) + throw invalidPlugin(`Replay plugin runtime does not match its backend: ${id}`); + return value as ReplayBackend; +} diff --git a/packages/plugins/tsconfig.json b/packages/plugins/tsconfig.json index 380be0b4f5..4ddd6ceaf5 100644 --- a/packages/plugins/tsconfig.json +++ b/packages/plugins/tsconfig.json @@ -11,9 +11,17 @@ }, "include": ["src"], "references": [ - { "path": "../contracts" }, - { "path": "../host-kit" }, - { "path": "../kernel" }, - { "path": "../test-kit" } + { + "path": "../contracts" + }, + { + "path": "../host-kit" + }, + { + "path": "../kernel" + }, + { + "path": "../test-kit" + } ] } diff --git a/packages/provider-aws-device-farm/README.md b/packages/provider-aws-device-farm/README.md new file mode 100644 index 0000000000..486e47f90f --- /dev/null +++ b/packages/provider-aws-device-farm/README.md @@ -0,0 +1,11 @@ +# AWS Device Farm for agent-device + +Install the plugin on the daemon host. + +```sh +agent-device plugins add @agent-device/aws-device-farm@nightly-0.22 +``` + +Run `agent-device help remote` to see the install command for your CLI. + +Configure AWS CLI credentials and connect using your Device Farm project and device ARNs. See the [AWS Device Farm guide](https://agent-device.dev/docs/aws-device-farm). diff --git a/packages/provider-aws-device-farm/package.json b/packages/provider-aws-device-farm/package.json new file mode 100644 index 0000000000..36308ae133 --- /dev/null +++ b/packages/provider-aws-device-farm/package.json @@ -0,0 +1,60 @@ +{ + "name": "@agent-device/aws-device-farm", + "version": "0.22.0-dev", + "type": "module", + "description": "AWS Device Farm real-device plugin for agent-device.", + "files": [ + "dist" + ], + "scripts": { + "build": "tsdown --config tsdown.config.ts", + "prepack": "pnpm build" + }, + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./agent-device": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./connection-verification": { + "types": "./src/aws-device-farm-connection-verification.ts", + "default": "./src/aws-device-farm-connection-verification.ts" + }, + "./package.json": "./package.json" + }, + "devDependencies": { + "@agent-device/build-config": "workspace:*", + "@agent-device/contracts": "workspace:*", + "@agent-device/kernel": "workspace:*", + "@agent-device/provider-webdriver": "workspace:*", + "agent-device": "workspace:*" + }, + "publishConfig": { + "exports": { + ".": { + "types": "./dist/agent-device.d.mts", + "import": "./dist/agent-device.mjs" + }, + "./agent-device": { + "types": "./dist/agent-device.d.mts", + "import": "./dist/agent-device.mjs" + }, + "./connection-verification": { + "types": "./dist/connection-verification.d.mts", + "import": "./dist/connection-verification.mjs" + }, + "./package.json": "./package.json" + }, + "access": "public" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/callstack/agent-device.git", + "directory": "packages/provider-aws-device-farm" + }, + "homepage": "https://agent-device.dev/docs/aws-device-farm" +} diff --git a/packages/provider-webdriver/src/aws-device-farm-artifacts.ts b/packages/provider-aws-device-farm/src/aws-device-farm-artifacts.ts similarity index 96% rename from packages/provider-webdriver/src/aws-device-farm-artifacts.ts rename to packages/provider-aws-device-farm/src/aws-device-farm-artifacts.ts index 8dbbdacdd3..2d4722a1ca 100644 --- a/packages/provider-webdriver/src/aws-device-farm-artifacts.ts +++ b/packages/provider-aws-device-farm/src/aws-device-farm-artifacts.ts @@ -1,6 +1,6 @@ import type { CloudArtifact, CloudArtifactsResult } from '@agent-device/contracts/observability'; import type { AwsDeviceFarmClient } from './aws-device-farm.ts'; -import { cloudArtifactsReadyOrPending } from './artifact-results.ts'; +import { cloudArtifactsReadyOrPending } from '@agent-device/provider-webdriver/plugin'; export type AwsDeviceFarmArtifactGroup = 'FILE' | 'LOG' | 'SCREENSHOT'; diff --git a/packages/provider-aws-device-farm/src/aws-device-farm-connection-verification.test.ts b/packages/provider-aws-device-farm/src/aws-device-farm-connection-verification.test.ts new file mode 100644 index 0000000000..a7e917dfef --- /dev/null +++ b/packages/provider-aws-device-farm/src/aws-device-farm-connection-verification.test.ts @@ -0,0 +1,115 @@ +import assert from 'node:assert/strict'; +import { afterEach, test, vi } from 'vitest'; +import { verifyAwsDeviceFarmConnection } from './aws-device-farm-connection-verification.ts'; +import type { RunHostCommand } from 'agent-device/plugins'; + +const awsResources = { + project: { arn: 'project-arn', name: 'Agent Device' }, + device: { + arn: 'device-arn', + name: 'Google Pixel 8', + platform: 'ANDROID', + os: '14', + availability: 'HIGHLY_AVAILABLE', + }, + upload: { + arn: 'app-arn', + name: 'sample.apk', + type: 'ANDROID_APP', + status: 'SUCCEEDED', + }, +}; + +afterEach(() => vi.unstubAllGlobals()); + +test('AWS Device Farm verifies resources without creating a remote access session', async () => { + const concurrency = { active: 0, max: 0 }; + const runHostCommand = createAwsRunner(awsResources, concurrency); + const result = await verifyAwsDeviceFarmConnection( + { + platform: 'android', + projectArn: 'project-arn', + deviceArn: 'device-arn', + appArn: 'app-arn', + region: 'us-west-2', + }, + runHostCommand, + ); + + assert.equal(result.provider, 'aws-device-farm'); + if (result.provider !== 'aws-device-farm') return; + assert.deepEqual(result.project, { name: 'Agent Device', reference: 'project-arn' }); + assert.equal(result.device.name, 'Google Pixel 8'); + assert.equal(result.app.name, 'sample.apk'); + assert.deepEqual( + runHostCommand.mock.calls.map(([, args]) => args[1]), + ['get-project', 'get-device', 'get-upload'], + ); + assert.equal( + runHostCommand.mock.calls.some(([, args]) => args.includes('create-remote-access-session')), + false, + ); + assert.equal(concurrency.max, 3); +}); + +test('AWS Device Farm reports an unattached app without pretending it is installed', async () => { + const runHostCommand = createAwsRunner({ + project: awsResources.project, + device: { ...awsResources.device, platform: 'IOS', name: 'iPhone 15', os: '17' }, + }); + const result = await verifyAwsDeviceFarmConnection( + { + platform: 'ios', + projectArn: 'project-arn', + deviceArn: 'device-arn', + }, + runHostCommand, + ); + + assert.equal(result.app.status, 'missing'); + assert.match(result.app.message ?? '', /--aws-app-arn/); + assert.equal(runHostCommand.mock.calls.length, 2); +}); + +test('AWS Device Farm rejects a device from the wrong platform before allocation', async () => { + const runHostCommand = createAwsRunner({ + project: awsResources.project, + device: { ...awsResources.device, platform: 'IOS', name: 'iPhone 15', os: '17' }, + }); + + await assert.rejects( + verifyAwsDeviceFarmConnection( + { + platform: 'android', + projectArn: 'project-arn', + deviceArn: 'device-arn', + }, + runHostCommand, + ), + /is ios, not android/, + ); + assert.equal( + runHostCommand.mock.calls.some(([, args]) => args.includes('create-remote-access-session')), + false, + ); +}); + +function createAwsRunner( + resources: Partial, + concurrency?: { active: number; max: number }, +) { + return vi.fn(async (_command, args) => { + if (concurrency) { + concurrency.active += 1; + concurrency.max = Math.max(concurrency.max, concurrency.active); + } + await Promise.resolve(); + try { + const resource = resources[String(args[1]).replace('get-', '') as keyof typeof awsResources]; + if (!resource) throw new Error(`Unexpected AWS command: ${args[1]}`); + return { stdout: JSON.stringify({ [String(args[1]).replace('get-', '')]: resource }) }; + } finally { + if (concurrency) concurrency.active -= 1; + } + }); +} diff --git a/packages/provider-webdriver/src/aws-device-farm-connection-verification.ts b/packages/provider-aws-device-farm/src/aws-device-farm-connection-verification.ts similarity index 98% rename from packages/provider-webdriver/src/aws-device-farm-connection-verification.ts rename to packages/provider-aws-device-farm/src/aws-device-farm-connection-verification.ts index 899cc7938f..6b5698b4a2 100644 --- a/packages/provider-webdriver/src/aws-device-farm-connection-verification.ts +++ b/packages/provider-aws-device-farm/src/aws-device-farm-connection-verification.ts @@ -1,6 +1,6 @@ import { AppError } from '@agent-device/kernel/errors'; import { createAwsDeviceFarmCommandRunner } from './aws-device-farm.ts'; -import type { RunHostCommand } from './dependencies.ts'; +import type { RunHostCommand } from 'agent-device/plugins'; import type { ProviderConnectionResource, ProviderConnectionVerification, diff --git a/packages/provider-aws-device-farm/src/aws-device-farm-profile-fields.test.ts b/packages/provider-aws-device-farm/src/aws-device-farm-profile-fields.test.ts new file mode 100644 index 0000000000..cb80fdf922 --- /dev/null +++ b/packages/provider-aws-device-farm/src/aws-device-farm-profile-fields.test.ts @@ -0,0 +1,20 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import type { ProviderProfileField } from '@agent-device/contracts/provider-profile-fields'; +import { AWS_DEVICE_FARM_PROFILE_FIELDS } from './profile-fields.ts'; + +test('AWS Device Farm consumes only its own fields and the session name', () => { + assert.deepEqual( + (Object.keys(AWS_DEVICE_FARM_PROFILE_FIELDS.fields) as ProviderProfileField[]) + .filter((field) => AWS_DEVICE_FARM_PROFILE_FIELDS.fields[field] === 'consumed') + .sort(), + [ + 'awsAppArn', + 'awsDeviceArn', + 'awsInteractionMode', + 'awsProjectArn', + 'awsRegion', + 'providerSessionName', + ], + ); +}); diff --git a/packages/provider-webdriver/src/aws-device-farm-provider.ts b/packages/provider-aws-device-farm/src/aws-device-farm-webdriver.ts similarity index 63% rename from packages/provider-webdriver/src/aws-device-farm-provider.ts rename to packages/provider-aws-device-farm/src/aws-device-farm-webdriver.ts index 6938e38afa..e946fd6222 100644 --- a/packages/provider-webdriver/src/aws-device-farm-provider.ts +++ b/packages/provider-aws-device-farm/src/aws-device-farm-webdriver.ts @@ -1,6 +1,12 @@ +import type { ProviderPluginHost } from 'agent-device/plugins'; +import type { WebDriverPluginOptions } from 'agent-device/plugins/webdriver'; +import { + readFlag, + requireRequest, + requireRequestPlatform, +} from '@agent-device/provider-webdriver/plugin'; import { AWS_DEVICE_FARM_CAPABILITY_OVERRIDES, - AWS_DEVICE_FARM_PROFILE_FIELDS, createAwsCliDeviceFarmClient, createAwsDeviceFarmPrepareSession, listAwsDeviceFarmCloudArtifacts, @@ -9,32 +15,20 @@ import { readAwsDeviceFarmSelectorFromEnv, requireAwsDeviceFarmSelector, } from './aws-device-farm.ts'; -import type { - BundledCloudWebDriverProvider, - CloudWebDriverConnection, - CloudWebDriverProviderHost, - CloudWebDriverProviderOptions, - CloudWebDriverProviderRegistration, -} from './provider-plugin.ts'; -import { CLOUD_WEBDRIVER_PROVIDERS, cloudWebDriverProviderDeclaration } from './providers.ts'; -import { readFlag, requireRequest, requireRequestPlatform } from './webdriver-utils.ts'; +import { AWS_DEVICE_FARM_PROFILE_FIELDS } from './profile-fields.ts'; +import { AWS_DEVICE_FARM_PROVIDER } from './providers.ts'; -const PROVIDER = CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm; const SERVICE = 'AWS Device Farm'; -export const awsDeviceFarmProvider: BundledCloudWebDriverProvider = { - declaration: cloudWebDriverProviderDeclaration(PROVIDER)!, - create: createAwsDeviceFarmProvider, -}; - -function createAwsDeviceFarmProvider( - host: CloudWebDriverProviderHost, -): CloudWebDriverProviderRegistration { - const { env, runHostCommand } = host; +/** The AWS Device Farm WebDriver descriptor the host drives through its shared engine. */ +export function createAwsDeviceFarmWebDriver(host: ProviderPluginHost): WebDriverPluginOptions { + const { env } = host; + const runHostCommand = (command: string, args: readonly string[]) => + host.runHostCommand(command, args); const client = (region: string | undefined) => createAwsCliDeviceFarmClient({ runHostCommand, region }); - const webDriver: CloudWebDriverProviderOptions = { - provider: PROVIDER, + const webDriver: WebDriverPluginOptions = { + provider: AWS_DEVICE_FARM_PROVIDER, profileFields: AWS_DEVICE_FARM_PROFILE_FIELDS, endpoint: 'http://127.0.0.1/', platform: 'android', @@ -71,11 +65,5 @@ function createAwsDeviceFarmProvider( })({ lease, req, base }); }, }; - const connect = async () => - (await import('./aws-device-farm-connection.ts')).createAwsDeviceFarmConnection(host); - const connection: CloudWebDriverConnection = { - resolve: async (context) => (await connect()).resolve(context), - verify: async (context) => await (await connect()).verify(context), - }; - return { webDriver, connection }; + return webDriver; } diff --git a/packages/provider-webdriver/src/aws-device-farm.test.ts b/packages/provider-aws-device-farm/src/aws-device-farm.test.ts similarity index 98% rename from packages/provider-webdriver/src/aws-device-farm.test.ts rename to packages/provider-aws-device-farm/src/aws-device-farm.test.ts index 0b80b9cd69..9d6afcb895 100644 --- a/packages/provider-webdriver/src/aws-device-farm.test.ts +++ b/packages/provider-aws-device-farm/src/aws-device-farm.test.ts @@ -11,7 +11,7 @@ import { type AwsDeviceFarmClient, type AwsDeviceFarmRemoteAccessSession, } from './aws-device-farm.ts'; -import { buildCloudWebDriverBaseCapabilities } from './runtime.ts'; +import { buildCloudWebDriverBaseCapabilities } from '@agent-device/provider-webdriver/plugin'; const ARN = 'arn:aws:devicefarm:us-west-2:1:session/pending'; diff --git a/packages/provider-webdriver/src/aws-device-farm.ts b/packages/provider-aws-device-farm/src/aws-device-farm.ts similarity index 89% rename from packages/provider-webdriver/src/aws-device-farm.ts rename to packages/provider-aws-device-farm/src/aws-device-farm.ts index 1f649c1745..c0a9df8774 100644 --- a/packages/provider-webdriver/src/aws-device-farm.ts +++ b/packages/provider-aws-device-farm/src/aws-device-farm.ts @@ -1,48 +1,20 @@ -import type { CloudWebDriverCapabilityOverrides } from './capabilities.ts'; -import { buildCloudWebDriverBaseCapabilities } from './runtime.ts'; +import { + buildCloudWebDriverBaseCapabilities, + releaseOnFailure, + type CloudWebDriverCapabilityOverrides, + type CloudWebDriverPlatform, + type CloudWebDriverPrepareSession, +} from '@agent-device/provider-webdriver/plugin'; import { readAwsArtifacts, type AwsDeviceFarmArtifact, type AwsDeviceFarmArtifactGroup, } from './aws-device-farm-artifacts.ts'; -import type { CloudWebDriverPlatform, CloudWebDriverPrepareSession } from './runtime.ts'; import type { LeaseLifecycleContext } from '@agent-device/contracts/device'; -import type { ProviderProfileFieldDeclaration } from '@agent-device/contracts/provider-profile-fields'; import { PROVIDER_PROFILE_FIELD_FLAGS } from '@agent-device/contracts/remote'; import { setTimeout as sleep } from 'node:timers/promises'; import { AppError } from '@agent-device/kernel/errors'; -import type { RunHostCommand } from './dependencies.ts'; -import { CLOUD_WEBDRIVER_PROVIDERS } from './providers.ts'; -import { releaseOnFailure } from './webdriver-utils.ts'; - -export const AWS_DEVICE_FARM_PROFILE_FIELDS: ProviderProfileFieldDeclaration = { - provider: CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, - label: 'AWS Device Farm', - fields: { - providerApp: 'refused', - providerOsVersion: 'refused', - providerDeviceType: 'refused', - providerProject: 'refused', - providerBuild: 'refused', - providerSessionName: 'consumed', - providerDeviceOrientation: 'refused', - providerGeoLocation: 'refused', - providerTimezone: 'refused', - providerAppiumVersion: 'refused', - providerLanguage: 'refused', - providerLocale: 'refused', - providerNetworkProfile: 'refused', - providerCustomNetwork: 'refused', - providerNoResignApp: 'refused', - providerNetworkLogs: 'refused', - providerNetworkHosts: 'refused', - awsProjectArn: 'consumed', - awsDeviceArn: 'consumed', - awsAppArn: 'consumed', - awsRegion: 'consumed', - awsInteractionMode: 'consumed', - }, -}; +import type { RunHostCommand } from 'agent-device/plugins'; /** Each selector reads its flag first, then the agent-device variable, then the AWS CLI one. */ const AWS_SELECTOR_VARIABLES = { diff --git a/packages/provider-webdriver/src/aws-device-farm-connection.test.ts b/packages/provider-aws-device-farm/src/connection.test.ts similarity index 51% rename from packages/provider-webdriver/src/aws-device-farm-connection.test.ts rename to packages/provider-aws-device-farm/src/connection.test.ts index 9b7c68edb7..d23b97fb5e 100644 --- a/packages/provider-webdriver/src/aws-device-farm-connection.test.ts +++ b/packages/provider-aws-device-farm/src/connection.test.ts @@ -1,12 +1,11 @@ import assert from 'node:assert/strict'; import { afterEach, test, vi } from 'vitest'; +import type { PluginConnectionContext, ProviderPluginHost } from 'agent-device/plugins'; import { AppError } from '@agent-device/kernel/errors'; -import { createAwsDeviceFarmConnection } from './aws-device-farm-connection.ts'; -import { verifyAwsDeviceFarmConnection } from './connection-verification.ts'; -import type { CloudWebDriverProviderHost } from './provider-plugin.ts'; +import { createAwsDeviceFarmConnection } from './connection.ts'; +import { verifyAwsDeviceFarmConnection } from './aws-device-farm-connection-verification.ts'; -vi.mock('./connection-verification.ts', async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('./aws-device-farm-connection-verification.ts', () => ({ verifyAwsDeviceFarmConnection: vi.fn(), })); @@ -23,16 +22,32 @@ const FLAGS = { awsDeviceArn: DEVICE_ARN, }; -function host(env: Record = {}): CloudWebDriverProviderHost { +function host(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 context( + overrides: Partial & { flags?: Record } = {}, +): PluginConnectionContext { + const pluginHost = overrides.host ?? host(); + return { + flags: FLAGS, + stateDir: '/state', + cwd: '/', + env: { ...pluginHost.env }, + host: pluginHost, + ...overrides, + } as PluginConnectionContext; +} + test('connect resolves selectors from flags, then agent-device variables, then AWS variables', async () => { const connection = createAwsDeviceFarmConnection( host({ @@ -41,8 +56,7 @@ test('connect resolves selectors from flags, then agent-device variables, then A AWS_DEFAULT_REGION: 'eu-west-1', }), ); - const { profile, extraFlags } = connection.resolve({ flags: FLAGS, cwd: '/' }); - assert.equal(extraFlags, undefined); + const { profile } = await connection.resolve(context()); assert.deepEqual(profile, { leaseProvider: 'aws-device-farm', platform: 'ios', @@ -55,41 +69,49 @@ test('connect resolves selectors from flags, then agent-device variables, then A providerSessionName: undefined, }); // With no region configured, the project ARN names it. - const fromArn = createAwsDeviceFarmConnection(host()).resolve({ flags: FLAGS, cwd: '/' }); + const fromArn = await createAwsDeviceFarmConnection(host()).resolve(context()); assert.equal(fromArn.profile.awsRegion, 'us-west-2'); }); test('connect names the flag and the AWS variable a missing selector can come from', async () => { const connection = createAwsDeviceFarmConnection(host()); - assert.throws( - () => connection.resolve({ flags: { ...FLAGS, awsDeviceArn: undefined }, cwd: '/' }), + await assert.rejects( + async () => await connection.resolve(context({ flags: { ...FLAGS, awsDeviceArn: undefined } })), { code: 'INVALID_ARGS', message: 'connect aws-device-farm requires --aws-device-arn or AWS_DEVICE_FARM_DEVICE_ARN.', }, ); - assert.throws( - () => connection.resolve({ flags: { ...FLAGS, providerApp: 'app.ipa' }, cwd: '/' }), + await assert.rejects( + async () => await connection.resolve(context({ flags: { ...FLAGS, providerApp: 'app.ipa' } })), (error: unknown) => error instanceof AppError && JSON.stringify(error.details?.flags) === '["--provider-app"]', ); }); -test('verify hands the saved selectors and the host command runner to the verifier', async () => { - const providerHost = host(); +test('verify hands the saved selectors and a host-command runner to the verifier', async () => { + const calls: string[][] = []; + const providerHost = { + ...host(), + runHostCommand: async (command: string, args: readonly string[]) => { + calls.push([command, ...args]); + return { stdout: '{}' }; + }, + }; const connection = createAwsDeviceFarmConnection(providerHost); await connection.verify({ flags: { ...FLAGS, awsRegion: 'us-west-2' } }); - assert.deepEqual(vi.mocked(verifyAwsDeviceFarmConnection).mock.calls[0], [ - { - platform: 'ios', - projectArn: PROJECT_ARN, - deviceArn: DEVICE_ARN, - appArn: undefined, - region: 'us-west-2', - }, - providerHost.runHostCommand, - ]); + const [options, runHostCommand] = vi.mocked(verifyAwsDeviceFarmConnection).mock.calls[0]!; + assert.deepEqual(options, { + platform: 'ios', + projectArn: PROJECT_ARN, + deviceArn: DEVICE_ARN, + appArn: undefined, + region: 'us-west-2', + }); + // The verifier drives the AWS CLI through the host capability, with the plugin host's own bounds. + await runHostCommand('aws', ['devicefarm', 'get-project', '--arn', PROJECT_ARN]); + assert.deepEqual(calls, [['aws', 'devicefarm', 'get-project', '--arn', PROJECT_ARN]]); await assert.rejects(connection.verify({ flags: { ...FLAGS, platform: undefined } }), { code: 'COMMAND_FAILED', message: 'AWS Device Farm profile missed a mobile platform.', diff --git a/packages/provider-webdriver/src/aws-device-farm-connection.ts b/packages/provider-aws-device-farm/src/connection.ts similarity index 71% rename from packages/provider-webdriver/src/aws-device-farm-connection.ts rename to packages/provider-aws-device-farm/src/connection.ts index cddc5725bd..9b9f181c42 100644 --- a/packages/provider-webdriver/src/aws-device-farm-connection.ts +++ b/packages/provider-aws-device-farm/src/connection.ts @@ -1,35 +1,29 @@ +import type { ProviderPluginHost } from 'agent-device/plugins'; +import type { CliFlags } from '@agent-device/contracts/command'; import { rejectRefusedProviderProfileFields, requireResolvedProfilePlatform, requireResolvedProfileValue, } from '@agent-device/contracts/provider-profile-fields'; +import { requireConnectPlatform } from '@agent-device/provider-webdriver/plugin'; import { - AWS_DEVICE_FARM_PROFILE_FIELDS, readAwsDeviceFarmRegionFromArn, readAwsDeviceFarmSelectorFromEnv, requireAwsDeviceFarmSelector, } from './aws-device-farm.ts'; -import { verifyAwsDeviceFarmConnection } from './connection-verification.ts'; -import type { - CloudWebDriverConnection, - CloudWebDriverConnectionContext, - CloudWebDriverConnectProfileResolution, - CloudWebDriverProviderHost, -} from './provider-plugin.ts'; -import { CLOUD_WEBDRIVER_PROVIDERS } from './providers.ts'; -import { requireConnectPlatform } from './webdriver-utils.ts'; +import { AWS_DEVICE_FARM_PROFILE_FIELDS } from './profile-fields.ts'; +import { verifyAwsDeviceFarmConnection } from './aws-device-farm-connection-verification.ts'; +import { AWS_DEVICE_FARM_PROVIDER } from './providers.ts'; -const PROVIDER = CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm; +const PROVIDER = AWS_DEVICE_FARM_PROVIDER; const SERVICE = 'AWS Device Farm'; const CONSUMER = `connect ${PROVIDER}`; /** The `connect aws-device-farm` callbacks, loaded only when the CLI runs them. */ -export function createAwsDeviceFarmConnection(host: CloudWebDriverProviderHost): { - resolve(context: CloudWebDriverConnectionContext): CloudWebDriverConnectProfileResolution; -} & CloudWebDriverConnection { +export function createAwsDeviceFarmConnection(host: ProviderPluginHost) { const { env } = host; return { - resolve: ({ flags }): CloudWebDriverConnectProfileResolution => { + resolve: ({ flags }: { flags: CliFlags; cwd: string }) => { rejectRefusedProviderProfileFields(flags, AWS_DEVICE_FARM_PROFILE_FIELDS); const platform = requireConnectPlatform(flags, PROVIDER); const awsProjectArn = requireAwsDeviceFarmSelector( @@ -60,7 +54,7 @@ export function createAwsDeviceFarmConnection(host: CloudWebDriverProviderHost): }, }; }, - verify: async ({ flags }) => + verify: async ({ flags }: { flags: CliFlags }) => await verifyAwsDeviceFarmConnection( { platform: requireResolvedProfilePlatform(flags.platform, SERVICE), @@ -75,7 +69,8 @@ export function createAwsDeviceFarmConnection(host: CloudWebDriverProviderHost): appArn: flags.awsAppArn, region: flags.awsRegion, }, - host.runHostCommand, + // The plugin drives `aws devicefarm ...` through the host-command capability. + (command, args) => host.runHostCommand(command, args), ), }; } diff --git a/packages/provider-webdriver/src/aws-device-farm-provider.test.ts b/packages/provider-aws-device-farm/src/index.test.ts similarity index 54% rename from packages/provider-webdriver/src/aws-device-farm-provider.test.ts rename to packages/provider-aws-device-farm/src/index.test.ts index dfefb64486..ccba0b59a0 100644 --- a/packages/provider-webdriver/src/aws-device-farm-provider.test.ts +++ b/packages/provider-aws-device-farm/src/index.test.ts @@ -1,30 +1,52 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; +import type { ProviderPluginHost } from 'agent-device/plugins'; +import { AppError } from '@agent-device/kernel/errors'; import type { DeviceLease } from '@agent-device/contracts/device'; -import { awsDeviceFarmProvider } from './aws-device-farm-provider.ts'; -import type { CloudWebDriverProviderHost } from './provider-plugin.ts'; +import awsDeviceFarm from './index.ts'; const DEVICE_ARN = 'arn:aws:devicefarm:us-west-2::device:device-a'; -function host(env: Record = {}): CloudWebDriverProviderHost { +function host(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'); }, }; } -test('the declaration reserves the provider id without environment credentials', () => { - assert.equal(awsDeviceFarmProvider.declaration.provider, 'aws-device-farm'); - assert.equal(awsDeviceFarmProvider.declaration.credentialVariables, undefined); - assert.equal(awsDeviceFarmProvider.declaration.connection.requiresAppAttachment, true); +test('the plugin declares its provider, capabilities, and no credential variables', () => { + const plugin = awsDeviceFarm(); + assert.equal(plugin.apiVersion, 2); + assert.equal(plugin.provider, 'aws-device-farm'); + // The AWS CLI credential chain has no environment fingerprint. + assert.deepEqual(plugin.credentials, { variables: [] }); + assert.deepEqual(plugin.connection?.capabilities, { + leaseKind: 'direct-device-provider', + requiresAppAttachment: true, + requiresRemoteDaemon: false, + supportsArtifacts: true, + supportsDeferredAppSelection: false, + supportsDirectPortReverse: false, + usesCloudWebDriverLease: true, + }); +}); + +test('setup builds a WebDriver descriptor for the shared engine', async () => { + const setup = await awsDeviceFarm().setup(host()); + if (!('webDriver' in setup)) throw new Error('AWS Device Farm sets up a WebDriver descriptor'); + assert.equal(setup.webDriver.provider, 'aws-device-farm'); + assert.equal(setup.webDriver.profileFields.provider, 'aws-device-farm'); }); test('lease preparation reads the connect selectors before any host command runs', async () => { - const { webDriver } = awsDeviceFarmProvider.create(host()); - assert.equal(webDriver.profileFields.provider, 'aws-device-farm'); + const setup = await awsDeviceFarm().setup(host()); + if (!('webDriver' in setup)) throw new Error('AWS Device Farm sets up a WebDriver descriptor'); + const { webDriver } = setup; const lease: DeviceLease = { leaseId: 'lease-aws', tenantId: 'team-a', @@ -56,15 +78,16 @@ test('lease preparation reads the connect selectors before any host command runs test('artifact lookup runs in the region of the session ARN, not the environment region', async () => { const commands: string[][] = []; - const { webDriver } = awsDeviceFarmProvider.create({ + const setup = await awsDeviceFarm().setup({ ...host({ AWS_REGION: 'eu-west-1' }), runHostCommand: async (command, args) => { commands.push([command, ...args]); - return { stdout: '{"artifacts":[]}', stderr: '', exitCode: 0 }; + return { stdout: '{"artifacts":[]}' }; }, }); + if (!('webDriver' in setup)) throw new Error('AWS Device Farm sets up a WebDriver descriptor'); - await webDriver.listArtifacts!({ + await setup.webDriver.listArtifacts!({ provider: 'aws-device-farm', providerSessionId: 'arn:aws:devicefarm:us-west-2:123:session:project-a/session-a/00000', }); @@ -77,7 +100,7 @@ test('artifact lookup runs in the region of the session ARN, not the environment }); test('the factory connects through the lazy callbacks', async () => { - const { connection } = awsDeviceFarmProvider.create(host({ AWS_REGION: 'eu-west-1' })); + const connection = awsDeviceFarm().connection!; const { profile } = await connection.resolve({ flags: { json: false, @@ -87,7 +110,10 @@ test('the factory connects through the lazy callbacks', async () => { awsProjectArn: 'arn:aws:devicefarm:us-west-2:123:project:project-a', awsDeviceArn: DEVICE_ARN, }, + stateDir: '/state', cwd: '/', + env: {}, + host: host({ AWS_REGION: 'eu-west-1' }), }); assert.equal(profile.leaseProvider, 'aws-device-farm'); assert.equal(profile.awsRegion, 'eu-west-1'); diff --git a/packages/provider-aws-device-farm/src/index.ts b/packages/provider-aws-device-farm/src/index.ts new file mode 100644 index 0000000000..37f86930c1 --- /dev/null +++ b/packages/provider-aws-device-farm/src/index.ts @@ -0,0 +1,41 @@ +import type { AgentDevicePlugin, ProviderPluginHost } from 'agent-device/plugins'; + +// The connection and WebDriver code load when they are first used, so importing the package for its +// declaration stays small. +async function loadConnection(host: ProviderPluginHost) { + return (await import('./connection.ts')).createAwsDeviceFarmConnection(host); +} + +/** + * AWS Device Farm as a plugin. Credentials come from the AWS CLI credential provider chain, which + * no environment fingerprint identifies, so the plugin declares no credential variables and works + * with any non-interactive AWS CLI credential source the daemon's host has. + */ +function awsDeviceFarm(): AgentDevicePlugin { + return { + apiVersion: 2, + provider: 'aws-device-farm', + // The AWS CLI credential chain has no environment fingerprint. + credentials: { variables: [] }, + connection: { + capabilities: { + leaseKind: 'direct-device-provider', + requiresAppAttachment: true, + requiresRemoteDaemon: false, + supportsArtifacts: true, + supportsDeferredAppSelection: false, + supportsDirectPortReverse: false, + usesCloudWebDriverLease: true, + }, + resolve: async (context) => await (await loadConnection(context.host)).resolve(context), + verify: async (context) => await (await loadConnection(context.host)).verify(context), + }, + setup: async (host) => ({ + webDriver: (await import('./aws-device-farm-webdriver.ts')).createAwsDeviceFarmWebDriver( + host, + ), + }), + }; +} + +export { awsDeviceFarm as default }; diff --git a/packages/provider-aws-device-farm/src/profile-fields.ts b/packages/provider-aws-device-farm/src/profile-fields.ts new file mode 100644 index 0000000000..97ab5a932d --- /dev/null +++ b/packages/provider-aws-device-farm/src/profile-fields.ts @@ -0,0 +1,31 @@ +import type { ProviderProfileFieldDeclaration } from '@agent-device/contracts/provider-profile-fields'; +import { AWS_DEVICE_FARM_PROVIDER } from './providers.ts'; + +export const AWS_DEVICE_FARM_PROFILE_FIELDS: ProviderProfileFieldDeclaration = { + provider: AWS_DEVICE_FARM_PROVIDER, + label: 'AWS Device Farm', + fields: { + providerApp: 'refused', + providerOsVersion: 'refused', + providerDeviceType: 'refused', + providerProject: 'refused', + providerBuild: 'refused', + providerSessionName: 'consumed', + providerDeviceOrientation: 'refused', + providerGeoLocation: 'refused', + providerTimezone: 'refused', + providerAppiumVersion: 'refused', + providerLanguage: 'refused', + providerLocale: 'refused', + providerNetworkProfile: 'refused', + providerCustomNetwork: 'refused', + providerNoResignApp: 'refused', + providerNetworkLogs: 'refused', + providerNetworkHosts: 'refused', + awsProjectArn: 'consumed', + awsDeviceArn: 'consumed', + awsAppArn: 'consumed', + awsRegion: 'consumed', + awsInteractionMode: 'consumed', + }, +}; diff --git a/packages/provider-aws-device-farm/src/providers.ts b/packages/provider-aws-device-farm/src/providers.ts new file mode 100644 index 0000000000..e00e051b71 --- /dev/null +++ b/packages/provider-aws-device-farm/src/providers.ts @@ -0,0 +1,2 @@ +/** The provider id the registry, connection profiles, and `connect aws-device-farm` use. */ +export const AWS_DEVICE_FARM_PROVIDER = 'aws-device-farm'; diff --git a/packages/provider-aws-device-farm/test/package-smoke.mjs b/packages/provider-aws-device-farm/test/package-smoke.mjs new file mode 100644 index 0000000000..fcfe995b62 --- /dev/null +++ b/packages/provider-aws-device-farm/test/package-smoke.mjs @@ -0,0 +1,186 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import assert from 'node:assert/strict'; + +export const provider = 'aws-device-farm'; +export const primaryExport = { + types: './dist/agent-device.d.mts', + import: './dist/agent-device.mjs', +}; +export const additionalExports = { + './connection-verification': { + types: './dist/connection-verification.d.mts', + import: './dist/connection-verification.mjs', + }, + './package.json': './package.json', +}; +export const args = [ + '--platform', + 'android', + '--aws-project-arn', + 'arn:aws:devicefarm:us-west-2:123456789012:project:12345678-1111-2222-3333-456789abcdef', + '--aws-device-arn', + 'arn:aws:devicefarm:us-west-2::device:12345678-1111-2222-3333-456789abcdef', + '--aws-app-arn', + 'arn:aws:devicefarm:us-west-2:123456789012:upload:12345678-1111-2222-3333-456789abcdef/12345678-1111-2222-3333-456789abcdef', +]; + +const RESOURCES = { + 'get-project': { project: { arn: 'project', name: 'Agent Device' } }, + 'get-device': { + device: { + arn: 'device', + name: 'Google Pixel 8', + platform: 'ANDROID', + os: '14', + availability: 'HIGHLY_AVAILABLE', + }, + }, + 'get-upload': { + upload: { + arn: 'upload', + name: 'sample.apk', + type: 'ANDROID_APP', + status: 'SUCCEEDED', + }, + }, +}; + +// The AWS CLI is the plugin's only external call, so the fixture answers it from PATH. It has no +// credentials of its own to reject, so `connect` must pass on its first try. +export function environment(endpoint) { + void endpoint; + const bin = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-aws-fixture-')); + const script = [ + '#!/usr/bin/env node', + `const resources = ${JSON.stringify(RESOURCES)};`, + 'const subcommand = process.argv[3];', + 'const result = resources[subcommand];', + 'if (!result) {', + ' process.stderr.write(`unexpected aws devicefarm ${subcommand}\\n`);', + ' process.exit(1);', + '}', + 'process.stdout.write(JSON.stringify(result));', + ].join('\n'); + fs.writeFileSync(path.join(bin, 'aws'), script, 'utf8'); + fs.chmodSync(path.join(bin, 'aws'), 0o755); + return { PATH: `${bin}${path.delimiter}${process.env.PATH ?? ''}` }; +} + +export async function verifyPacked({ core, contracts, plugin }) { + const flags = { + platform: 'android', + awsProjectArn: 'arn:aws:devicefarm:us-west-2:123:project:project', + awsDeviceArn: 'arn:aws:devicefarm:us-west-2::device:device', + awsAppArn: 'arn:aws:devicefarm:us-west-2:123:upload:upload', + }; + const calls = []; + const host = { + env: {}, + options: {}, + clientVersion: '0.22.0', + createError: (code, message, details) => new core.AppError(code, message, details), + runHostCommand: async (_command, commandArgs) => { + const subcommand = commandArgs[1]; + calls.push(subcommand); + if (subcommand === 'get-project') return { stdout: JSON.stringify(RESOURCES[subcommand]) }; + if (subcommand === 'get-device') return { stdout: JSON.stringify(RESOURCES[subcommand]) }; + if (subcommand === 'get-upload') { + return { stdout: JSON.stringify({ upload: { status: 'PROCESSING' } }) }; + } + if (subcommand === 'create-remote-access-session') { + return { stdout: JSON.stringify({ remoteAccessSession: { arn: 'session-arn' } }) }; + } + if (subcommand === 'get-remote-access-session') { + throw new core.AppError('COMMAND_FAILED', 'host command failed', { + reason: 'host-primary', + hint: 'Retry manually.', + }); + } + if (subcommand === 'stop-remote-access-session') { + throw new core.AppError('COMMAND_FAILED', 'cleanup failed', { reason: 'cleanup-failed' }); + } + throw new Error(`Unexpected AWS command: ${subcommand}`); + }, + }; + const aws = plugin.default(); + const capture = async (run) => { + try { + await run(); + } catch (error) { + assert.ok(error instanceof core.AppError); + return contracts.normalizeError(error); + } + assert.fail('Expected an AWS failure'); + }; + const missing = await capture(() => + aws.connection.resolve({ flags: { platform: 'android' }, cwd: '/', env: {}, host }), + ); + assert.equal(missing.code, 'INVALID_ARGS'); + assert.ok(missing.hint); + + const verification = await capture(() => aws.connection.verify({ flags, env: {}, host })); + assert.equal(verification.code, 'COMMAND_FAILED'); + assert.equal(verification.details.status, 'PROCESSING'); + assert.equal( + verification.hint, + 'Wait for the upload to succeed or reconnect with a different --aws-app-arn.', + ); + + const setup = await aws.setup(host); + const allocation = await capture(() => + setup.webDriver.prepareSession({ + lease: { leaseId: 'lease-1' }, + req: { flags }, + base: { + provider, + platform: 'android', + deviceName: 'device', + endpoint: 'http://localhost', + webdriverCapabilities: {}, + }, + }), + ); + assert.equal(allocation.code, 'COMMAND_FAILED'); + assert.equal(allocation.details.reason, 'host-primary'); + assert.equal(allocation.hint, 'Retry manually.'); + assert.equal(allocation.details.cleanupError, 'cleanup failed'); + assert.deepEqual(calls.slice(-3), [ + 'create-remote-access-session', + 'get-remote-access-session', + 'stop-remote-access-session', + ]); +} + +export async function verifyTypes({ consumer, run, root }) { + fs.writeFileSync( + path.join(consumer, 'consumer.mts'), + ` +import { startAgentDevice } from 'agent-device'; +import awsDeviceFarm from '@agent-device/aws-device-farm/agent-device'; +import { verifyAwsDeviceFarmConnection } from '@agent-device/aws-device-farm/connection-verification'; +const runtime = await startAgentDevice({ stateDir: './state', plugins: [awsDeviceFarm()] }); +await runtime.close(); +await verifyAwsDeviceFarmConnection({ platform: 'android', projectArn: 'project', deviceArn: 'device' }, async () => ({ stdout: '{}' })); +`, + ); + await run( + process.execPath, + [ + path.join(root, 'node_modules/typescript/bin/tsc'), + '--noEmit', + '--strict', + '--module', + 'NodeNext', + '--moduleResolution', + 'NodeNext', + '--target', + 'ES2022', + '--typeRoots', + path.join(root, 'node_modules/@types'), + 'consumer.mts', + ], + consumer, + ); +} diff --git a/packages/provider-aws-device-farm/tsconfig.json b/packages/provider-aws-device-farm/tsconfig.json new file mode 100644 index 0000000000..a255bc33cf --- /dev/null +++ b/packages/provider-aws-device-farm/tsconfig.json @@ -0,0 +1,29 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "composite": true, + "noEmit": false, + "emitDeclarationOnly": true, + "declaration": true, + "declarationDir": "./dist-types", + "tsBuildInfoFile": "./dist-types/index.tsbuildinfo", + "rootDir": ".", + "paths": { + "agent-device/plugins": ["./node_modules/agent-device/src/sdk/plugins.ts"], + "agent-device/plugins/webdriver": ["./node_modules/agent-device/src/sdk/plugin-webdriver.ts"] + } + }, + "include": ["src"], + "references": [ + { "path": "../build-config" }, + { + "path": "../contracts" + }, + { + "path": "../kernel" + }, + { + "path": "../provider-webdriver" + } + ] +} diff --git a/packages/provider-aws-device-farm/tsdown.config.ts b/packages/provider-aws-device-farm/tsdown.config.ts new file mode 100644 index 0000000000..c8ee5e8593 --- /dev/null +++ b/packages/provider-aws-device-farm/tsdown.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from 'tsdown'; +import { providerPluginBuildConfig } from '@agent-device/build-config'; + +export default defineConfig({ + ...providerPluginBuildConfig, + dts: true, + tsconfig: '../../tsconfig.lib.json', + entry: { + 'agent-device': 'src/index.ts', + 'connection-verification': 'src/aws-device-farm-connection-verification.ts', + }, +}); diff --git a/packages/provider-browserstack/README.md b/packages/provider-browserstack/README.md new file mode 100644 index 0000000000..66596fcf74 --- /dev/null +++ b/packages/provider-browserstack/README.md @@ -0,0 +1,42 @@ +# @agent-device/browserstack + +Use BrowserStack App Automate Android and iOS devices with [agent-device](https://agent-device.dev). +You need a BrowserStack account with App Automate access. + +Install the plugin on the daemon host, then connect with your BrowserStack credentials. + +```sh +agent-device plugins add @agent-device/browserstack@nightly-0.22 +export BROWSERSTACK_USERNAME=your-username +export BROWSERSTACK_ACCESS_KEY=your-access-key +agent-device connect browserstack --session checkout-android --platform android --device "Google Pixel 8" --provider-os-version 14.0 --provider-app bs://app-id +``` + +Run `agent-device help remote` to see the install command for your CLI. + +See the [BrowserStack guide](https://agent-device.dev/docs/browserstack) for setup and supported operations. + +After you add or update the plugin, close your sessions and run `agent-device daemon stop --state-dir ` for your daemon before reconnecting. + +## Use it from JavaScript + +The package default-exports a plugin factory. Pass credentials as options, or leave them out to read `BROWSERSTACK_USERNAME` and `BROWSERSTACK_ACCESS_KEY` from the environment: + +```js +import { startAgentDevice } from 'agent-device'; +import browserstack from '@agent-device/browserstack'; + +const host = await startAgentDevice({ + stateDir: './.my-app/agent-device-state', + plugins: [ + browserstack({ credentials: { username: 'your-username', accessKey: 'your-access-key' } }), + ], +}); +try { + console.log(await host.client.sessions.list()); +} finally { + await host.close(); +} +``` + +Each credential key passed as an option replaces its environment variable. A key left out uses the environment, and only that environment key participates in the credential fingerprint. diff --git a/packages/provider-browserstack/package.json b/packages/provider-browserstack/package.json new file mode 100644 index 0000000000..95124241a3 --- /dev/null +++ b/packages/provider-browserstack/package.json @@ -0,0 +1,58 @@ +{ + "name": "@agent-device/browserstack", + "version": "0.22.0-dev", + "type": "module", + "description": "BrowserStack real-device cloud plugin for agent-device.", + "files": [ + "dist" + ], + "scripts": { + "build": "tsdown --config tsdown.config.ts", + "prepack": "pnpm build" + }, + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./agent-device": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./connection-verification": { + "types": "./src/browserstack-connection-verification.ts", + "default": "./src/browserstack-connection-verification.ts" + }, + "./package.json": "./package.json" + }, + "devDependencies": { + "@agent-device/contracts": "workspace:*", + "@agent-device/kernel": "workspace:*", + "@agent-device/provider-webdriver": "workspace:*", + "agent-device": "workspace:*", + "@agent-device/test-kit": "workspace:*", + "@agent-device/build-config": "workspace:*" + }, + "publishConfig": { + "exports": { + ".": { + "import": "./dist/agent-device.mjs" + }, + "./agent-device": { + "import": "./dist/agent-device.mjs" + }, + "./connection-verification": { + "import": "./dist/connection-verification.mjs" + }, + "./package.json": "./package.json" + }, + "access": "public" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/callstack/agent-device.git", + "directory": "packages/provider-browserstack" + }, + "homepage": "https://agent-device.dev/docs/browserstack" +} diff --git a/packages/provider-webdriver/src/connection-verification.test.ts b/packages/provider-browserstack/src/browserstack-connection-verification.test.ts similarity index 64% rename from packages/provider-webdriver/src/connection-verification.test.ts rename to packages/provider-browserstack/src/browserstack-connection-verification.test.ts index 2e831f9858..cf55bd14b2 100644 --- a/packages/provider-webdriver/src/connection-verification.test.ts +++ b/packages/provider-browserstack/src/browserstack-connection-verification.test.ts @@ -1,11 +1,7 @@ import assert from 'node:assert/strict'; import { afterEach, test, vi } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { - verifyAwsDeviceFarmConnection, - verifyBrowserStackConnection, -} from './connection-verification.ts'; -import type { RunHostCommand } from './dependencies.ts'; +import { verifyBrowserStackConnection } from './browserstack-connection-verification.ts'; const CLIENT_VERSION = '1.2.3'; @@ -18,23 +14,6 @@ const browserStackOptions = { app: 'bs://app-id', }; -const awsResources = { - project: { arn: 'project-arn', name: 'Agent Device' }, - device: { - arn: 'device-arn', - name: 'Google Pixel 8', - platform: 'ANDROID', - os: '14', - availability: 'HIGHLY_AVAILABLE', - }, - upload: { - arn: 'app-arn', - name: 'sample.apk', - type: 'ANDROID_APP', - status: 'SUCCEEDED', - }, -}; - afterEach(() => vi.unstubAllGlobals()); test('BrowserStack verifies the selected resources without creating a session', async () => { @@ -222,98 +201,6 @@ test('BrowserStack accepts an empty-object recent apps response', async () => { assert.equal(result.app.status, 'configured'); }); -test('AWS Device Farm verifies resources without creating a remote access session', async () => { - const concurrency = { active: 0, max: 0 }; - const runHostCommand = createAwsRunner(awsResources, concurrency); - const result = await verifyAwsDeviceFarmConnection( - { - platform: 'android', - projectArn: 'project-arn', - deviceArn: 'device-arn', - appArn: 'app-arn', - region: 'us-west-2', - }, - runHostCommand, - ); - - assert.equal(result.provider, 'aws-device-farm'); - if (result.provider !== 'aws-device-farm') return; - assert.deepEqual(result.project, { name: 'Agent Device', reference: 'project-arn' }); - assert.equal(result.device.name, 'Google Pixel 8'); - assert.equal(result.app.name, 'sample.apk'); - assert.deepEqual( - runHostCommand.mock.calls.map(([, args]) => args[1]), - ['get-project', 'get-device', 'get-upload'], - ); - assert.equal( - runHostCommand.mock.calls.some(([, args]) => args.includes('create-remote-access-session')), - false, - ); - assert.equal(concurrency.max, 3); -}); - -test('AWS Device Farm reports an unattached app without pretending it is installed', async () => { - const runHostCommand = createAwsRunner({ - project: awsResources.project, - device: { ...awsResources.device, platform: 'IOS', name: 'iPhone 15', os: '17' }, - }); - const result = await verifyAwsDeviceFarmConnection( - { - platform: 'ios', - projectArn: 'project-arn', - deviceArn: 'device-arn', - }, - runHostCommand, - ); - - assert.equal(result.app.status, 'missing'); - assert.match(result.app.message ?? '', /--aws-app-arn/); - assert.equal(runHostCommand.mock.calls.length, 2); -}); - -test('AWS Device Farm rejects a device from the wrong platform before allocation', async () => { - const runHostCommand = createAwsRunner({ - project: awsResources.project, - device: { ...awsResources.device, platform: 'IOS', name: 'iPhone 15', os: '17' }, - }); - - await assert.rejects( - verifyAwsDeviceFarmConnection( - { - platform: 'android', - projectArn: 'project-arn', - deviceArn: 'device-arn', - }, - runHostCommand, - ), - /is ios, not android/, - ); - assert.equal( - runHostCommand.mock.calls.some(([, args]) => args.includes('create-remote-access-session')), - false, - ); -}); - -function createAwsRunner( - resources: Partial, - concurrency?: { active: number; max: number }, -) { - return vi.fn(async (_command, args) => { - if (concurrency) { - concurrency.active += 1; - concurrency.max = Math.max(concurrency.max, concurrency.active); - } - await Promise.resolve(); - try { - const resource = resources[String(args[1]).replace('get-', '') as keyof typeof awsResources]; - if (!resource) throw new Error(`Unexpected AWS command: ${args[1]}`); - return { stdout: JSON.stringify({ [String(args[1]).replace('get-', '')]: resource }) }; - } finally { - if (concurrency) concurrency.active -= 1; - } - }); -} - function jsonResponse(value: unknown, status = 200): Response { return new Response(JSON.stringify(value), { status }); } diff --git a/packages/provider-webdriver/src/browserstack-connection-verification.ts b/packages/provider-browserstack/src/browserstack-connection-verification.ts similarity index 92% rename from packages/provider-webdriver/src/browserstack-connection-verification.ts rename to packages/provider-browserstack/src/browserstack-connection-verification.ts index c82482204e..6578ef65ce 100644 --- a/packages/provider-webdriver/src/browserstack-connection-verification.ts +++ b/packages/provider-browserstack/src/browserstack-connection-verification.ts @@ -1,8 +1,5 @@ import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; -import { parseBrowserStackAppReference } from './browserstack.ts'; -import { isBrowserStackAppReference } from './providers.ts'; -import { fetchProviderVerificationJson, sameOsVersion } from './webdriver-utils.ts'; import type { ProviderConnectionResource, ProviderConnectionVerification, @@ -35,7 +32,9 @@ export async function verifyBrowserStackConnection( options: BrowserStackConnectionVerificationOptions, clientVersion: string, ): Promise { - const providerApp = readBrowserStackAppOption(options.app); + const { parseBrowserStackAppReference } = await import('./browserstack.ts'); + const { sameOsVersion } = await import('@agent-device/provider-webdriver/plugin'); + const providerApp = parseBrowserStackAppReference(options.app) ?? options.app; const auth = { username: options.username, accessKey: options.accessKey }; const devices = await fetchBrowserStackJson( options.devicesEndpoint ?? BROWSERSTACK_DEVICES_ENDPOINT, @@ -76,17 +75,13 @@ export async function verifyBrowserStackConnection( }; } -/** Hand-authored remote configs reach verification without passing through connect's normalization. */ -function readBrowserStackAppOption(app: string): string { - return parseBrowserStackAppReference(app) ?? app; -} - async function verifyBrowserStackApp( app: string, options: BrowserStackConnectionVerificationOptions, auth: { username: string; accessKey: string }, clientVersion: string, ): Promise { + const { isBrowserStackAppReference } = await import('./providers.ts'); if (isBrowserStackAppReference(app)) { const apps = await fetchBrowserStackJson( options.appsEndpoint ?? BROWSERSTACK_APPS_ENDPOINT, @@ -124,6 +119,7 @@ async function fetchBrowserStackJson( auth: { username: string; accessKey: string }, clientVersion: string, ): Promise { + const { fetchProviderVerificationJson } = await import('@agent-device/provider-webdriver/plugin'); return await fetchProviderVerificationJson(endpoint, { clientVersion, auth, diff --git a/packages/provider-webdriver/src/browserstack-connection.test.ts b/packages/provider-browserstack/src/browserstack-connection.test.ts similarity index 64% rename from packages/provider-webdriver/src/browserstack-connection.test.ts rename to packages/provider-browserstack/src/browserstack-connection.test.ts index ce232c295a..6d520a2754 100644 --- a/packages/provider-webdriver/src/browserstack-connection.test.ts +++ b/packages/provider-browserstack/src/browserstack-connection.test.ts @@ -2,14 +2,14 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { afterEach, test, vi } from 'vitest'; +import type { ProviderPluginHost } from 'agent-device/plugins'; import { AppError } from '@agent-device/kernel/errors'; -import { createBrowserStackConnection } from './browserstack-connection.ts'; -import { verifyBrowserStackConnection } from './connection-verification.ts'; -import type { CloudWebDriverProviderHost } from './provider-plugin.ts'; -import { mkdtempForTestSync } from './tmp-dir.fixtures.ts'; +import { createBrowserStackConnection } from './connection.ts'; +import { verifyBrowserStackConnection } from './browserstack-connection-verification.ts'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; -vi.mock('./connection-verification.ts', async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock('./browserstack-connection-verification.ts', async (importOriginal) => ({ + ...(await importOriginal()), verifyBrowserStackConnection: vi.fn(), })); @@ -26,24 +26,29 @@ const FLAGS = { providerApp: 'bs://app-id', }; -function host(env: Record = CREDENTIALS): CloudWebDriverProviderHost { +function host(env: Record = CREDENTIALS): ProviderPluginHost { return { env, + options: {}, clientVersion: '1.2.3', runHostCommand: async () => { - throw new Error('BrowserStack runs no host commands'); + throw new Error('host command unused'); }, + createError: (code, message, details) => new AppError(code, message, details), }; } +const CONTEXT = { stateDir: '/state', env: CREDENTIALS, host: host() }; + test('connect resolves a profile carrying only the fields BrowserStack reads', async () => { - const { profile, extraFlags } = createBrowserStackConnection(host()).resolve({ + const { profile, extraFlags } = await createBrowserStackConnection(host()).resolve({ flags: { ...FLAGS, providerApp: 'Bs://app-id', providerProject: 'agent-device', providerTimezone: 'Europe/Warsaw', }, + ...CONTEXT, cwd: '/', }); assert.deepEqual(profile, { @@ -64,32 +69,43 @@ test('connect refuses a malformed bs:// id, a missing local file, and AWS flags' const tempDir = mkdtempForTestSync('browserstack-connection-'); const connection = createBrowserStackConnection(host()); for (const app of ['bs://', 'bs://a b', 'BS://a/b']) { - assert.throws( - () => connection.resolve({ flags: { ...FLAGS, providerApp: app }, cwd: tempDir }), + await assert.rejects( + async () => + connection.resolve({ flags: { ...FLAGS, providerApp: app }, ...CONTEXT, cwd: tempDir }), (error: unknown) => error instanceof AppError && error.code === 'INVALID_ARGS' && error.message === `BrowserStack --provider-app ${app} is not a bs:// app id.`, ); } - assert.throws( - () => connection.resolve({ flags: { ...FLAGS, providerApp: './missing.apk' }, cwd: tempDir }), + await assert.rejects( + async () => + connection.resolve({ + flags: { ...FLAGS, providerApp: './missing.apk' }, + ...CONTEXT, + cwd: tempDir, + }), { code: 'INVALID_ARGS', message: `BrowserStack app file not found: ${path.join(tempDir, 'missing.apk')}`, }, ); - assert.throws( - () => connection.resolve({ flags: { ...FLAGS, awsRegion: 'us-west-2' }, cwd: tempDir }), + await assert.rejects( + async () => + connection.resolve({ flags: { ...FLAGS, awsRegion: 'us-west-2' }, ...CONTEXT, cwd: tempDir }), (error: unknown) => error instanceof AppError && JSON.stringify(error.details?.flags) === '["--aws-region"]', ); }); test('connect requires credentials, platform, device, OS version, and app', async () => { - assert.throws(() => createBrowserStackConnection(host({})).resolve({ flags: FLAGS, cwd: '/' }), { - message: 'connect browserstack requires BROWSERSTACK_USERNAME in the environment.', - }); + await assert.rejects( + async () => + createBrowserStackConnection(host({})).resolve({ flags: FLAGS, ...CONTEXT, cwd: '/' }), + { + message: 'connect browserstack requires BROWSERSTACK_USERNAME in the environment.', + }, + ); const connection = createBrowserStackConnection(host()); for (const [missing, flag] of [ ['platform', '--platform ios|android'], @@ -97,8 +113,9 @@ test('connect requires credentials, platform, device, OS version, and app', asyn ['providerOsVersion', '--provider-os-version '], ['providerApp', '--provider-app '], ] as const) { - assert.throws( - () => connection.resolve({ flags: { ...FLAGS, [missing]: undefined }, cwd: '/' }), + await assert.rejects( + async () => + connection.resolve({ flags: { ...FLAGS, [missing]: undefined }, ...CONTEXT, cwd: '/' }), { code: 'INVALID_ARGS', message: `connect browserstack requires ${flag}.`, @@ -111,13 +128,15 @@ test('connect persists a local artifact as an absolute path and a public URL as const tempDir = mkdtempForTestSync('browserstack-connection-app-'); fs.writeFileSync(path.join(tempDir, 'app.apk'), 'apk'); const connection = createBrowserStackConnection(host()); - const local = connection.resolve({ + const local = await connection.resolve({ flags: { ...FLAGS, providerApp: './app.apk' }, + ...CONTEXT, cwd: tempDir, }); assert.equal(local.profile.providerApp, path.join(tempDir, 'app.apk')); - const url = connection.resolve({ + const url = await connection.resolve({ flags: { ...FLAGS, providerApp: 'https://example.test/app.apk' }, + ...CONTEXT, cwd: tempDir, }); assert.equal(url.profile.providerApp, 'https://example.test/app.apk'); @@ -125,7 +144,7 @@ test('connect persists a local artifact as an absolute path and a public URL as test('verify hands the saved profile and the client version to the verifier', async () => { const connection = createBrowserStackConnection(host()); - await connection.verify({ flags: FLAGS }); + await connection.verify({ flags: FLAGS, env: CREDENTIALS, host: host() }); assert.deepEqual(vi.mocked(verifyBrowserStackConnection).mock.calls[0], [ { username: 'user', @@ -137,8 +156,11 @@ test('verify hands the saved profile and the client version to the verifier', as }, '1.2.3', ]); - await assert.rejects(connection.verify({ flags: { ...FLAGS, device: undefined } }), { - code: 'COMMAND_FAILED', - message: 'BrowserStack profile missed device.', - }); + await assert.rejects( + connection.verify({ flags: { ...FLAGS, device: undefined }, env: CREDENTIALS, host: host() }), + { + code: 'COMMAND_FAILED', + message: 'BrowserStack profile missed device.', + }, + ); }); diff --git a/packages/provider-webdriver/src/browserstack-device-features.test.ts b/packages/provider-browserstack/src/browserstack-device-features.test.ts similarity index 100% rename from packages/provider-webdriver/src/browserstack-device-features.test.ts rename to packages/provider-browserstack/src/browserstack-device-features.test.ts diff --git a/packages/provider-webdriver/src/browserstack-device-features.ts b/packages/provider-browserstack/src/browserstack-device-features.ts similarity index 97% rename from packages/provider-webdriver/src/browserstack-device-features.ts rename to packages/provider-browserstack/src/browserstack-device-features.ts index 05995a068e..bb22da96fc 100644 --- a/packages/provider-webdriver/src/browserstack-device-features.ts +++ b/packages/provider-browserstack/src/browserstack-device-features.ts @@ -4,8 +4,8 @@ import { type CloudProviderProfileFields, } from '@agent-device/contracts/remote'; import { AppError } from '@agent-device/kernel/errors'; -import { requireProviderDeviceOrientation } from './webdriver-utils.ts'; -import type { CloudWebDriverPlatform } from './runtime.ts'; +import { requireProviderDeviceOrientation } from '@agent-device/provider-webdriver/plugin'; +import type { CloudWebDriverPlatform } from '@agent-device/provider-webdriver/plugin'; /** * BrowserStack "device feature" session capabilities. diff --git a/packages/provider-webdriver/src/browserstack-profile-fields.test.ts b/packages/provider-browserstack/src/browserstack-profile-fields.test.ts similarity index 77% rename from packages/provider-webdriver/src/browserstack-profile-fields.test.ts rename to packages/provider-browserstack/src/browserstack-profile-fields.test.ts index 0f57ca4975..0f38dffd86 100644 --- a/packages/provider-webdriver/src/browserstack-profile-fields.test.ts +++ b/packages/provider-browserstack/src/browserstack-profile-fields.test.ts @@ -1,9 +1,8 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; import type { ProviderProfileField } from '@agent-device/contracts/provider-profile-fields'; -import { BROWSERSTACK_PROFILE_FIELDS } from './browserstack.ts'; +import { BROWSERSTACK_PROFILE_FIELDS } from './profile-fields.ts'; import { BROWSERSTACK_DEVICE_FEATURE_SPECS } from './browserstack-device-features.ts'; -import { consumedProfileFields } from './profile-fields.fixtures.ts'; // Fields a hub reads directly while building its session, outside the device-feature table. const HUB_SESSION_FIELDS: readonly ProviderProfileField[] = [ @@ -17,7 +16,9 @@ const HUB_SESSION_FIELDS: readonly ProviderProfileField[] = [ // A consumed device feature with no capability row would be accepted and then dropped at the hub. test('BrowserStack consumes exactly the fields its capability builder reads', () => { assert.deepEqual( - consumedProfileFields(BROWSERSTACK_PROFILE_FIELDS), + (Object.keys(BROWSERSTACK_PROFILE_FIELDS.fields) as ProviderProfileField[]) + .filter((field) => BROWSERSTACK_PROFILE_FIELDS.fields[field] === 'consumed') + .sort(), [...HUB_SESSION_FIELDS, ...BROWSERSTACK_DEVICE_FEATURE_SPECS.map((spec) => spec.field)].sort(), ); }); diff --git a/packages/provider-webdriver/src/browserstack-provider.ts b/packages/provider-browserstack/src/browserstack-webdriver.ts similarity index 71% rename from packages/provider-webdriver/src/browserstack-provider.ts rename to packages/provider-browserstack/src/browserstack-webdriver.ts index 04548c2c79..e014ba1174 100644 --- a/packages/provider-webdriver/src/browserstack-provider.ts +++ b/packages/provider-browserstack/src/browserstack-webdriver.ts @@ -1,47 +1,34 @@ +import type { ProviderPluginHost } from 'agent-device/plugins'; +import type { WebDriverPluginOptions } from 'agent-device/plugins/webdriver'; +import { + buildCloudWebDriverBaseCapabilities, + readFlag, + requireFlag, + requireRequest, + requireRequestPlatform, +} from '@agent-device/provider-webdriver/plugin'; import { BROWSERSTACK_APP_AUTOMATE_ENDPOINT, BROWSERSTACK_APP_UPLOAD_ENDPOINT, BROWSERSTACK_CAPABILITY_OVERRIDES, - BROWSERSTACK_PROFILE_FIELDS, buildBrowserStackCapabilities, createBrowserStackUploadApp, listBrowserStackCloudArtifacts, - requireBrowserStackCredentials, resolveBrowserStackAppReference, } from './browserstack.ts'; import { buildBrowserStackDeviceFeatureCapabilities, readBrowserStackDeviceFeatureFields, } from './browserstack-device-features.ts'; -import { buildCloudWebDriverBaseCapabilities } from './capabilities.ts'; -import type { - BundledCloudWebDriverProvider, - CloudWebDriverConnection, - CloudWebDriverProviderHost, - CloudWebDriverProviderOptions, - CloudWebDriverProviderRegistration, -} from './provider-plugin.ts'; -import { CLOUD_WEBDRIVER_PROVIDERS, cloudWebDriverProviderDeclaration } from './providers.ts'; -import { - readFlag, - requireFlag, - requireRequest, - requireRequestPlatform, -} from './webdriver-utils.ts'; +import { BROWSERSTACK_PROFILE_FIELDS } from './profile-fields.ts'; +import { PROVIDER, requireBrowserStackCredentials } from './providers.ts'; -const PROVIDER = CLOUD_WEBDRIVER_PROVIDERS.browserStack; const SERVICE = 'BrowserStack'; -export const browserStackProvider: BundledCloudWebDriverProvider = { - declaration: cloudWebDriverProviderDeclaration(PROVIDER)!, - create: createBrowserStackProvider, -}; - -function createBrowserStackProvider( - host: CloudWebDriverProviderHost, -): CloudWebDriverProviderRegistration { +/** The BrowserStack WebDriver descriptor the host drives through its shared engine. */ +export function createBrowserStackWebDriver(host: ProviderPluginHost): WebDriverPluginOptions { const { env, clientVersion } = host; - const webDriver: CloudWebDriverProviderOptions = { + const webDriver: WebDriverPluginOptions = { provider: PROVIDER, profileFields: BROWSERSTACK_PROFILE_FIELDS, platform: 'android', @@ -102,11 +89,5 @@ function createBrowserStackProvider( }; }, }; - const connect = async () => - (await import('./browserstack-connection.ts')).createBrowserStackConnection(host); - const connection: CloudWebDriverConnection = { - resolve: async (context) => (await connect()).resolve(context), - verify: async (context) => await (await connect()).verify(context), - }; - return { webDriver, connection }; + return webDriver; } diff --git a/packages/provider-webdriver/src/browserstack.test.ts b/packages/provider-browserstack/src/browserstack.test.ts similarity index 99% rename from packages/provider-webdriver/src/browserstack.test.ts rename to packages/provider-browserstack/src/browserstack.test.ts index 2f77e2c4a6..cc36541656 100644 --- a/packages/provider-webdriver/src/browserstack.test.ts +++ b/packages/provider-browserstack/src/browserstack.test.ts @@ -9,7 +9,7 @@ import { resolveBrowserStackAppReference, uploadBrowserStackApp, } from './browserstack.ts'; -import { mkdtempForTest } from './tmp-dir.fixtures.ts'; +import { mkdtempForTest } from '@agent-device/test-kit'; const realFetch = globalThis.fetch; diff --git a/packages/provider-webdriver/src/browserstack.ts b/packages/provider-browserstack/src/browserstack.ts similarity index 80% rename from packages/provider-webdriver/src/browserstack.ts rename to packages/provider-browserstack/src/browserstack.ts index 4ae188a3d8..9bb5f208f1 100644 --- a/packages/provider-webdriver/src/browserstack.ts +++ b/packages/provider-browserstack/src/browserstack.ts @@ -1,64 +1,24 @@ import type { CloudArtifact, CloudArtifactsResult } from '@agent-device/contracts/observability'; -import type { ProviderProfileFieldDeclaration } from '@agent-device/contracts/provider-profile-fields'; import { AppError } from '@agent-device/kernel/errors'; -import type { CloudWebDriverCapabilityOverrides } from './capabilities.ts'; -import type { CloudWebDriverUploadApp } from './runtime.ts'; -import { cloudArtifactsReadyOrPending, urlArtifactFromDetails } from './artifact-results.ts'; -import { - BROWSERSTACK_CREDENTIAL_VARIABLES, - canonicalBrowserStackAppReference, - CLOUD_WEBDRIVER_PROVIDERS, - isBrowserStackAppReference, -} from './providers.ts'; import { appendUrlPath, appFileUploadForm, + cloudArtifactsReadyOrPending, createHubUploadApp, fetchProviderSessionDetails, postHubAppUpload, - requireEnv, resolveHubAppReference, -} from './webdriver-utils.ts'; - -export const BROWSERSTACK_PROFILE_FIELDS: ProviderProfileFieldDeclaration = { - provider: CLOUD_WEBDRIVER_PROVIDERS.browserStack, - label: 'BrowserStack', - fields: { - providerApp: 'consumed', - providerOsVersion: 'consumed', - providerDeviceType: 'refused', - providerProject: 'consumed', - providerBuild: 'consumed', - providerSessionName: 'consumed', - providerDeviceOrientation: 'consumed', - providerGeoLocation: 'consumed', - providerTimezone: 'consumed', - providerAppiumVersion: 'consumed', - providerLanguage: 'consumed', - providerLocale: 'consumed', - providerNetworkProfile: 'consumed', - providerCustomNetwork: 'consumed', - providerNoResignApp: 'consumed', - providerNetworkLogs: 'refused', - providerNetworkHosts: 'refused', - awsProjectArn: 'refused', - awsDeviceArn: 'refused', - awsAppArn: 'refused', - awsRegion: 'refused', - awsInteractionMode: 'refused', - }, -}; - -/** The BrowserStack credentials in `env`; `consumer` names the command a missing one fails. */ -export function requireBrowserStackCredentials( - env: Readonly>, - consumer: string, -): { username: string; accessKey: string } { - return { - username: requireEnv(env, BROWSERSTACK_CREDENTIAL_VARIABLES.username, consumer), - accessKey: requireEnv(env, BROWSERSTACK_CREDENTIAL_VARIABLES.accessKey, consumer), - }; -} + urlArtifactFromDetails, +} from '@agent-device/provider-webdriver/plugin'; +import type { + CloudWebDriverCapabilityOverrides, + CloudWebDriverUploadApp, +} from '@agent-device/provider-webdriver/plugin'; +import { + PROVIDER, + canonicalBrowserStackAppReference, + isBrowserStackAppReference, +} from './providers.ts'; export const BROWSERSTACK_APP_AUTOMATE_ENDPOINT = 'https://hub-cloud.browserstack.com/wd/hub/'; export const BROWSERSTACK_APP_UPLOAD_ENDPOINT = @@ -130,7 +90,7 @@ export async function uploadBrowserStackApp( signal?.throwIfAborted(); return await postHubAppUpload( await appFileUploadForm(appPath, 'file', { - provider: CLOUD_WEBDRIVER_PROVIDERS.browserStack, + provider: PROVIDER, service: 'BrowserStack', }), { diff --git a/packages/provider-webdriver/src/browserstack-connection.ts b/packages/provider-browserstack/src/connection.ts similarity index 72% rename from packages/provider-webdriver/src/browserstack-connection.ts rename to packages/provider-browserstack/src/connection.ts index 018b23977d..2f1250b21e 100644 --- a/packages/provider-webdriver/src/browserstack-connection.ts +++ b/packages/provider-browserstack/src/connection.ts @@ -1,40 +1,30 @@ +import type { PluginConnection, ProviderPluginHost } from 'agent-device/plugins'; import { rejectRefusedProviderProfileFields, requireResolvedProfilePlatform, requireResolvedProfileValue, } from '@agent-device/contracts/provider-profile-fields'; -import { - BROWSERSTACK_PROFILE_FIELDS, - parseBrowserStackAppReference, - requireBrowserStackCredentials, -} from './browserstack.ts'; -import { readBrowserStackDeviceFeatureFields } from './browserstack-device-features.ts'; -import { verifyBrowserStackConnection } from './connection-verification.ts'; -import type { - CloudWebDriverConnection, - CloudWebDriverConnectionContext, - CloudWebDriverConnectProfileResolution, - CloudWebDriverProviderHost, -} from './provider-plugin.ts'; -import { CLOUD_WEBDRIVER_PROVIDERS } from './providers.ts'; import { requireConnectFlag, requireConnectPlatform, resolveLocalAppArtifact, -} from './webdriver-utils.ts'; +} from '@agent-device/provider-webdriver/plugin'; +import { parseBrowserStackAppReference } from './browserstack.ts'; +import { readBrowserStackDeviceFeatureFields } from './browserstack-device-features.ts'; +import { BROWSERSTACK_PROFILE_FIELDS } from './profile-fields.ts'; +import { PROVIDER, requireBrowserStackCredentials } from './providers.ts'; +import { verifyBrowserStackConnection } from './browserstack-connection-verification.ts'; -const PROVIDER = CLOUD_WEBDRIVER_PROVIDERS.browserStack; const SERVICE = 'BrowserStack'; -const CONSUMER = `connect ${PROVIDER}`; /** The `connect browserstack` callbacks, loaded only when the CLI runs them. */ -export function createBrowserStackConnection(host: CloudWebDriverProviderHost): { - resolve(context: CloudWebDriverConnectionContext): CloudWebDriverConnectProfileResolution; -} & CloudWebDriverConnection { +export function createBrowserStackConnection( + host: ProviderPluginHost, +): Pick { return { - resolve: ({ flags, cwd }): CloudWebDriverConnectProfileResolution => { + resolve: ({ flags, cwd }) => { rejectRefusedProviderProfileFields(flags, BROWSERSTACK_PROFILE_FIELDS); - requireBrowserStackCredentials(host.env, CONSUMER); + requireBrowserStackCredentials(host.env, `connect ${PROVIDER}`); const platform = requireConnectPlatform(flags, PROVIDER); const device = requireConnectFlag(flags.device, PROVIDER, '--device '); const providerOsVersion = requireConnectFlag( @@ -70,7 +60,7 @@ export function createBrowserStackConnection(host: CloudWebDriverProviderHost): verify: async ({ flags }) => await verifyBrowserStackConnection( { - ...requireBrowserStackCredentials(host.env, CONSUMER), + ...requireBrowserStackCredentials(host.env, `connect ${PROVIDER}`), platform: requireResolvedProfilePlatform(flags.platform, SERVICE), deviceName: requireResolvedProfileValue( flags.device, diff --git a/packages/provider-browserstack/src/index.test.ts b/packages/provider-browserstack/src/index.test.ts new file mode 100644 index 0000000000..08f3feca35 --- /dev/null +++ b/packages/provider-browserstack/src/index.test.ts @@ -0,0 +1,214 @@ +import assert from 'node:assert/strict'; +import { afterEach, test, vi } from 'vitest'; +import type { ProviderPluginHost } from 'agent-device/plugins'; +import { AppError } from '@agent-device/kernel/errors'; +import browserstack from './index.ts'; +import { verifyBrowserStackConnection } from './browserstack-connection-verification.ts'; + +vi.mock('./browserstack-connection-verification.ts', () => ({ + verifyBrowserStackConnection: vi.fn(), +})); + +const realFetch = globalThis.fetch; + +afterEach(() => { + globalThis.fetch = realFetch; + vi.clearAllMocks(); +}); + +function host(env: Record): ProviderPluginHost { + return { + env, + options: {}, + clientVersion: '0.0.0-test', + runHostCommand: async () => { + throw new Error('host command unused'); + }, + createError: (code, message, details) => new AppError(code, message, details), + }; +} + +function capturedAuthorization(): { read(): string | undefined } { + let authorization: string | undefined; + globalThis.fetch = async (_input, init) => { + authorization = new Headers(init?.headers).get('authorization') ?? undefined; + return new Response(JSON.stringify({})); + }; + return { read: () => authorization }; +} + +async function listArtifacts(plugin: ReturnType, env: Record) { + const setup = await plugin.setup(host(env)); + if (!('webDriver' in setup)) throw new Error('BrowserStack sets up a WebDriver descriptor'); + await setup.webDriver.listArtifacts!({ provider: 'browserstack', providerSessionId: 'SESSION1' }); +} + +const basic = (username: string, accessKey: string) => + `Basic ${Buffer.from(`${username}:${accessKey}`).toString('base64')}`; + +test('the plugin declares its provider, capabilities and credential variables', () => { + const plugin = browserstack(); + assert.equal(plugin.apiVersion, 2); + assert.equal(plugin.provider, 'browserstack'); + assert.deepEqual(plugin.credentials, { + variables: ['BROWSERSTACK_USERNAME', 'BROWSERSTACK_ACCESS_KEY'], + }); + assert.deepEqual(plugin.connection?.capabilities, { + leaseKind: 'direct-device-provider', + requiresAppAttachment: false, + requiresRemoteDaemon: false, + supportsArtifacts: true, + supportsDeferredAppSelection: false, + supportsDirectPortReverse: false, + usesCloudWebDriverLease: true, + }); +}); + +test('setup builds a WebDriver descriptor that reads its hub endpoint from the environment', async () => { + const setup = await browserstack().setup( + host({ + BROWSERSTACK_USERNAME: 'user', + BROWSERSTACK_ACCESS_KEY: 'key', + BROWSERSTACK_WEBDRIVER_ENDPOINT: 'https://hub.test/wd/hub/', + }), + ); + if (!('webDriver' in setup)) throw new Error('BrowserStack sets up a WebDriver descriptor'); + assert.equal(setup.webDriver.provider, 'browserstack'); + assert.equal(setup.webDriver.endpoint, 'https://hub.test/wd/hub/'); + assert.equal(setup.webDriver.profileFields.provider, 'browserstack'); +}); + +test('the plugin declares the BrowserStack variables only when it reads credentials from the environment', () => { + assert.deepEqual(browserstack().credentials, { + variables: ['BROWSERSTACK_USERNAME', 'BROWSERSTACK_ACCESS_KEY'], + }); + assert.deepEqual(browserstack({ credentials: { username: 'u', accessKey: 'k' } }).credentials, { + variables: [], + }); +}); + +test('a credentials object missing one key still declares the variable it reads from the environment', () => { + assert.deepEqual(browserstack({ credentials: { username: 'u' } }).credentials, { + variables: ['BROWSERSTACK_ACCESS_KEY'], + }); + assert.deepEqual(browserstack({ credentials: { accessKey: 'k' } }).credentials, { + variables: ['BROWSERSTACK_USERNAME'], + }); +}); + +test('credentials passed as options replace the environment, which stays the fallback', async () => { + const captured = capturedAuthorization(); + const env = { BROWSERSTACK_USERNAME: 'env-user', BROWSERSTACK_ACCESS_KEY: 'env-key' }; + + await listArtifacts( + browserstack({ credentials: { username: 'opt-user', accessKey: 'opt-key' } }), + env, + ); + assert.equal(captured.read(), basic('opt-user', 'opt-key')); + await listArtifacts( + browserstack({ credentials: { username: 'opt-user', accessKey: 'opt-key' } }), + {}, + ); + assert.equal(captured.read(), basic('opt-user', 'opt-key')); + await listArtifacts(browserstack(), env); + assert.equal(captured.read(), basic('env-user', 'env-key')); + await assert.rejects(listArtifacts(browserstack(), {}), { code: 'INVALID_ARGS' }); +}); + +test('a credentials object missing one key falls back to the environment for that key', async () => { + const captured = capturedAuthorization(); + await listArtifacts(browserstack({ credentials: { username: 'opt-user' } }), { + BROWSERSTACK_USERNAME: 'env-user', + BROWSERSTACK_ACCESS_KEY: 'env-key', + }); + assert.equal(captured.read(), basic('opt-user', 'env-key')); + await listArtifacts(browserstack({ credentials: { accessKey: 'opt-key' } }), { + BROWSERSTACK_USERNAME: 'env-user', + BROWSERSTACK_ACCESS_KEY: 'env-key', + }); + assert.equal(captured.read(), basic('env-user', 'opt-key')); +}); + +test.each([ + [{ username: '' }, ['BROWSERSTACK_ACCESS_KEY']], + [{ accessKey: '' }, ['BROWSERSTACK_USERNAME']], +] as const)( + 'explicit empty credential %j never falls back to the environment', + async (credentials, variables) => { + const env = { BROWSERSTACK_USERNAME: 'env-user', BROWSERSTACK_ACCESS_KEY: 'env-key' }; + const fetch = vi.fn(async () => new Response('{}')); + globalThis.fetch = fetch; + const flags = { + json: false, + help: false, + version: false, + platform: 'android', + device: 'Pixel', + providerOsVersion: '14', + providerApp: 'bs://app-id', + } as const; + const plugin = browserstack({ credentials }); + const [resolve, artifacts] = await Promise.allSettled([ + Promise.resolve().then(() => + plugin.connection!.resolve({ flags, stateDir: '/state', cwd: '/', env, host: host(env) }), + ), + listArtifacts(plugin, env), + ]); + assert.equal(resolve.status, 'rejected'); + if (resolve.status === 'rejected') assert.equal(resolve.reason.code, 'INVALID_ARGS'); + assert.equal(artifacts.status, 'rejected'); + if (artifacts.status === 'rejected') assert.equal(artifacts.reason.code, 'INVALID_ARGS'); + assert.deepEqual(plugin.credentials, { variables }); + assert.equal(fetch.mock.calls.length, 0); + }, +); + +test('connect uses the option credentials without an environment and verifies with them', async () => { + vi.mocked(verifyBrowserStackConnection).mockResolvedValue({ + provider: 'browserstack', + service: 'BrowserStack', + verificationMessage: 'verified', + device: { status: 'verified', name: 'Google Pixel 8', platform: 'android', osVersion: '14.0' }, + app: { status: 'verified', reference: 'bs://app-id' }, + }); + const { connection } = browserstack({ + credentials: { username: 'opt-user', accessKey: 'opt-key' }, + }); + const flags = { + json: false, + help: false, + version: false, + platform: 'android', + device: 'Google Pixel 8', + providerOsVersion: '14.0', + providerApp: 'bs://app-id', + } as const; + + const resolved = await connection!.resolve({ + flags, + stateDir: '/state', + cwd: '/work', + env: {}, + host: host({}), + }); + assert.equal(resolved.profile.leaseProvider, 'browserstack'); + await connection!.verify({ flags, env: {}, host: host({}) }); + assert.deepEqual( + [ + vi.mocked(verifyBrowserStackConnection).mock.calls[0]?.[0].username, + vi.mocked(verifyBrowserStackConnection).mock.calls[0]?.[0].accessKey, + ], + ['opt-user', 'opt-key'], + ); + await assert.rejects( + async () => + await browserstack().connection!.resolve({ + flags, + stateDir: '/state', + cwd: '/work', + env: {}, + host: host({}), + }), + { code: 'INVALID_ARGS' }, + ); +}); diff --git a/packages/provider-browserstack/src/index.ts b/packages/provider-browserstack/src/index.ts new file mode 100644 index 0000000000..ea9635de61 --- /dev/null +++ b/packages/provider-browserstack/src/index.ts @@ -0,0 +1,66 @@ +import type { AgentDevicePlugin, ProviderPluginHost } from 'agent-device/plugins'; +import { HOSTED_WEBDRIVER_CONNECTION } from '@agent-device/provider-webdriver/providers'; +import { BROWSERSTACK_CREDENTIAL_VARIABLES } from './providers.ts'; + +export type BrowserStackOptions = { + /** Each supplied key replaces its environment variable; omitted keys use the environment. */ + credentials?: { username?: string; accessKey?: string }; +}; + +// The connection and WebDriver code load when they are first used, so importing the package for its +// declaration stays small. +async function loadConnection(host: ProviderPluginHost) { + return (await import('./connection.ts')).createBrowserStackConnection(host); +} + +/** + * BrowserStack as a plugin. The credentials come from `options.credentials`, with the + * `BROWSERSTACK_USERNAME` and `BROWSERSTACK_ACCESS_KEY` environment variables as the fallback for + * each key the options leave out. The plugin declares only the variables it reads from the + * environment; credentials passed as options are not part of the environment the daemon + * fingerprints. + */ +function browserstack(options: BrowserStackOptions = {}): AgentDevicePlugin { + const { credentials } = options; + const withCredentials = (host: ProviderPluginHost): ProviderPluginHost => + credentials + ? { + ...host, + // A key the caller left out falls back to the environment instead of shadowing it. + env: { + ...host.env, + ...(credentials.username !== undefined + ? { [BROWSERSTACK_CREDENTIAL_VARIABLES.username]: credentials.username } + : {}), + ...(credentials.accessKey !== undefined + ? { [BROWSERSTACK_CREDENTIAL_VARIABLES.accessKey]: credentials.accessKey } + : {}), + }, + } + : host; + // Only the variables the options do not supply come from the environment, so only those are + // part of the credential fingerprint. + const environmentVariables = [ + ...(credentials?.username !== undefined ? [] : [BROWSERSTACK_CREDENTIAL_VARIABLES.username]), + ...(credentials?.accessKey !== undefined ? [] : [BROWSERSTACK_CREDENTIAL_VARIABLES.accessKey]), + ]; + return { + apiVersion: 2, + provider: 'browserstack', + credentials: { variables: environmentVariables }, + connection: { + capabilities: { ...HOSTED_WEBDRIVER_CONNECTION }, + resolve: async (context) => + (await loadConnection(withCredentials(context.host))).resolve(context), + verify: async (context) => + await (await loadConnection(withCredentials(context.host))).verify(context), + }, + setup: async (host) => ({ + webDriver: (await import('./browserstack-webdriver.ts')).createBrowserStackWebDriver( + withCredentials(host), + ), + }), + }; +} + +export { browserstack as default }; diff --git a/packages/provider-browserstack/src/profile-fields.ts b/packages/provider-browserstack/src/profile-fields.ts new file mode 100644 index 0000000000..221ee249cd --- /dev/null +++ b/packages/provider-browserstack/src/profile-fields.ts @@ -0,0 +1,30 @@ +import type { ProviderProfileFieldDeclaration } from '@agent-device/contracts/provider-profile-fields'; + +export const BROWSERSTACK_PROFILE_FIELDS: ProviderProfileFieldDeclaration = { + provider: 'browserstack', + label: 'BrowserStack', + fields: { + providerApp: 'consumed', + providerOsVersion: 'consumed', + providerDeviceType: 'refused', + providerProject: 'consumed', + providerBuild: 'consumed', + providerSessionName: 'consumed', + providerDeviceOrientation: 'consumed', + providerGeoLocation: 'consumed', + providerTimezone: 'consumed', + providerAppiumVersion: 'consumed', + providerLanguage: 'consumed', + providerLocale: 'consumed', + providerNetworkProfile: 'consumed', + providerCustomNetwork: 'consumed', + providerNoResignApp: 'consumed', + providerNetworkLogs: 'refused', + providerNetworkHosts: 'refused', + awsProjectArn: 'refused', + awsDeviceArn: 'refused', + awsAppArn: 'refused', + awsRegion: 'refused', + awsInteractionMode: 'refused', + }, +}; diff --git a/packages/provider-browserstack/src/providers.ts b/packages/provider-browserstack/src/providers.ts new file mode 100644 index 0000000000..de47ea2c34 --- /dev/null +++ b/packages/provider-browserstack/src/providers.ts @@ -0,0 +1,29 @@ +import { requireEnv } from '@agent-device/provider-webdriver/plugin'; +import { canonicalSchemeReference } from '@agent-device/provider-webdriver/providers'; + +/** The provider id the registry, connection profiles, and `connect browserstack` use. */ +export const PROVIDER = 'browserstack'; + +/** The environment variables that hold BrowserStack credentials. */ +export const BROWSERSTACK_CREDENTIAL_VARIABLES = { + username: 'BROWSERSTACK_USERNAME', + accessKey: 'BROWSERSTACK_ACCESS_KEY', +} as const; + +export function requireBrowserStackCredentials( + env: Readonly>, + providerLabel: string, +): { username: string; accessKey: string } { + return { + username: requireEnv(env, BROWSERSTACK_CREDENTIAL_VARIABLES.username, providerLabel), + accessKey: requireEnv(env, BROWSERSTACK_CREDENTIAL_VARIABLES.accessKey, providerLabel), + }; +} + +export function isBrowserStackAppReference(reference: string): boolean { + return /^bs:\/\/[\w.-]+$/.test(reference); +} + +export function canonicalBrowserStackAppReference(app: string): string | undefined { + return canonicalSchemeReference(app, 'bs://'); +} diff --git a/packages/provider-browserstack/test/package-smoke.mjs b/packages/provider-browserstack/test/package-smoke.mjs new file mode 100644 index 0000000000..d114c86259 --- /dev/null +++ b/packages/provider-browserstack/test/package-smoke.mjs @@ -0,0 +1,30 @@ +export const provider = 'browserstack'; +export const additionalExports = { + './connection-verification': { import: './dist/connection-verification.mjs' }, + './package.json': './package.json', +}; +export const args = [ + '--platform', + 'android', + '--device', + 'Google Pixel 8', + '--provider-os-version', + '14.0', + '--provider-app', + 'bs://app-id', +]; +export function environment() { + return { BROWSERSTACK_USERNAME: 'user', BROWSERSTACK_ACCESS_KEY: 'key' }; +} +export function respond(url, rejectCredentials) { + const pathname = new URL(url, 'http://fixture').pathname; + if (!['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/app-automate/devices.json', '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/app-automate/recent_apps'].includes(pathname)) { + return { status: 404, body: { error: 'not-found' } }; + } + if (rejectCredentials) return { status: 401, body: { error: 'unauthorized' } }; + return pathname === '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/app-automate/devices.json' + ? { body: [{ os: 'android', os_version: '14.0', device: 'Google Pixel 8', realMobile: true }] } + : { body: [{ app_name: 'app.apk', app_version: '1.0', app_url: 'bs://app-id' }] }; +} + +export const fetchRedirects = ['https://api-cloud.browserstack.com']; diff --git a/packages/provider-browserstack/tsconfig.json b/packages/provider-browserstack/tsconfig.json new file mode 100644 index 0000000000..dacac6776d --- /dev/null +++ b/packages/provider-browserstack/tsconfig.json @@ -0,0 +1,34 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "composite": true, + "noEmit": false, + "emitDeclarationOnly": true, + "declaration": true, + "declarationDir": "./dist-types", + "tsBuildInfoFile": "./dist-types/index.tsbuildinfo", + "rootDir": ".", + "paths": { + "agent-device/plugins": ["./node_modules/agent-device/src/sdk/plugins.ts"], + "agent-device/plugins/webdriver": ["./node_modules/agent-device/src/sdk/plugin-webdriver.ts"] + } + }, + "include": ["src"], + "references": [ + { + "path": "../build-config" + }, + { + "path": "../contracts" + }, + { + "path": "../kernel" + }, + { + "path": "../provider-webdriver" + }, + { + "path": "../test-kit" + } + ] +} diff --git a/packages/provider-browserstack/tsdown.config.ts b/packages/provider-browserstack/tsdown.config.ts new file mode 100644 index 0000000000..b223adde00 --- /dev/null +++ b/packages/provider-browserstack/tsdown.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'tsdown'; +import { providerPluginBuildConfig } from '@agent-device/build-config'; + +export default defineConfig({ + ...providerPluginBuildConfig, + entry: { + 'agent-device': 'src/index.ts', + 'connection-verification': 'src/browserstack-connection-verification.ts', + }, +}); diff --git a/packages/provider-limrun/src/index.ts b/packages/provider-limrun/src/index.ts index ebb24478d1..25db54d2ee 100644 --- a/packages/provider-limrun/src/index.ts +++ b/packages/provider-limrun/src/index.ts @@ -1,4 +1,4 @@ -export { LIMRUN_PROFILE_FIELDS, LIMRUN_PROVIDER } from './device.ts'; +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'; diff --git a/packages/provider-revyl/package.json b/packages/provider-revyl/package.json index cf47afc342..e50a9c4cb3 100644 --- a/packages/provider-revyl/package.json +++ b/packages/provider-revyl/package.json @@ -1,6 +1,6 @@ { "name": "@agent-device/revyl", - "version": "0.21.39-dev", + "version": "0.22.0-dev", "type": "module", "description": "Revyl cloud iOS simulator and Android emulator plugin for agent-device.", "files": [ @@ -28,26 +28,8 @@ "@agent-device/provision-kit": "workspace:*", "@agent-device/provider-webdriver": "workspace:*", "@agent-device/test-kit": "workspace:*", - "agent-device": "workspace:*" - }, - "agentDevicePlugin": { - "apiVersion": 1, - "provider": "revyl", - "entry": "./dist/plugin.mjs", - "connection": { - "leaseKind": "direct-device-provider", - "requiresAppAttachment": false, - "requiresRemoteDaemon": false, - "supportsArtifacts": false, - "supportsDeferredAppSelection": false, - "supportsDirectPortReverse": false, - "usesCloudWebDriverLease": false, - "holdsCloudDevice": true - }, - "credentialVariables": [ - "REVYL_API_KEY", - "REVYL_API_URL" - ] + "agent-device": "workspace:*", + "@agent-device/build-config": "workspace:*" }, "publishConfig": { "exports": { diff --git a/packages/provider-revyl/src/plugin.ts b/packages/provider-revyl/src/plugin.ts deleted file mode 100644 index 71e65786f2..0000000000 --- a/packages/provider-revyl/src/plugin.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { ProviderPluginHost } from 'agent-device/plugins'; -import type { RevylConnection } from './connection.ts'; -import type { RevylRuntimeRegistration } from './runtime.ts'; - -/** What the version 1 host reads out of this entry: the runtime pair, plus the connect half. */ -export type RevylPluginEntryResult = RevylRuntimeRegistration & { - connection: RevylConnection; -}; - -/** - * The version 1 plugin entry, kept so hosts without the version 2 contract still load this package. - * The runtime is built by the same setup the version 2 declaration runs. - */ -export default async function revylPlugin( - host: ProviderPluginHost, -): Promise { - const { setupRevylPlugin } = await import('./plugin-setup.ts'); - const { createRevylConnection } = await import('./connection.ts'); - const registration = await setupRevylPlugin(host); - return { ...registration, connection: createRevylConnection(host) }; -} diff --git a/packages/provider-revyl/tsconfig.json b/packages/provider-revyl/tsconfig.json index 71c7fd8f75..f66af48034 100644 --- a/packages/provider-revyl/tsconfig.json +++ b/packages/provider-revyl/tsconfig.json @@ -15,6 +15,9 @@ }, "include": ["src"], "references": [ + { + "path": "../build-config" + }, { "path": "../capture-kit" }, diff --git a/packages/provider-revyl/tsdown.config.ts b/packages/provider-revyl/tsdown.config.ts index 6173fbf90a..ff5b303a0c 100644 --- a/packages/provider-revyl/tsdown.config.ts +++ b/packages/provider-revyl/tsdown.config.ts @@ -1,19 +1 @@ -import { defineConfig } from 'tsdown'; - -export default defineConfig({ - entry: { plugin: 'src/plugin.ts', 'agent-device': 'src/index.ts' }, - outDir: 'dist', - format: 'esm', - platform: 'node', - target: 'es2022', - minify: true, - dts: false, - hash: false, - deps: { alwaysBundle: [/^@agent-device\//] }, - inputOptions: { - onLog(level, log, handler) { - if (log.code === 'UNRESOLVED_IMPORT') throw new Error(log.message); - handler(level, log); - }, - }, -}); +export { providerPluginBuildConfig as default } from '@agent-device/build-config'; diff --git a/packages/provider-testmu/package.json b/packages/provider-testmu/package.json index 10bec1b831..156620b759 100644 --- a/packages/provider-testmu/package.json +++ b/packages/provider-testmu/package.json @@ -1,6 +1,6 @@ { "name": "@agent-device/testmu", - "version": "0.21.39-dev", + "version": "0.22.0-dev", "type": "module", "description": "TestMu AI real and virtual mobile device plugin for agent-device.", "files": [ @@ -29,25 +29,8 @@ "@agent-device/contracts": "workspace:*", "@agent-device/kernel": "workspace:*", "@agent-device/provider-webdriver": "workspace:*", - "agent-device": "workspace:*" - }, - "agentDevicePlugin": { - "apiVersion": 1, - "provider": "testmu", - "entry": "./dist/plugin.mjs", - "connection": { - "leaseKind": "direct-device-provider", - "requiresAppAttachment": false, - "requiresRemoteDaemon": false, - "supportsArtifacts": true, - "supportsDeferredAppSelection": false, - "supportsDirectPortReverse": false, - "usesCloudWebDriverLease": true - }, - "credentialVariables": [ - "LT_USERNAME", - "LT_ACCESS_KEY" - ] + "agent-device": "workspace:*", + "@agent-device/build-config": "workspace:*" }, "publishConfig": { "exports": { diff --git a/packages/provider-testmu/src/index.test.ts b/packages/provider-testmu/src/index.test.ts index 924457b2fd..85a84835e7 100644 --- a/packages/provider-testmu/src/index.test.ts +++ b/packages/provider-testmu/src/index.test.ts @@ -4,7 +4,6 @@ import type { ProviderPluginHost } from 'agent-device/plugins'; import { AppError } from '@agent-device/kernel/errors'; import testmu from './index.ts'; import { verifyTestMuConnection } from './testmu-connection-verification.ts'; -import manifest from '../package.json' with { type: 'json' }; vi.mock('./testmu-connection-verification.ts', () => ({ verifyTestMuConnection: vi.fn() })); @@ -20,6 +19,9 @@ function host(env: Record): ProviderPluginHost { env, options: {}, clientVersion: '0.0.0-test', + runHostCommand: async () => { + throw new Error('host command unused'); + }, createError: (code, message, details) => new AppError(code, message, details), }; } @@ -119,12 +121,20 @@ test('connect uses the option credentials without an environment and verifies wi ); }); -test('the v2 declaration matches the v1 manifest that hosts without the v2 contract read', () => { - const v1 = manifest.agentDevicePlugin; - assert.equal(testmu().provider, v1.provider); - assert.deepEqual(testmu().connection?.capabilities, v1.connection); - assert.deepEqual(testmu().credentials.variables, v1.credentialVariables); - assert.equal(v1.apiVersion, 1); +test('the plugin declares its provider, capabilities and credential variables', () => { + const plugin = testmu(); + assert.equal(plugin.apiVersion, 2); + assert.equal(plugin.provider, 'testmu'); + assert.deepEqual(plugin.credentials, { variables: ['LT_USERNAME', 'LT_ACCESS_KEY'] }); + assert.deepEqual(plugin.connection?.capabilities, { + leaseKind: 'direct-device-provider', + requiresAppAttachment: false, + requiresRemoteDaemon: false, + supportsArtifacts: true, + supportsDeferredAppSelection: false, + supportsDirectPortReverse: false, + usesCloudWebDriverLease: true, + }); }); test('a credentials object missing one key falls back to the environment for that key', async () => { diff --git a/packages/provider-testmu/src/plugin.test.ts b/packages/provider-testmu/src/plugin.test.ts deleted file mode 100644 index 29621ae951..0000000000 --- a/packages/provider-testmu/src/plugin.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import assert from 'node:assert/strict'; -import { afterEach, test, vi } from 'vitest'; -import type { ProviderPluginHost } from 'agent-device/plugins'; -import { AppError } from '@agent-device/kernel/errors'; -import testMuPlugin from './plugin.ts'; -import { verifyTestMuConnection } from './testmu-connection-verification.ts'; - -vi.mock('./testmu-connection-verification.ts', () => ({ verifyTestMuConnection: vi.fn() })); - -const realFetch = globalThis.fetch; - -afterEach(() => { - globalThis.fetch = realFetch; - vi.clearAllMocks(); -}); - -function host(env: Record): ProviderPluginHost { - return { - env, - options: {}, - clientVersion: '0.0.0-test', - createError: (code, message, details) => new AppError(code, message, details), - }; -} - -test('whitespace-only credentials are missing, not a provider authentication failure', async () => { - globalThis.fetch = async () => { - throw new Error('a missing credential must not reach TestMu AI'); - }; - for (const env of [ - { LT_USERNAME: ' ', LT_ACCESS_KEY: 'key' }, - { LT_USERNAME: 'user', LT_ACCESS_KEY: '\t' }, - ]) { - await assert.rejects( - testMuPlugin(host(env)).webDriver.listArtifacts!({ - provider: 'testmu', - providerSessionId: 'SESSION1', - }), - (error: unknown) => - error instanceof AppError && - error.code === 'INVALID_ARGS' && - /requires LT_(USERNAME|ACCESS_KEY) in the environment/.test(error.message), - ); - } -}); - -test('verification of a hand-authored profile canonicalizes an upper-case app scheme', async () => { - vi.mocked(verifyTestMuConnection).mockResolvedValue({ - provider: 'testmu', - service: 'TestMu AI', - verificationMessage: 'verified', - device: { status: 'verified', name: 'iPhone 16', platform: 'ios', osVersion: '18.0' }, - app: { status: 'verified', reference: 'lt://APP1' }, - }); - const env = { LT_USERNAME: 'user', LT_ACCESS_KEY: 'key' }; - await testMuPlugin(host(env)).connection.verify({ - flags: { - json: false, - help: false, - version: false, - platform: 'ios', - device: 'iPhone 16', - providerOsVersion: '18.0', - providerApp: 'LT://APP1', - }, - }); - assert.equal(vi.mocked(verifyTestMuConnection).mock.calls[0]?.[0].app, 'lt://APP1'); -}); diff --git a/packages/provider-testmu/src/plugin.ts b/packages/provider-testmu/src/plugin.ts deleted file mode 100644 index 6303af5632..0000000000 --- a/packages/provider-testmu/src/plugin.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { ProviderPluginHost } from 'agent-device/plugins'; -import { createTestMuConnection } from './connection.ts'; -import { createTestMuWebDriver } from './testmu-webdriver.ts'; - -/** The version 1 plugin entry, kept so hosts without the version 2 contract still load this package. */ -export default function testMuPlugin(host: ProviderPluginHost) { - return { webDriver: createTestMuWebDriver(host), connection: createTestMuConnection(host) }; -} diff --git a/packages/provider-testmu/tsconfig.json b/packages/provider-testmu/tsconfig.json index 81ccf03333..0a5a37e397 100644 --- a/packages/provider-testmu/tsconfig.json +++ b/packages/provider-testmu/tsconfig.json @@ -15,6 +15,9 @@ }, "include": ["src"], "references": [ + { + "path": "../build-config" + }, { "path": "../contracts" }, diff --git a/packages/provider-testmu/tsdown.config.ts b/packages/provider-testmu/tsdown.config.ts index 6173fbf90a..ff5b303a0c 100644 --- a/packages/provider-testmu/tsdown.config.ts +++ b/packages/provider-testmu/tsdown.config.ts @@ -1,19 +1 @@ -import { defineConfig } from 'tsdown'; - -export default defineConfig({ - entry: { plugin: 'src/plugin.ts', 'agent-device': 'src/index.ts' }, - outDir: 'dist', - format: 'esm', - platform: 'node', - target: 'es2022', - minify: true, - dts: false, - hash: false, - deps: { alwaysBundle: [/^@agent-device\//] }, - inputOptions: { - onLog(level, log, handler) { - if (log.code === 'UNRESOLVED_IMPORT') throw new Error(log.message); - handler(level, log); - }, - }, -}); +export { providerPluginBuildConfig as default } from '@agent-device/build-config'; diff --git a/packages/provider-tizen/package.json b/packages/provider-tizen/package.json index fa95e95a78..83691ebebd 100644 --- a/packages/provider-tizen/package.json +++ b/packages/provider-tizen/package.json @@ -1,6 +1,6 @@ { "name": "@agent-device/tizen", - "version": "0.21.39-dev", + "version": "0.22.0-dev", "type": "module", "description": "Samsung Tizen TV web app plugin for agent-device.", "files": [ diff --git a/packages/provider-webdriver/package.json b/packages/provider-webdriver/package.json index b5ed3a1528..8f6949059b 100644 --- a/packages/provider-webdriver/package.json +++ b/packages/provider-webdriver/package.json @@ -3,7 +3,7 @@ "version": "0.0.0", "private": true, "type": "module", - "description": "BrowserStack and AWS Device Farm WebDriver providers for agent-device. Internal workspace package bundled into the published artifact.", + "description": "Shared hosted-WebDriver engine for agent-device provider plugins. Internal workspace package bundled into the published artifact.", "dependencies": { "@agent-device/capture-kit": "workspace:*", "@agent-device/contracts": "workspace:*", @@ -12,10 +12,6 @@ "@agent-device/xml": "workspace:*" }, "exports": { - ".": { - "types": "./src/index.ts", - "default": "./src/index.ts" - }, "./providers": { "types": "./src/providers.ts", "default": "./src/providers.ts" @@ -24,10 +20,6 @@ "types": "./src/plugin.ts", "default": "./src/plugin.ts" }, - "./connection-verification": { - "types": "./src/connection-verification.ts", - "default": "./src/connection-verification.ts" - }, "./android-snapshot": { "types": "./src/webdriver-android-source.ts", "default": "./src/webdriver-android-source.ts" diff --git a/packages/provider-webdriver/src/aws-device-farm-profile-fields.test.ts b/packages/provider-webdriver/src/aws-device-farm-profile-fields.test.ts deleted file mode 100644 index 45efd819eb..0000000000 --- a/packages/provider-webdriver/src/aws-device-farm-profile-fields.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { test } from 'vitest'; -import assert from 'node:assert/strict'; -import { AWS_DEVICE_FARM_PROFILE_FIELDS } from './aws-device-farm.ts'; -import { consumedProfileFields } from './profile-fields.fixtures.ts'; - -test('AWS Device Farm consumes only its own fields and the session name', () => { - assert.deepEqual(consumedProfileFields(AWS_DEVICE_FARM_PROFILE_FIELDS), [ - 'awsAppArn', - 'awsDeviceArn', - 'awsInteractionMode', - 'awsProjectArn', - 'awsRegion', - 'providerSessionName', - ]); -}); diff --git a/packages/provider-webdriver/src/browserstack-provider.test.ts b/packages/provider-webdriver/src/browserstack-provider.test.ts deleted file mode 100644 index cfbff96988..0000000000 --- a/packages/provider-webdriver/src/browserstack-provider.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'vitest'; -import { browserStackProvider } from './browserstack-provider.ts'; -import type { CloudWebDriverProviderHost } from './provider-plugin.ts'; - -const HOST: CloudWebDriverProviderHost = { - env: { - BROWSERSTACK_USERNAME: 'user', - BROWSERSTACK_ACCESS_KEY: 'key', - BROWSERSTACK_WEBDRIVER_ENDPOINT: 'https://hub.test/wd/hub/', - }, - clientVersion: '1.2.3', - runHostCommand: async () => { - throw new Error('BrowserStack runs no host commands'); - }, -}; - -test('the declaration reserves the provider id and names the credential variables', () => { - assert.equal(browserStackProvider.declaration.provider, 'browserstack'); - assert.deepEqual(browserStackProvider.declaration.credentialVariables, [ - 'BROWSERSTACK_USERNAME', - 'BROWSERSTACK_ACCESS_KEY', - ]); - assert.equal(browserStackProvider.declaration.connection.usesCloudWebDriverLease, true); -}); - -test('the factory reads its hub endpoint from the environment and connects through the lazy callbacks', async () => { - const { webDriver, connection } = browserStackProvider.create(HOST); - assert.equal(webDriver.provider, 'browserstack'); - assert.equal(webDriver.endpoint, 'https://hub.test/wd/hub/'); - assert.equal(webDriver.profileFields.provider, 'browserstack'); - const { profile } = await connection.resolve({ - flags: { - json: false, - help: false, - version: false, - platform: 'ios', - device: 'iPhone 16', - providerOsVersion: '18.0', - providerApp: 'bs://app-id', - }, - cwd: '/', - }); - assert.equal(profile.leaseProvider, 'browserstack'); - assert.equal(profile.device, 'iPhone 16'); -}); diff --git a/packages/provider-webdriver/src/connection-verification.ts b/packages/provider-webdriver/src/connection-verification.ts deleted file mode 100644 index 6d9d6dd90e..0000000000 --- a/packages/provider-webdriver/src/connection-verification.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * The read-only provider checks `connect` runs before it saves a profile. Published as one subpath - * so a host can substitute every bundled verifier together, the way a plugin's own - * `connection-verification` subpath is substituted. - */ -export { verifyBrowserStackConnection } from './browserstack-connection-verification.ts'; -export { verifyAwsDeviceFarmConnection } from './aws-device-farm-connection-verification.ts'; diff --git a/packages/provider-webdriver/src/dependencies.ts b/packages/provider-webdriver/src/dependencies.ts deleted file mode 100644 index 95507f93e4..0000000000 --- a/packages/provider-webdriver/src/dependencies.ts +++ /dev/null @@ -1,13 +0,0 @@ -export type HostCommandResult = { - stdout: string; -}; - -export type RunHostCommand = ( - command: string, - args: readonly string[], -) => Promise; - -export type ProviderWebDriverDependencies = { - clientVersion: string; - runHostCommand: RunHostCommand; -}; diff --git a/packages/provider-webdriver/src/index-profile-fields.test.ts b/packages/provider-webdriver/src/index-profile-fields.test.ts deleted file mode 100644 index 636b49850b..0000000000 --- a/packages/provider-webdriver/src/index-profile-fields.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { test } from 'vitest'; -import assert from 'node:assert/strict'; -import { BUNDLED_CLOUD_WEBDRIVER_PROVIDERS } from './index.ts'; - -test('every bundled runtime reads the profile fields declared under its provider id', () => { - const host = { - env: {}, - clientVersion: 'test', - runHostCommand: async () => { - throw new Error('declarations need no host command'); - }, - }; - for (const bundled of BUNDLED_CLOUD_WEBDRIVER_PROVIDERS) { - const { webDriver } = bundled.create(host); - assert.equal(webDriver.provider, bundled.declaration.provider); - assert.equal(webDriver.profileFields.provider, bundled.declaration.provider); - } -}); diff --git a/packages/provider-webdriver/src/index.ts b/packages/provider-webdriver/src/index.ts deleted file mode 100644 index f284472929..0000000000 --- a/packages/provider-webdriver/src/index.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { awsDeviceFarmProvider } from './aws-device-farm-provider.ts'; -import { browserStackProvider } from './browserstack-provider.ts'; -import type { BundledCloudWebDriverProvider } from './provider-plugin.ts'; - -export type { RunHostCommand } from './dependencies.ts'; -export type { - BundledCloudWebDriverProvider, - CloudWebDriverConnection, - CloudWebDriverProviderHost, -} from './provider-plugin.ts'; - -/** - * The hosted WebDriver providers agent-device ships. Each presents the shape an installed plugin - * returns, so moving one out of the bundle is a packaging change, not a provider rewrite. - */ -export const BUNDLED_CLOUD_WEBDRIVER_PROVIDERS: readonly BundledCloudWebDriverProvider[] = - Object.freeze([browserStackProvider, awsDeviceFarmProvider]); - -export function bundledCloudWebDriverProvider( - provider: string | undefined, -): BundledCloudWebDriverProvider | undefined { - return BUNDLED_CLOUD_WEBDRIVER_PROVIDERS.find( - (bundled) => bundled.declaration.provider === provider, - ); -} diff --git a/packages/provider-webdriver/src/platform-runtime.test.ts b/packages/provider-webdriver/src/platform-runtime.test.ts index 21d5603747..1a8c8377a9 100644 --- a/packages/provider-webdriver/src/platform-runtime.test.ts +++ b/packages/provider-webdriver/src/platform-runtime.test.ts @@ -10,13 +10,12 @@ import { type CloudWebDriverCapabilityOverrides, } from './capabilities.ts'; import type { CloudWebDriverPlatform } from './runtime.ts'; -import { CLOUD_WEBDRIVER_PROVIDERS } from './providers.ts'; /** The declared map fact generation now reads. Defaults to a provider with no overrides. */ function capabilities( platform: CloudWebDriverPlatform = 'android', overrides?: CloudWebDriverCapabilityOverrides, - provider: string = CLOUD_WEBDRIVER_PROVIDERS.browserStack, + provider: string = 'aws-device-farm', ) { return createCloudWebDriverCapabilities({ provider, @@ -77,9 +76,9 @@ test('direct WebDriver refuses a live network dump instead of answering from ano test('a provider with no capture of its own states the same refusal for a live dump', async () => { const owner = createWebDriverPlatformRuntimeOwner({ host: host(async () => ({ stdout: '', stderr: '', exitCode: 0 })), - owner: providerRuntimeOwner(CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, 'android'), + owner: providerRuntimeOwner('aws-device-farm', 'android'), ownsDevice: () => true, - capabilities: capabilities('android', undefined, CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm), + capabilities: capabilities('android', undefined, 'aws-device-farm'), }); expect(await owner.inspectFacts({ ...device, id: 'aws-device-farm:lease-one' })).toMatchObject({ diff --git a/packages/provider-webdriver/src/plugin.ts b/packages/provider-webdriver/src/plugin.ts index 3d9faadfcd..4afc6a703a 100644 --- a/packages/provider-webdriver/src/plugin.ts +++ b/packages/provider-webdriver/src/plugin.ts @@ -10,8 +10,13 @@ export type { CloudWebDriverRuntimeOptions, CloudWebDriverPlatform, CloudWebDriverUploadApp, + CloudWebDriverPrepareSession, } from './runtime.ts'; -export type { CloudWebDriverProviderOptions } from './provider-plugin.ts'; + +/** The engine options a provider contributes; the host supplies `clientVersion`. */ +export type CloudWebDriverProviderOptions = Omit; + +export type { CloudWebDriverCapabilityOverrides } from './capabilities.ts'; export { appFileUploadForm, appendUrlPath, @@ -27,8 +32,10 @@ export { requireProviderDeviceOrientation, requireRequest, requireRequestPlatform, + releaseOnFailure, resolveHubAppReference, resolveLocalAppArtifact, } from './webdriver-utils.ts'; export { cloudArtifactsReadyOrPending, urlArtifactFromDetails } from './artifact-results.ts'; export { buildCloudWebDriverBaseCapabilities } from './capabilities.ts'; +export { sameOsVersion } from './webdriver-utils.ts'; diff --git a/packages/provider-webdriver/src/provider-plugin.ts b/packages/provider-webdriver/src/provider-plugin.ts deleted file mode 100644 index 7f31d2fab5..0000000000 --- a/packages/provider-webdriver/src/provider-plugin.ts +++ /dev/null @@ -1,69 +0,0 @@ -import type { CliFlags } from '@agent-device/contracts/command'; -import type { - CloudProviderProfileFields, - ProviderConnectionVerification, -} from '@agent-device/contracts/remote'; -import type { LeaseBackend } from '@agent-device/kernel/contracts'; -import type { ProviderWebDriverDependencies } from './dependencies.ts'; -import type { CloudWebDriverProviderDeclaration } from './providers.ts'; -import type { CloudWebDriverPlatform, CloudWebDriverRuntimeOptions } from './runtime.ts'; - -/** - * What a hosted WebDriver provider receives from the process that composes it. A bundled provider - * and an installed plugin see the same shape: the environment, the client version the shared - * engine stamps on provider requests, and a host-command runner for providers that drive a CLI. - */ -export type CloudWebDriverProviderHost = ProviderWebDriverDependencies & - Readonly<{ - env: Readonly>; - }>; - -/** The engine options a provider contributes; the host supplies `clientVersion`. */ -export type CloudWebDriverProviderOptions = Omit; - -/** - * The profile fields a provider contributes to a generated connection profile. The composing - * process adds connection identity, session defaults, and Metro settings, then persists it. - */ -export type CloudWebDriverConnectProfile = CloudProviderProfileFields & - Readonly<{ - leaseProvider: string; - leaseBackend?: LeaseBackend; - platform: CloudWebDriverPlatform; - device?: string; - }>; - -export type CloudWebDriverConnectionContext = Readonly<{ - flags: CliFlags; - cwd: string; -}>; - -export type CloudWebDriverConnectProfileResolution = { - profile: CloudWebDriverConnectProfile; - extraFlags?: Partial; -}; - -/** - * The `connect ` callbacks: validate flags into a profile, then verify it read-only. - * A bundled provider answers `resolve` asynchronously because it loads connect code on first use; - * a daemon composing the runtime never evaluates it. - */ -export type CloudWebDriverConnection = Readonly<{ - resolve( - context: CloudWebDriverConnectionContext, - ): Promise | CloudWebDriverConnectProfileResolution; - verify( - context: Pick, - ): Promise; -}>; - -export type CloudWebDriverProviderRegistration = Readonly<{ - webDriver: CloudWebDriverProviderOptions; - connection: CloudWebDriverConnection; -}>; - -/** A provider shipped inside agent-device: its manifest-shaped declaration plus its factory. */ -export type BundledCloudWebDriverProvider = Readonly<{ - declaration: CloudWebDriverProviderDeclaration; - create(host: CloudWebDriverProviderHost): CloudWebDriverProviderRegistration; -}>; diff --git a/packages/provider-webdriver/src/providers.ts b/packages/provider-webdriver/src/providers.ts index dd0e6c5a46..55b1941f7e 100644 --- a/packages/provider-webdriver/src/providers.ts +++ b/packages/provider-webdriver/src/providers.ts @@ -1,32 +1,6 @@ import type { ConnectionProviderCapabilities } from '@agent-device/contracts/remote'; -export const CLOUD_WEBDRIVER_PROVIDERS = { - browserStack: 'browserstack', - awsDeviceFarm: 'aws-device-farm', -} as const; - -export type CloudWebDriverKnownProviderName = - (typeof CLOUD_WEBDRIVER_PROVIDERS)[keyof typeof CLOUD_WEBDRIVER_PROVIDERS]; - -/** The environment variables that hold BrowserStack credentials. */ -export const BROWSERSTACK_CREDENTIAL_VARIABLES = { - username: 'BROWSERSTACK_USERNAME', - accessKey: 'BROWSERSTACK_ACCESS_KEY', -} as const; - -/** - * What a bundled provider declares before any of its code runs: the same fields an installed - * plugin publishes under `agentDevicePlugin` in its manifest. Connect policy and the credential - * fingerprint read this, never the provider implementation. - */ -export type CloudWebDriverProviderDeclaration = Readonly<{ - provider: CloudWebDriverKnownProviderName; - connection: ConnectionProviderCapabilities; - /** Absent for a provider whose credentials do not come from the environment. */ - credentialVariables?: readonly string[]; -}>; - -const HOSTED_WEBDRIVER_CONNECTION: ConnectionProviderCapabilities = { +export const HOSTED_WEBDRIVER_CONNECTION: ConnectionProviderCapabilities = { leaseKind: 'direct-device-provider', requiresAppAttachment: false, requiresRemoteDaemon: false, @@ -36,30 +10,6 @@ const HOSTED_WEBDRIVER_CONNECTION: ConnectionProviderCapabilities = { usesCloudWebDriverLease: true, }; -export const CLOUD_WEBDRIVER_PROVIDER_DECLARATIONS: readonly CloudWebDriverProviderDeclaration[] = - Object.freeze([ - { - provider: CLOUD_WEBDRIVER_PROVIDERS.browserStack, - connection: HOSTED_WEBDRIVER_CONNECTION, - credentialVariables: Object.values(BROWSERSTACK_CREDENTIAL_VARIABLES), - }, - { - // AWS Device Farm reads the AWS CLI credential chain, which no environment hash identifies. - provider: CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, - connection: { ...HOSTED_WEBDRIVER_CONNECTION, requiresAppAttachment: true }, - }, - ]); - -export function cloudWebDriverProviderDeclaration( - provider: string | undefined, -): CloudWebDriverProviderDeclaration | undefined { - return CLOUD_WEBDRIVER_PROVIDER_DECLARATIONS.find( - (declaration) => declaration.provider === provider, - ); -} - -const BROWSERSTACK_APP_SCHEME = 'bs://'; - /** * URI schemes are case-insensitive, but hosted hubs only match the lower-case spelling, so * `BS://id` is returned as `bs://id`. Anything without the lower-case `scheme` returns undefined. @@ -68,12 +18,3 @@ export function canonicalSchemeReference(app: string, scheme: string): string | if (app.slice(0, scheme.length).toLowerCase() !== scheme) return undefined; return `${scheme}${app.slice(scheme.length)}`; } - -export function canonicalBrowserStackAppReference(app: string): string | undefined { - return canonicalSchemeReference(app, BROWSERSTACK_APP_SCHEME); -} - -/** An id outside this grammar would pass every local check and fail only at session creation. */ -export function isBrowserStackAppReference(reference: string): boolean { - return /^bs:\/\/[\w.-]+$/.test(reference); -} diff --git a/packages/provider-webdriver/src/runtime-deployment.test.ts b/packages/provider-webdriver/src/runtime-deployment.test.ts index ce8b5f4c93..80c06e8b60 100644 --- a/packages/provider-webdriver/src/runtime-deployment.test.ts +++ b/packages/provider-webdriver/src/runtime-deployment.test.ts @@ -3,8 +3,8 @@ import path from 'node:path'; import { afterEach, expect, test, vi } from 'vitest'; import { createCloudWebDriverCapabilities } from './capabilities.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { createBrowserStackUploadApp } from './browserstack.ts'; import { mkdtempForTest } from './tmp-dir.fixtures.ts'; +import { appFileUploadForm, createHubUploadApp } from './webdriver-utils.ts'; import { createWebDriverDeploymentRuntime } from './runtime-deployment.ts'; import type { WebDriverProviderSession } from './runtime-session.ts'; import type { CloudWebDriverUploadApp } from './runtime.ts'; @@ -134,12 +134,13 @@ test('a hosted upload refuses a directory typed before any upload request', asyn globalThis.fetch = fetchSpy; const installApp = vi.fn(async () => undefined); const deployment = createWebDriverDeploymentRuntime({ - provider: 'browserstack', - uploadApp: createBrowserStackUploadApp({ - clientVersion: '0.0.0-test', - username: 'user', - accessKey: 'key', - endpoint: 'https://upload.example.test/app', + provider: 'webdriver-test', + uploadApp: createHubUploadApp(async (appPath) => { + await appFileUploadForm(appPath, 'file', { + provider: 'webdriver-test', + service: 'Hub', + }); + return 'hub://uploaded'; }), findSessionForDevice: () => activeSession(installApp), }); @@ -152,8 +153,8 @@ test('a hosted upload refuses a directory typed before any upload request', asyn ), ).rejects.toMatchObject({ code: 'INVALID_ARGS', - message: `BrowserStack can only upload a regular app file: ${installablePath}`, - details: expect.objectContaining({ provider: 'browserstack' }), + message: `Hub can only upload a regular app file: ${installablePath}`, + details: expect.objectContaining({ provider: 'webdriver-test' }), }); expect(fetchSpy).not.toHaveBeenCalled(); expect(installApp).not.toHaveBeenCalled(); diff --git a/packages/provider-webdriver/src/runtime.ts b/packages/provider-webdriver/src/runtime.ts index 601d54f1af..2583538cae 100644 --- a/packages/provider-webdriver/src/runtime.ts +++ b/packages/provider-webdriver/src/runtime.ts @@ -117,8 +117,6 @@ export function createCloudWebDriverRuntime( return new CloudWebDriverRuntimeImplementation(options); } -export { buildCloudWebDriverBaseCapabilities } from './capabilities.ts'; - /** Public façade: provider wiring stays small while session/deployment mechanics stay focused. */ class CloudWebDriverRuntimeImplementation implements CloudWebDriverRuntime { readonly provider: string; diff --git a/packages/provider-webos/package.json b/packages/provider-webos/package.json index 88b5b7892a..b00eea3445 100644 --- a/packages/provider-webos/package.json +++ b/packages/provider-webos/package.json @@ -1,6 +1,6 @@ { "name": "@agent-device/webos", - "version": "0.21.39-dev", + "version": "0.22.0-dev", "type": "module", "description": "LG webOS TV web app plugin for agent-device.", "files": [ diff --git a/packages/proxy/package.json b/packages/proxy/package.json index 7af4cf2294..ed15c4118e 100644 --- a/packages/proxy/package.json +++ b/packages/proxy/package.json @@ -1,6 +1,6 @@ { "name": "@agent-device/proxy", - "version": "0.21.39-dev", + "version": "0.22.0-dev", "type": "module", "description": "Transport-neutral authenticating proxy in front of an agent-device daemon.", "license": "MIT", @@ -31,7 +31,8 @@ "devDependencies": { "@agent-device/contracts": "workspace:*", "@agent-device/host-kit": "workspace:*", - "@agent-device/kernel": "workspace:*" + "@agent-device/kernel": "workspace:*", + "@agent-device/build-config": "workspace:*" }, "publishConfig": { "exports": { diff --git a/packages/proxy/tsconfig.json b/packages/proxy/tsconfig.json index 247a915b90..a504c0acb5 100644 --- a/packages/proxy/tsconfig.json +++ b/packages/proxy/tsconfig.json @@ -10,5 +10,18 @@ "tsBuildInfoFile": "./dist-types/index.tsbuildinfo" }, "include": ["src"], - "references": [{ "path": "../contracts" }, { "path": "../host-kit" }, { "path": "../kernel" }] + "references": [ + { + "path": "../build-config" + }, + { + "path": "../contracts" + }, + { + "path": "../host-kit" + }, + { + "path": "../kernel" + } + ] } diff --git a/packages/proxy/tsdown.config.ts b/packages/proxy/tsdown.config.ts index 2b4fe28c98..67dedb454d 100644 --- a/packages/proxy/tsdown.config.ts +++ b/packages/proxy/tsdown.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from 'tsdown'; +import { strictBundlerInputOptions } from '@agent-device/build-config'; const typeScriptPackageJsonUrl = import.meta.resolve('typescript/package.json'); const { default: getTypeScript7ExePath } = await import( @@ -15,10 +16,5 @@ export default defineConfig({ dts: { tsgo: { path: getTypeScript7ExePath() } }, hash: false, deps: { alwaysBundle: [/^@agent-device\//] }, - inputOptions: { - onLog(level, log, handler) { - if (log.code === 'UNRESOLVED_IMPORT') throw new Error(log.message); - handler(level, log); - }, - }, + inputOptions: strictBundlerInputOptions, }); diff --git a/packages/remote/src/remote-config-core.ts b/packages/remote/src/remote-config-core.ts index f5913ebb6c..38a1bc518d 100644 --- a/packages/remote/src/remote-config-core.ts +++ b/packages/remote/src/remote-config-core.ts @@ -5,19 +5,13 @@ import { getRemoteConfigEnvNames, getRemoteConfigFieldSpec, type RemoteConfigProfile, + type RemoteConfigProfileOptions, type ResolvedRemoteConfigProfile, } from './remote-config-schema.ts'; import { AppError } from '@agent-device/kernel/errors'; import { resolveUserPath } from '@agent-device/host-kit/file'; import { parseSourceValue, type EnvMap } from '@agent-device/kernel/source-value'; -/** The remote-config location and the host environment it resolves against. */ -export type HostRemoteConfigProfileOptions = { - configPath: string; - cwd: string; - env: EnvMap; -}; - // Deliberately narrower than `resolveRemoteConfigProfile`: this reads only // what the config *file itself* declares, with no ambient environment // defaults merged in. Callers that need to know a credential provably @@ -25,7 +19,7 @@ export type HostRemoteConfigProfileOptions = { // somewhere") must use this, not the env-merged resolver, or provenance is // lost — an env var is global and cannot say which endpoint it belongs to. export function readRemoteConfigFile( - options: HostRemoteConfigProfileOptions, + options: RemoteConfigProfileOptions, ): ResolvedRemoteConfigProfile { const { env } = options; const resolvedPath = resolveRemoteConfigPath(options); @@ -117,13 +111,13 @@ function mergeRemoteConfigProfile( return merged; } -export function resolveRemoteConfigPath(options: HostRemoteConfigProfileOptions): string { +export function resolveRemoteConfigPath(options: RemoteConfigProfileOptions): string { const { env } = options; return resolveUserPath(options.configPath, { cwd: options.cwd, env }); } export function resolveRemoteConfigProfile( - options: HostRemoteConfigProfileOptions, + options: RemoteConfigProfileOptions, ): ResolvedRemoteConfigProfile { const loaded = readRemoteConfigFile(options); return { diff --git a/packages/remote/src/remote-config-schema.ts b/packages/remote/src/remote-config-schema.ts index 517a0931d2..b11fecc44b 100644 --- a/packages/remote/src/remote-config-schema.ts +++ b/packages/remote/src/remote-config-schema.ts @@ -13,7 +13,7 @@ import { PLATFORM_SELECTORS } from '@agent-device/kernel/device'; export type RemoteConfigProfileOptions = { configPath: string; cwd: string; - env?: Record; + env: Record; }; export type ResolvedRemoteConfigProfile = { diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index 93ffa02f48..be0875dbf8 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -30,6 +30,7 @@ import { leaseScopeToCommandFlags, leaseScopeToConnectionMetadata, parseLeaseDeviceKey, + remoteSessionRequiredError, } from '@agent-device/contracts/lease-scope'; export type RemoteConnectionState = { @@ -453,19 +454,6 @@ export function requireLeasedConnectionSession( throw remoteSessionRequiredError(connection.leaseProvider); } -/** The refusal for a command on a leased connection that names no session. */ -export function remoteSessionRequiredError(leaseProvider: string | undefined): AppError { - return new AppError( - 'INVALID_ARGS', - 'A leased remote connection needs its session named: pass --session or set AGENT_DEVICE_SESSION.', - { - reason: 'REMOTE_SESSION_REQUIRED', - ...(leaseProvider === undefined ? {} : { leaseProvider }), - hint: "Without a name, a command could reach another agent's connection on this machine.", - }, - ); -} - function isLeasedConnection(connection: Pick): boolean { return connection.leaseProvider !== undefined; } diff --git a/packages/replay-port/package.json b/packages/replay-port/package.json index 44b00d2069..6a9de03d98 100644 --- a/packages/replay-port/package.json +++ b/packages/replay-port/package.json @@ -6,7 +6,6 @@ "type": "module", "description": "Daemon-side replay port: the adapter over the ad-replay, ad-script and replay-test engines.", "dependencies": { - "@agent-device/ad-replay": "workspace:*", "@agent-device/ad-script": "workspace:*", "@agent-device/capture-kit": "workspace:*", "@agent-device/command-registry": "workspace:*", @@ -14,10 +13,9 @@ "@agent-device/device-selection": "workspace:*", "@agent-device/host-kit": "workspace:*", "@agent-device/kernel": "workspace:*", - "@agent-device/maestro": "workspace:*", - "@agent-device/replay-test": "workspace:*", "@agent-device/selectors": "workspace:*", - "@agent-device/session-journal": "workspace:*" + "@agent-device/session-journal": "workspace:*", + "@agent-device/plugins": "workspace:*" }, "exports": { "./command-types": { @@ -139,6 +137,10 @@ "./source-discovery": { "types": "./src/source-discovery.ts", "default": "./src/source-discovery.ts" + }, + "./replay-plugin-admission": { + "types": "./src/daemon-port/replay-plugin-admission.ts", + "default": "./src/daemon-port/replay-plugin-admission.ts" } }, "devDependencies": { diff --git a/packages/replay-port/src/__tests__/script-source-bundle.test.ts b/packages/replay-port/src/__tests__/script-source-bundle.test.ts index 0ab47f9274..9664ad4d92 100644 --- a/packages/replay-port/src/__tests__/script-source-bundle.test.ts +++ b/packages/replay-port/src/__tests__/script-source-bundle.test.ts @@ -16,7 +16,11 @@ test('a native .ad bundle carries the entry script resolved against the caller c const script = 'open "Demo"\nclick "Save"\n'; fs.writeFileSync(path.join(root, 'flow.ad'), script); - const bundle = await loadReplayScriptSourceBundle({ inputPath: './flow.ad', cwd: root }); + const bundle = await loadReplayScriptSourceBundle({ + hostEnv: process.env, + inputPath: './flow.ad', + cwd: root, + }); expect(bundle.entry).toBe(path.join(root, 'flow.ad')); expect(bundle.files).toEqual({ [path.join(root, 'flow.ad')]: script }); @@ -33,6 +37,7 @@ test('a Maestro bundle carries the entry flow and its transitive runFlow include fs.writeFileSync(path.join(root, 'tail.yaml'), '---\n- back\n'); const bundle = await loadReplayScriptSourceBundle({ + hostEnv: process.env, inputPath: './flow.yaml', cwd: root, replayBackend: 'maestro', @@ -54,7 +59,11 @@ test('a missing entry script fails as INVALID_ARGS naming the path as typed', as const root = mkdtempForTestSync('agent-device-bundle-missing-'); await expect( - loadReplayScriptSourceBundle({ inputPath: './flows/login.ad', cwd: root }), + loadReplayScriptSourceBundle({ + hostEnv: process.env, + inputPath: './flows/login.ad', + cwd: root, + }), ).rejects.toThrow( expect.objectContaining({ code: 'INVALID_ARGS', @@ -70,7 +79,9 @@ test('an oversized bundle is refused with the limit named', async () => { `open "Demo"\n${'#'.repeat(REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES)}\n`, ); - await expect(loadReplayScriptSourceBundle({ inputPath: './flow.ad', cwd: root })).rejects.toThrow( + await expect( + loadReplayScriptSourceBundle({ hostEnv: process.env, inputPath: './flow.ad', cwd: root }), + ).rejects.toThrow( expect.objectContaining({ code: 'INVALID_ARGS', message: expect.stringContaining(`over the ${REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES}-byte`), diff --git a/packages/replay-port/src/daemon-port/__tests__/replay-backend-registry.test.ts b/packages/replay-port/src/daemon-port/__tests__/replay-backend-registry.test.ts index a907928087..238784af79 100644 --- a/packages/replay-port/src/daemon-port/__tests__/replay-backend-registry.test.ts +++ b/packages/replay-port/src/daemon-port/__tests__/replay-backend-registry.test.ts @@ -1,50 +1,63 @@ -import { expect, test, vi } from 'vitest'; -import { maestroReplayBackendDeclaration } from '@agent-device/maestro/replay-backend-declaration'; +import { getReplayPluginInstallation } from '@agent-device/ad-script'; +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; import { getReplayBackendDeclaration } from '../replay-backend-declarations.ts'; -import { getReplayBackend } from '../replay-backend-registry.ts'; +import { getReplayBackend, openReplayBackend } from '../replay-backend-registry.ts'; +import { pluginHome, selectV2Plugin } from '@agent-device/test-kit'; -// The #3377 extraction seam: the registry is the only host-side door to a non-native engine, so -// what it promises is exactly what the plugin swap must keep — the load-once contract and the -// capability shape every host call site routes through. - -test('lists the Maestro declaration for the maestro id', () => { - expect(getReplayBackendDeclaration('maestro')).toBe(maestroReplayBackendDeclaration); +test('help declares the exact optional package without requiring a working plugin', () => { + expect( + getReplayBackendDeclaration( + getReplayPluginInstallation('maestro'), + getReplayPluginInstallation('ad'), + ), + ).toMatchObject({ + id: 'maestro', + package: '@agent-device/maestro', + }); }); -test('memoizes the backend so a process evaluates the engine once', async () => { - const first = getReplayBackend('maestro'); - const second = getReplayBackend('maestro'); - expect(second).toBe(first); - expect(await second).toBe(await first); +test('the runtime registry memoizes the installed backend capabilities', async () => { + const first = await getReplayBackend('maestro'); + expect(await getReplayBackend('maestro')).toBe(first); + expect(first.inspectSource('appId: com.example.app\n---\n- launchApp\n', 'flow.yaml')).toEqual({ + title: undefined, + appTarget: 'com.example.app', + }); }); -test('a backend carries every capability the host routes through it', async () => { - const backend = await getReplayBackend('maestro'); - expect(backend.id).toBe('maestro'); - expect(Object.keys(backend).sort()).toEqual( - ['collectSourceFiles', 'exportReplayScript', 'id', 'inspectSource', 'runReplay'].sort(), +test('client replay absence does not evaluate unrelated provider packages', async () => { + const { home, env } = pluginHome(); + const evaluated = path.join(home, 'provider-evaluated'); + selectV2Plugin( + home, + '@example/unrelated', + `import fs from 'node:fs'; + fs.writeFileSync(${JSON.stringify(evaluated)}, 'evaluated'); + throw new Error('Unrelated provider import');`, ); + await expect(openReplayBackend('maestro', { env, cwd: '/' })).rejects.toMatchObject({ + details: { + reason: 'plugin-not-installed', + package: '@agent-device/maestro', + installCommand: 'agent-device plugins add @agent-device/maestro', + }, + }); + expect(fs.existsSync(evaluated)).toBe(false); }); -test('a failed load is not cached, so the next call retries it', async () => { - // The mutation that makes this fail: without the registry's delete-on-rejection, the rejected - // promise stays memoized and this second resolution rejects forever, where the pre-registry - // per-call `import()` recovered from a one-off load failure. A fresh registry instance keeps - // the memo map free of the successes above. - vi.resetModules(); - let loadAttempts = 0; - vi.doMock('@agent-device/maestro/replay-backend', () => ({ - // The loader reads the plugin export right after the `import()`, so failing the first read - // fails the load exactly like a rejecting module evaluation would. - get maestroReplayBackendPlugin() { - loadAttempts += 1; - if (loadAttempts === 1) throw new Error('transient load failure'); - return { create: () => ({ id: 'maestro' }) }; - }, - })); - const { getReplayBackend: freshGet } = await import('../replay-backend-registry.ts'); - await expect(freshGet('maestro')).rejects.toThrow('transient load failure'); - await expect(freshGet('maestro')).resolves.toMatchObject({ id: 'maestro' }); - expect(loadAttempts).toBe(2); - vi.doUnmock('@agent-device/maestro/replay-backend'); +test('an unbound daemon runtime never borrows another runtime or the client store', async () => { + const isolated = createRuntimeStateHandle(); + try { + await isolated.run( + async () => + await expect(getReplayBackend('maestro')).rejects.toMatchObject({ + details: { reason: 'plugin-not-installed' }, + }), + ); + } finally { + isolated.dispose(); + } }); diff --git a/packages/replay-port/src/daemon-port/native-command.ts b/packages/replay-port/src/daemon-port/native-command.ts index 607ae8e22a..e4371b85af 100644 --- a/packages/replay-port/src/daemon-port/native-command.ts +++ b/packages/replay-port/src/daemon-port/native-command.ts @@ -1,5 +1,5 @@ import { normalizeError } from '@agent-device/kernel/errors'; -import { runAdReplay } from '@agent-device/ad-replay'; +import { getReplayExecution } from './replay-backend-registry.ts'; import type { SnapshotTimingSample } from '@agent-device/contracts/capture'; import { summarizeSnapshotTimingSamples } from '@agent-device/contracts/capture'; import type { ReplayCommandResult } from '@agent-device/contracts/replay'; @@ -88,7 +88,9 @@ export async function runReplayCommand(command: ReplayCommand): Promise; -} = { - maestro: maestroReplayBackendDeclaration, -}; +export const MAESTRO_COMPAT_SUPPORTED_CAPABILITIES = [ + 'Flows: launchApp (with clearState, permissions, and Apple-only launch arguments; permissions apply after state clearing but before launch, and a launchApp without permissions touches nothing — there is no silent all: allow default); setPermissions (mid-flow permission grants, denials, and resets; all resolves in the backend — one simctl call on iOS, the declared permissions on Android — with specific entries overriding after it); runFlow file/inline; runFlow.when and repeat.while conditions (platform, visible, notVisible, and true, all re-evaluated before every repeat iteration); onFlowStart/onFlowComplete; repeat with times, while, or both; and retry.', + 'Interactions: tapOn, doubleTapOn, longPressOn, inputText on the focused element, eraseText (up to 10000 characters), openLink, hideKeyboard, basic pressKey, and back; selector targets poll until available and support recursive index, childOf, above, below, leftOf, rightOf, containsChild, containsDescendants, points, and optional; outer command labels are metadata, not target selectors.', + 'Assertions and navigation: assertVisible, assertNotVisible, assertTrue (literal values and ${VAR} lookups only; "", "false", "0", "null", and "undefined" are falsy, everything else is truthy), extendedWaitUntil, scroll, scrollUntilVisible, absolute/percentage/target swipe, takeScreenshot, waitForAnimationToEnd, clearState, stopApp, and killApp (system-initiated process death: am kill on ADB-backed Android devices, which refuse a foreground target with android-kill-requires-background-app — background the app first, for example pressKey: Home — and fail a target whose process survives with android-kill-process-survived; iOS, Limrun, and WebDriver-provider backends run it as stopApp).', + 'Scripts: ordered runScript file/env scripts with http.post, json, and output variables; evalScript inline expressions run flow-scoped JavaScript and write output.* leaves for later steps.', +] as const; + +export const MAESTRO_COMPAT_LIMITATIONS = [ + 'Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict: current runtimes refuse a targeted notifications change and leave notifications untouched under all.', + 'Runtime: iOS and Android only; launchApp.clearState and standalone clearState support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading - unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported.', + 'Expressions: evalScript and condition true: fields (runFlow.when and repeat.while share one evaluator) are evaluated as JavaScript (flow env and prior output leaves are string-typed); a true: field that is a boolean, a maestro.platform comparison, or plain literal text after ${VAR} lookups is decided without JavaScript, with the assertTrue falsy table for literal text. Other fields stay literal or ${VAR} lookup-only — assertTrue supports literals and bare lookups, and other expression-shaped payloads fail loud.', + 'Environment: flow env is the default, AD_VAR_* overrides it, and CLI -e KEY=VALUE wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and AD_* stays reserved.', + 'Failure diagnostics: resolved targets and runFlow paths are rendered, while inputText payloads remain hidden; do not place secrets in diagnostic identifiers.', + 'Trust: runScript, evalScript, and JavaScript condition true: fields execute flow scripts via node:vm, which is not a security sandbox. runScript runs in a daemon child process with a 30 s script budget. It may make http.post network requests (30 s each, response bodies up to 8 MiB), and its output keys cannot contain a dot. Remote flows refuse runScript before reading its file, including files supplied in the replay bundle, and refuse evalScript and true: fields that need JavaScript. Run these scripts only in trusted local flows. Local runScript paths refer to the daemon filesystem: relative paths resolve from the containing flow, and absolute paths and symlinks are allowed.', + 'Remote screenshots: takeScreenshot uses a daemon-generated path and reports that path in artifactPaths. The flow cannot choose a file destination on the daemon host. Animation waits and tap retry comparisons use temporary screenshots that are removed after comparison.', + 'Errors and tracking: unsupported commands and fields fail with source context when available; open a focused issue only when implementation work is planned.', +] as const; + +const MAESTRO_COMPATIBILITY_ADR_URL = + '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/callstack/agent-device/blob/main/docs/adr/0015-direct-maestro-engine.md'; + +const MAESTRO_COMPATIBILITY_ISSUE_URL = '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/callstack/agent-device/issues/new'; + +function formatMaestroCompatibilityReference(): string { + return [ + 'Supported subset:', + ...MAESTRO_COMPAT_SUPPORTED_CAPABILITIES.map((capability) => ` - ${capability}`), + '', + 'Boundaries:', + ...MAESTRO_COMPAT_LIMITATIONS.map((limitation) => ` - ${limitation}`), + ].join('\n'); +} + +/** Full compatibility help is composed only by help consumers, from the vetted installation. */ export function getReplayBackendDeclaration( - id: ReplayBackendId, -): ReplayBackendDeclaration { - return REPLAY_BACKEND_DECLARATIONS[id]; + installation: ReturnType, + suiteInstallation: ReturnType, +): ReplayBackendDeclaration { + const body = + installation.id === 'ad' + ? `Run agent-device plugins add ${installation.package} on the daemon host for native .ad replay and all test suites. Existing scripts and arguments stay the same. Ordinary open/close --save-script recording stays in core. Restart the daemon after changing plugins, then retry the original invocation with all its arguments.` + : `agent-device help maestro + +Install with agent-device plugins add ${installation.package}. ${installation.installationHint} + +For test suites, also run agent-device plugins add ${suiteInstallation.package}. ${suiteInstallation.installationHint} + +Restart the daemon after installing the required plugins. + +Run Maestro compatibility flows with replay --maestro or test --maestro. Bind an iOS or Android target with --platform or an existing session. + +${formatMaestroCompatibilityReference()} + +Unsupported syntax fails loudly rather than being skipped. Architecture, performance tradeoffs, and declared conformance divergences: ${MAESTRO_COMPATIBILITY_ADR_URL} +Focused compatibility request: ${MAESTRO_COMPATIBILITY_ISSUE_URL}`; + return { + id: installation.id, + package: installation.package, + installationHint: installation.installationHint, + help: { summary: installation.summary, body }, + }; +} + +/** Installation guidance uses the same vetted package declaration as missing-plugin errors. */ +export function replayPluginInstallHelp( + installation: ReturnType, +): string { + return `${installation.summary} (plugin, install separately). Run agent-device plugins add ${installation.package}. ${installation.installationHint}`; } diff --git a/packages/replay-port/src/daemon-port/replay-backend-failure.ts b/packages/replay-port/src/daemon-port/replay-backend-failure.ts index d632c3f12c..bc2b64faf7 100644 --- a/packages/replay-port/src/daemon-port/replay-backend-failure.ts +++ b/packages/replay-port/src/daemon-port/replay-backend-failure.ts @@ -4,7 +4,7 @@ import { REPLAY_DIVERGENCE_SUGGESTION_LIMIT, createReplayDivergenceSanitizer, type ReplayVarScrubEntry, -} from '@agent-device/ad-replay/divergence'; +} from '@agent-device/contracts/replay-divergence-data'; import { getRequestSignal } from '@agent-device/host-kit/request'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { computeReplayRepairHint } from './repair-hint.ts'; diff --git a/packages/replay-port/src/daemon-port/replay-backend-host.ts b/packages/replay-port/src/daemon-port/replay-backend-host.ts index 2d9e6aa1e0..4729556108 100644 --- a/packages/replay-port/src/daemon-port/replay-backend-host.ts +++ b/packages/replay-port/src/daemon-port/replay-backend-host.ts @@ -1,4 +1,13 @@ +import { runCmd, withCommandHost } from '@agent-device/host-kit/command'; +import { + emitDiagnostic, + registerDiagnosticSensitiveValue, +} from '@agent-device/host-kit/diagnostics'; import type { ReplayBackendHost } from '@agent-device/contracts/replay-backend'; +import { + assertSnapshotScreenOrigin, + readSnapshotClickabilityEvidence, +} from '@agent-device/contracts/capture'; import { resolveTargetDevice } from '@agent-device/device-selection/dispatch-resolve'; import { getRequestSignal } from '@agent-device/host-kit/request'; import { buildReplayBuiltinVars } from '../session-replay-vars.ts'; @@ -16,6 +25,14 @@ import { appendReplayTraceEvent } from './session-replay-trace.ts'; */ export function createReplayBackendHost(): ReplayBackendHost { return { + emitDiagnostic, + readSnapshotClickabilityEvidence, + assertSnapshotScreenOrigin, + runCommand: ({ executable, args, host, ...options }, signal) => + withCommandHost({ host, requestEnv: undefined }, () => + runCmd(executable, args, { ...options, ...host, signal }), + ), + registerSensitiveValue: registerDiagnosticSensitiveValue, appendTraceEvent: appendReplayTraceEvent, buildBuiltinVars: (params) => buildReplayBuiltinVars({ ...params, metadata: {} }), readScriptSourceFile: readReplayScriptSourceFile, diff --git a/packages/replay-port/src/daemon-port/replay-backend-registry.ts b/packages/replay-port/src/daemon-port/replay-backend-registry.ts index e5d2cc3d42..5811900a96 100644 --- a/packages/replay-port/src/daemon-port/replay-backend-registry.ts +++ b/packages/replay-port/src/daemon-port/replay-backend-registry.ts @@ -1,64 +1,134 @@ -import type { ReplayBackendId } from '@agent-device/ad-script'; -import type { ReplayBackend, ReplayBackendPlugin } from '@agent-device/contracts/replay-backend'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import type { + ReplayExecution, + ReplayExecutionResolver, +} from '@agent-device/contracts/replay-execution'; +import type { ReplayBackendId, ReplayFormat } from '@agent-device/ad-script'; +import type { ReplayBackend, ReplayBackendResolver } from '@agent-device/contracts/replay-backend'; +import type { AppError } from '@agent-device/kernel/errors'; -/** - * The replay backend registry (#3377). - * - * The host (the replay command, `test` discovery, request device binding, and the client-side - * replay surface) reaches a non-native engine only through this module. A backend id resolves to - * one plugin (`ReplayBackendPlugin`, `create(host)`) whose loading is memoized per process; this - * module and `replay-backend-declarations.ts` are the only host code that names an engine package. Backend ids come from the format grammar's vocabulary - * (`@agent-device/ad-script`), so the registry's keys and the `--maestro` flag's accepted values - * can never drift apart. The Maestro plugin extraction (#3377) swaps the builtin - * table for an installed-plugin lookup and changes no caller. - * - * A backend is a capability bundle over scripts: it expands a source closure, inspects a flow for - * scheduling metadata, runs a replay, and converts a native `.ad` script into its own format. - * Dispatch, session, and wire policy stay on this side — a backend receives an already-prepared - * command and returns an ordinary `DaemonResponse`, so the daemon never re-enters engine parsing - * or compatibility dispatch (ADR 0015). - * - * A hub eager-closure rule of this repository (`scripts/__tests__/eager-closure-budgets.ts`) - * holds `src/cli.ts` and `src/daemon.ts` to "no new module evaluated at startup", so the host's - * value imports of this module are function-scoped `await import()` calls at the few call sites; - * the plugin, its declaration, and the host behind it are reached the same way. Type imports are - * free. - */ +const backendResolverKey = Symbol('replay-backend-resolver'); +async function binding() { + const { runtimeSlot } = await import('@agent-device/host-kit/runtime-slots'); + return runtimeSlot(backendResolverKey, () => ({ + resolve: undefined as ReplayBackendResolver | undefined, + execution: undefined as ReplayExecutionResolver | undefined, + })); +} + +/** Binds the fixed plugin set of the current daemon runtime. Its registry owns disposal. */ +export async function bindReplayBackendResolver( + resolve: ReplayBackendResolver, + execution?: ReplayExecutionResolver, +): Promise { + Object.assign(await binding(), { resolve, execution }); +} -/** - * Builtin registrations: the ONE extraction seam. Each loader is a function-scoped `import()` so - * no host entry evaluates an engine eagerly (the `cli-startup-import-closure` pins). Extraction - * swaps this table for the installed-plugin lookup; the host call sites never change. - */ -const BUILTIN_REPLAY_BACKEND_PLUGINS: { - readonly [TId in ReplayBackendId]: () => Promise>; -} = { - maestro: async () => - (await import('@agent-device/maestro/replay-backend')).maestroReplayBackendPlugin, -}; +/** Resolves native replay and suite execution from this runtime's fixed plugin set. */ +export async function getReplayExecution(): Promise { + const state = await binding(); + if (!state.execution) throw await missingReplayBackend('ad'); + try { + return await state.execution(await backendPackage('ad')); + } catch (error) { + throw await recoverReplayPluginError('ad', error); + } +} -const loadedBackends = new Map>>(); +async function recoverReplayPluginError(id: ReplayFormat, error: unknown): Promise { + const { AppError } = await import('@agent-device/kernel/errors'); + if (!(error instanceof AppError) || error.details?.reason !== 'plugin-not-installed') + return error; + return await missingReplayBackend(id); +} + +/** Resolves against the current daemon's plugins, without consulting another host's store. */ +export async function getReplayBackend(id: ReplayBackendId): Promise { + const { resolve } = await binding(); + if (!resolve) throw await missingReplayBackend(id); + return await resolveBackend(id, resolve); +} -async function createReplayBackend(id: ReplayBackendId): Promise> { - const plugin = await BUILTIN_REPLAY_BACKEND_PLUGINS[id](); +async function resolveBackend( + id: ReplayBackendId, + resolve: ReplayBackendResolver, +): Promise { const { createReplayBackendHost } = await import('./replay-backend-host.ts'); - return plugin.create(createReplayBackendHost()); + try { + return await resolve(id, createReplayBackendHost(), await backendPackage(id)); + } catch (error) { + throw await recoverReplayPluginError(id, error); + } } -/** - * Resolves a backend once per process, memoizing the engine's single evaluation. A load failure - * is NOT cached — a failed `import()` stays retryable, as it was at the pre-registry call sites - * that imported fresh per invocation. The id's type is the grammar's `isReplayBackendId` guard, so - * an unregistered value is rejected by the caller before it reaches here; engines never fall back - * to one another. - */ -export function getReplayBackend(id: ReplayBackendId): Promise> { - const cached = loadedBackends.get(id); - if (cached) return cached; - const loading = createReplayBackend(id).catch((error: unknown) => { - loadedBackends.delete(id); +/** Uses the embedded registry, or owns a client-side store scope until the task settles. */ +export async function withReplayBackend( + id: ReplayBackendId, + host: HostEnvironment, + run: (backend: ReplayBackend) => Promise | T, + resolve?: ReplayBackendResolver, +): Promise { + if (resolve) return await run(await resolveBackend(id, resolve)); + const scope = await openReplayBackend(id, host); + try { + return await run(scope.backend); + } finally { + await scope.close(); + } +} + +/** A client/tooling scope owns its plugin registry until close. It never starts providers. */ +export async function openReplayBackend(id: ReplayBackendId, host: HostEnvironment) { + const { AppError } = await import('@agent-device/kernel/errors'); + const packageName = await backendPackage(id); + const [{ storePluginCandidates }, { resolveProviderPlugins, startProviderRegistry }] = + await Promise.all([ + import('@agent-device/plugins/store'), + import('@agent-device/plugins/registry'), + ]); + const registry = await startProviderRegistry( + await resolveProviderPlugins( + (await storePluginCandidates(host.env)).filter( + (candidate) => candidate.package === packageName, + ), + ), + host, + { + adaptWebDriver: async () => { + throw new AppError('INVALID_ARGS', 'Client replay scope cannot start a provider'); + }, + }, + 'replay-backends', + ); + try { + const { createReplayBackendHost } = await import('./replay-backend-host.ts'); + const backend = await registry.resolveReplayBackend(id, createReplayBackendHost(), packageName); + return { backend, close: registry.close }; + } catch (error) { + await registry.close(); + if (error instanceof AppError && error.details?.reason === 'plugin-not-installed') + throw await missingReplayBackend(id); throw error; - }); - loadedBackends.set(id, loading); - return loading; + } +} + +async function missingReplayBackend(id: ReplayFormat): Promise { + const { AppError } = await import('@agent-device/kernel/errors'); + const packageName = await backendPackage(id); + const installCommand = `agent-device plugins add ${packageName}`; + return new AppError( + 'INVALID_ARGS', + `Replay backend ${id} requires ${packageName}. Run ${installCommand}, then retry the original command with all its arguments.`, + { + reason: 'plugin-not-installed', + backend: id, + package: packageName, + installCommand, + hint: `${(await import('@agent-device/ad-script')).getReplayPluginInstallation(id).installationHint} Restart the daemon after changing plugins; retry the original command with all its arguments.`, + }, + ); +} + +async function backendPackage(id: ReplayFormat): Promise { + return (await import('@agent-device/ad-script')).getReplayPluginInstallation(id).package; } diff --git a/packages/replay-port/src/daemon-port/replay-plugin-admission.ts b/packages/replay-port/src/daemon-port/replay-plugin-admission.ts new file mode 100644 index 0000000000..6ae7eed784 --- /dev/null +++ b/packages/replay-port/src/daemon-port/replay-plugin-admission.ts @@ -0,0 +1,48 @@ +import type { ReplayBackendId } from '@agent-device/ad-script'; +import type { DaemonWireRequest } from '@agent-device/contracts/command'; +import { AppError } from '@agent-device/kernel/errors'; +import { getReplayBackend, getReplayExecution } from './replay-backend-registry.ts'; + +/** Rejects unavailable execution before request binding can select or act on a device. */ +export async function requireReplayPlugins(request: DaemonWireRequest): Promise { + const { isReplayBackendId, unsupportedReplayBackendMessage } = + await import('@agent-device/ad-script'); + const backend = request.flags?.replayBackend; + if (backend !== undefined && !isReplayBackendId(backend)) + throw new AppError('INVALID_ARGS', unsupportedReplayBackendMessage(backend)); + if (request.command === 'test') await requireReplayTestPlugins(request, backend); + else if (request.command === 'replay') await requireReplayEntryPlugin(request, backend); +} + +async function requireReplayTestPlugins( + request: DaemonWireRequest, + backend: ReplayBackendId | undefined, +): Promise { + const { resolveReplayFormat, isMaestroYamlPath, maestroBackendRequiredMessage } = + await import('@agent-device/ad-script'); + const entry = request.flags?.replayScriptSources?.find((source) => + isMaestroYamlPath(source.entry), + )?.entry; + if (entry !== undefined && backend !== 'maestro') + throw new AppError('INVALID_ARGS', maestroBackendRequiredMessage('test', entry)); + await getReplayExecution(); + if ( + request.flags?.replayScriptSources?.some( + (source) => resolveReplayFormat(source.entry, backend) === 'maestro', + ) + ) + await getReplayBackend('maestro'); +} + +async function requireReplayEntryPlugin( + request: DaemonWireRequest, + backend: ReplayBackendId | undefined, +): Promise { + const { resolveReplayFormat, isMaestroYamlPath, maestroBackendRequiredMessage } = + await import('@agent-device/ad-script'); + const entry = request.flags?.replayScriptSource?.entry ?? request.positionals?.[0] ?? ''; + if (isMaestroYamlPath(entry) && backend !== 'maestro') + throw new AppError('INVALID_ARGS', maestroBackendRequiredMessage('replay', entry)); + if (resolveReplayFormat(entry, backend) === 'maestro') await getReplayBackend('maestro'); + else await getReplayExecution(); +} diff --git a/packages/replay-port/src/daemon-port/session-replay-dispatch-narrowing.ts b/packages/replay-port/src/daemon-port/session-replay-dispatch-narrowing.ts index a6f7dacd1e..6fd1bfc2dd 100644 --- a/packages/replay-port/src/daemon-port/session-replay-dispatch-narrowing.ts +++ b/packages/replay-port/src/daemon-port/session-replay-dispatch-narrowing.ts @@ -5,7 +5,7 @@ import type { AdReplayGuardMismatchEvidence, AdReplayLandmarkMismatchEvidence, AdReplayStepFailure, -} from '@agent-device/ad-replay'; +} from '@agent-device/contracts/ad-replay-execution'; import type { LocalIdentity } from '@agent-device/ad-script'; import type { TargetAncestryEntry } from '@agent-device/contracts/replay'; import { diff --git a/packages/replay-port/src/daemon-port/session-replay-divergence-publication.ts b/packages/replay-port/src/daemon-port/session-replay-divergence-publication.ts index 5953ee9526..6e38ee8238 100644 --- a/packages/replay-port/src/daemon-port/session-replay-divergence-publication.ts +++ b/packages/replay-port/src/daemon-port/session-replay-divergence-publication.ts @@ -3,7 +3,7 @@ import path from 'node:path'; import type { ResponseLevel } from '@agent-device/kernel/contracts'; import { redactDiagnosticData } from '@agent-device/kernel/redaction'; import { type ReplayDivergence } from '@agent-device/contracts/divergence'; -import { boundReplayDivergence } from '@agent-device/ad-replay/divergence'; +import { boundReplayDivergence } from '@agent-device/contracts/replay-divergence-data'; import type { ReplayObservationEvidence } from '@agent-device/contracts/replay'; import type { ReplaySessionObservation, diff --git a/packages/replay-port/src/daemon-port/session-replay-divergence.ts b/packages/replay-port/src/daemon-port/session-replay-divergence.ts index e4bfd9db79..7ea894e76c 100644 --- a/packages/replay-port/src/daemon-port/session-replay-divergence.ts +++ b/packages/replay-port/src/daemon-port/session-replay-divergence.ts @@ -47,7 +47,7 @@ import { REPLAY_DIVERGENCE_SUGGESTION_LIMIT, createReplayDivergenceSanitizer, type ReplayVarScrubEntry, -} from '@agent-device/ad-replay/divergence'; +} from '@agent-device/contracts/replay-divergence-data'; export type DivergenceFieldSanitizer = (value: string, limit?: number) => string; diff --git a/packages/replay-port/src/daemon-port/session-replay-resume.ts b/packages/replay-port/src/daemon-port/session-replay-resume.ts index 824545ce2d..45f78098e1 100644 --- a/packages/replay-port/src/daemon-port/session-replay-resume.ts +++ b/packages/replay-port/src/daemon-port/session-replay-resume.ts @@ -42,7 +42,7 @@ export function buildAndPersistReplayDivergenceResume(params: { * `failedIndex` would re-diverge on the step the agent already performed). * Every other repair hint (including a plain `action-failure`) resumes AT * `failedIndex` unchanged. This must agree with the text guidance rendered by - * `formatReplayDivergenceReport` (`packages/ad-replay/src/replay-divergence.ts`) — both are + * `formatReplayDivergenceReport` (`packages/contracts/src/replay-divergence-data.ts`) — both are * derived from the same computed `from` value. * * `failedIndex` is always a valid 1-based index into `actions` (both call diff --git a/packages/replay-port/src/daemon-port/session-replay-runtime-engine-adapter.ts b/packages/replay-port/src/daemon-port/session-replay-runtime-engine-adapter.ts index ab8719ed49..414884f367 100644 --- a/packages/replay-port/src/daemon-port/session-replay-runtime-engine-adapter.ts +++ b/packages/replay-port/src/daemon-port/session-replay-runtime-engine-adapter.ts @@ -20,7 +20,10 @@ import type { SnapshotTimingSample } from '@agent-device/contracts/capture'; import { withReplayFailureDiagnostics } from './session-replay-runtime-failure.ts'; import { invokeReplayAction } from './session-replay-action-runtime.ts'; -import type { AdReplayStepFailure, AdReplayStepRuntime } from '@agent-device/ad-replay'; +import type { + AdReplayStepFailure, + AdReplayStepRuntime, +} from '@agent-device/contracts/ad-replay-execution'; import { collectReplayActionArtifactPaths } from '@agent-device/replay-port/session-replay-runtime-artifacts'; import { applyReplayDispatchGuard, @@ -39,7 +42,7 @@ import { resolveTargetVerificationEntry, type TargetBindingDivergenceContext, } from './session-replay-target-verification.ts'; -import type { ReplayTestAttemptStepSink } from '@agent-device/replay-test'; +import type { ReplayTestAttemptStepSink } from '@agent-device/contracts/replay-test-execution'; /** * #1555 P5 (decomposition): the daemon's `AdReplayStepRuntime` adapter — extracted verbatim out diff --git a/packages/replay-port/src/daemon-port/session-replay-runtime-failure-response.ts b/packages/replay-port/src/daemon-port/session-replay-runtime-failure-response.ts index db5f5f56ca..a86b31904d 100644 --- a/packages/replay-port/src/daemon-port/session-replay-runtime-failure-response.ts +++ b/packages/replay-port/src/daemon-port/session-replay-runtime-failure-response.ts @@ -1,7 +1,10 @@ import type { SessionAction } from '@agent-device/contracts/session'; import { ANDROID_SHELL_TEXT_UNSUPPORTED_REASON } from '@agent-device/contracts/input-validation'; import { BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON } from '@agent-device/kernel/errors'; -import { scrubReplayVarValues, type ReplayVarScrubEntry } from '@agent-device/ad-replay/divergence'; +import { + scrubReplayVarValues, + type ReplayVarScrubEntry, +} from '@agent-device/contracts/replay-divergence-data'; import { formatDivergenceActionLabel } from '@agent-device/ad-script'; import type { SnapshotDiagnosticsSummary } from '@agent-device/contracts/capture'; import { buildDisplayPositionals } from '@agent-device/session-journal/session-event-action'; diff --git a/packages/replay-port/src/daemon-port/session-replay-runtime-failure.ts b/packages/replay-port/src/daemon-port/session-replay-runtime-failure.ts index eb9d0d225e..4280b5ac22 100644 --- a/packages/replay-port/src/daemon-port/session-replay-runtime-failure.ts +++ b/packages/replay-port/src/daemon-port/session-replay-runtime-failure.ts @@ -1,5 +1,5 @@ import type { SessionAction } from '@agent-device/contracts/session'; -import type { AdReplayScrubValue } from '@agent-device/ad-replay'; +import type { AdReplayScrubValue } from '@agent-device/contracts/ad-replay-execution'; import { summarizeSnapshotTimingSamples, type SnapshotDiagnosticsSummary, diff --git a/packages/replay-port/src/daemon-port/session-replay-runtime-plan.ts b/packages/replay-port/src/daemon-port/session-replay-runtime-plan.ts index 59b0ec51d1..24986b1b82 100644 --- a/packages/replay-port/src/daemon-port/session-replay-runtime-plan.ts +++ b/packages/replay-port/src/daemon-port/session-replay-runtime-plan.ts @@ -1,3 +1,4 @@ +import type { ReplayExecution } from '@agent-device/contracts/replay-execution'; import type { SessionAction } from '@agent-device/contracts/session'; import type { ReplayDispatchOptions } from '@agent-device/contracts/replay'; import type { CommandFlags, DaemonWireRequest } from '@agent-device/contracts/command'; @@ -9,11 +10,10 @@ import type { ReplaySessionStore, } from '@agent-device/contracts/replay-backend'; import { buildReplayScriptPlatformFlags } from '@agent-device/replay-port/replay-script-selection'; -import { - inspectAdReplay, - type AdReplayManifest, - type AdReplayVarSources, -} from '@agent-device/ad-replay'; +import type { + AdReplayManifest, + AdReplayVarSources, +} from '@agent-device/contracts/ad-replay-execution'; import { collectReplayShellEnv, isReplayBackendId, @@ -89,6 +89,7 @@ export type PreparedReplayPlan = { }; export function prepareReplayPlan(params: { + inspectAdReplay: ReplayExecution['inspectAdReplay']; req: DaemonWireRequest; /** The command's runtime host; variable sources read environment and cwd from it. */ host: HostEnvironment; @@ -116,7 +117,12 @@ export function prepareReplayPlan(params: { const backendRejection = validateReplayBackendFlag(req); if (backendRejection) return { ok: false, response: backendRejection }; - const { manifest, replayReq } = inspectReplayPlanManifest(req, script, dispatch); + const { manifest, replayReq } = inspectReplayPlanManifest( + req, + script, + dispatch, + params.inspectAdReplay, + ); const { metadata, actions, actionLines, planDigest } = manifest; const preEntrySession = sessionStore.get(); const entryIndexResult = resolveReplayPlanEntryIndex({ @@ -179,6 +185,7 @@ function inspectReplayPlanManifest( req: DaemonWireRequest, script: string, dispatch: ReplayDispatchOptions | undefined, + inspectAdReplay: ReplayExecution['inspectAdReplay'], ): { manifest: AdReplayManifest; replayReq: ReplayDispatchRequest } { const manifest = inspectAdReplay(script, { platform: req.flags?.platform, diff --git a/packages/replay-port/src/daemon-port/session-replay-target-verification.ts b/packages/replay-port/src/daemon-port/session-replay-target-verification.ts index 6cc42477d0..11db4ab668 100644 --- a/packages/replay-port/src/daemon-port/session-replay-target-verification.ts +++ b/packages/replay-port/src/daemon-port/session-replay-target-verification.ts @@ -16,14 +16,14 @@ import type { AdReplayTargetBindingEvidence, AdReplayTargetClassification, AdReplayVerificationEntry, -} from '@agent-device/ad-replay'; +} from '@agent-device/contracts/ad-replay-execution'; import { type ReplayDivergence, type ReplayDivergenceTargetBindingKind, type ReplayDivergenceTargetCandidate, type ReplayDivergenceTargetIdentity, } from '@agent-device/contracts/divergence'; -import { createReplayDivergenceSanitizer } from '@agent-device/ad-replay/divergence'; +import { createReplayDivergenceSanitizer } from '@agent-device/contracts/replay-divergence-data'; import { REPLAY_TARGET_GUARD_MISMATCH_REASON, WAIT_LANDMARK_MISMATCH_REASON, diff --git a/packages/replay-port/src/daemon-port/session-test-outcome.ts b/packages/replay-port/src/daemon-port/session-test-outcome.ts index 088616de5c..85828ef4ba 100644 --- a/packages/replay-port/src/daemon-port/session-test-outcome.ts +++ b/packages/replay-port/src/daemon-port/session-test-outcome.ts @@ -2,7 +2,10 @@ import { readSnapshotDiagnosticsSummary } from '@agent-device/contracts/capture' import { readResponseWarnings } from '@agent-device/kernel/success-text'; import { BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON } from '@agent-device/kernel/errors'; import { isReplayInfrastructureFailure } from './session-test-infrastructure.ts'; -import type { ReplayTestAttemptFailed, ReplayTestAttemptOutcome } from '@agent-device/replay-test'; +import type { + ReplayTestAttemptFailed, + ReplayTestAttemptOutcome, +} from '@agent-device/contracts/replay-test-execution'; import { type DaemonResponse } from '@agent-device/kernel/contracts'; /** diff --git a/packages/replay-port/src/daemon-port/session-test-shard-devices.ts b/packages/replay-port/src/daemon-port/session-test-shard-devices.ts index 7c588571a4..dedec38bc4 100644 --- a/packages/replay-port/src/daemon-port/session-test-shard-devices.ts +++ b/packages/replay-port/src/daemon-port/session-test-shard-devices.ts @@ -15,7 +15,7 @@ import type { ReplayTestResolveShardTargets, ReplayTestShardContext, ReplayTestShardTarget, -} from '@agent-device/replay-test'; +} from '@agent-device/contracts/replay-test-execution'; /** * The daemon adapter's shard-device binding (#1478 P3b). diff --git a/packages/replay-port/src/daemon-port/session-test-source-discovery.ts b/packages/replay-port/src/daemon-port/session-test-source-discovery.ts index 6ef93fe530..66a55a1fee 100644 --- a/packages/replay-port/src/daemon-port/session-test-source-discovery.ts +++ b/packages/replay-port/src/daemon-port/session-test-source-discovery.ts @@ -9,7 +9,7 @@ import type { ReplayTestDiscoverSources, ReplayTestManifest, ReplayTestSource, -} from '@agent-device/replay-test'; +} from '@agent-device/contracts/replay-test-execution'; import type { ReplayBackend } from '@agent-device/contracts/replay-backend'; import { getReplayBackend } from './replay-backend-registry.ts'; diff --git a/packages/replay-port/src/daemon-port/test-command.ts b/packages/replay-port/src/daemon-port/test-command.ts index 3a4f01747c..d30b14c19b 100644 --- a/packages/replay-port/src/daemon-port/test-command.ts +++ b/packages/replay-port/src/daemon-port/test-command.ts @@ -1,3 +1,4 @@ +import { getReplayExecution } from './replay-backend-registry.ts'; /** Runs the replay-test scheduler and its nested replay attempts. */ import { randomUUID } from 'node:crypto'; @@ -13,13 +14,12 @@ import { REPLAY_SCRIPT_SOURCE_REQUIRED_MESSAGE } from '@agent-device/replay-port import type { ReplayScriptMetadata } from '@agent-device/ad-script'; import { expandSessionPath } from '@agent-device/host-kit/session-paths'; import type { ReplayCommand, ReplayTestCommand } from '@agent-device/replay-port/command-types'; -import { - runReplayTestSuite, - type ReplayTestAttemptOutcome, - type ReplayTestBindAttemptCancellation, - type ReplayTestShardContext, - type ReplayTestSuiteRequest, -} from '@agent-device/replay-test'; +import type { + ReplayTestAttemptOutcome, + ReplayTestBindAttemptCancellation, + ReplayTestShardContext, + ReplayTestSuiteRequest, +} from '@agent-device/contracts/replay-test-execution'; import { runReplayCommand } from './native-command.ts'; import { collectReplayActionArtifactPaths } from '@agent-device/replay-port/session-replay-runtime-artifacts'; import { @@ -195,7 +195,9 @@ export async function runReplayTestCommand(command: ReplayTestCommand): Promise< return errorResponse(appErr.code, appErr.message); } const sourceBundlesByPath = new Map(sourceBundles.map((bundle) => [bundle.entry, bundle])); - const outcome = await runReplayTestSuite({ + const outcome = await ( + await getReplayExecution() + ).runReplayTestSuite({ request: suiteRequest, // The host owns the request-global progress sink; the scheduler receives only the // narrow emit capability (#1478 P3b). diff --git a/packages/replay-port/src/replay-script-source.fixtures.ts b/packages/replay-port/src/replay-script-source.fixtures.ts index 0b826d84b1..48f7efe52d 100644 --- a/packages/replay-port/src/replay-script-source.fixtures.ts +++ b/packages/replay-port/src/replay-script-source.fixtures.ts @@ -12,6 +12,7 @@ export async function maestroScriptSourceBundleFor( filePath: string, ): Promise { return await loadReplayScriptSourceBundle({ + hostEnv: process.env, inputPath: filePath, cwd: process.cwd(), replayBackend: 'maestro', diff --git a/packages/replay-port/src/script-source-bundle.ts b/packages/replay-port/src/script-source-bundle.ts index 57cf3b05c0..b448a204bd 100644 --- a/packages/replay-port/src/script-source-bundle.ts +++ b/packages/replay-port/src/script-source-bundle.ts @@ -1,9 +1,9 @@ import fs from 'node:fs'; +import type { ReplayBackendResolver } from '@agent-device/contracts/replay-backend'; import { AppError } from '@agent-device/kernel/errors'; import type { ReplayScriptSourceBundle } from '@agent-device/contracts/replay'; import { resolveUserPath } from '@agent-device/host-kit/file'; import { resolveReplayFormat } from '@agent-device/ad-script'; -import type { ReplayBackend } from '@agent-device/contracts/replay-backend'; export const REPLAY_SCRIPT_SOURCE_BUNDLE_MAX_BYTES = 2 * 1024 * 1024; @@ -11,6 +11,8 @@ export type ReplayScriptSourceRequest = { inputPath: string; cwd: string; replayBackend?: string; + hostEnv: NodeJS.ProcessEnv; + resolveReplayBackend?: ReplayBackendResolver; env?: Readonly>; }; @@ -26,15 +28,20 @@ export async function loadReplayScriptSourceBundle( // Function-scoped on purpose: the eager-closure budget gate counts a static import here as a // module every warm CLI command evaluates, for a format most runs never use (#1802), and the // backend's engine sits one thunk behind it (#3377). - const backend: ReplayBackend = await ( + const files = await ( await import('@agent-device/replay-port/replay-backend-registry') - ).getReplayBackend(backendId); - const files = backend.collectSourceFiles({ - entryPath: entry, - entrySource, - env: params.env, - readSource: tryReadScriptFile, - }); + ).withReplayBackend( + backendId, + { env: params.hostEnv, cwd: params.cwd }, + (backend) => + backend.collectSourceFiles({ + entryPath: entry, + entrySource, + env: params.env, + readSource: tryReadScriptFile, + }), + params.resolveReplayBackend, + ); return finishBundle(entry, files, params.inputPath); } diff --git a/packages/replay-port/tsconfig.json b/packages/replay-port/tsconfig.json index 92d1911f45..ea675e52e0 100644 --- a/packages/replay-port/tsconfig.json +++ b/packages/replay-port/tsconfig.json @@ -11,18 +11,38 @@ }, "include": ["src", "../command-registry/src/global.d.ts"], "references": [ - { "path": "../ad-replay" }, - { "path": "../ad-script" }, - { "path": "../capture-kit" }, - { "path": "../command-registry" }, - { "path": "../contracts" }, - { "path": "../device-selection" }, - { "path": "../host-kit" }, - { "path": "../kernel" }, - { "path": "../maestro" }, - { "path": "../replay-test" }, - { "path": "../selectors" }, - { "path": "../session-journal" }, - { "path": "../test-kit" } + { + "path": "../ad-script" + }, + { + "path": "../capture-kit" + }, + { + "path": "../command-registry" + }, + { + "path": "../contracts" + }, + { + "path": "../device-selection" + }, + { + "path": "../host-kit" + }, + { + "path": "../kernel" + }, + { + "path": "../selectors" + }, + { + "path": "../session-journal" + }, + { + "path": "../test-kit" + }, + { + "path": "../plugins" + } ] } diff --git a/packages/replay-test/src/index.ts b/packages/replay-test/src/index.ts index c4f469f001..ae868639e8 100644 --- a/packages/replay-test/src/index.ts +++ b/packages/replay-test/src/index.ts @@ -1,35 +1,2 @@ -/** - * The replay-test package façade (#1478 P3). - * - * One function plus the values crossing its seam. Everything else — scheduling, retries, - * sharding distribution, attempt identity, timeout policy, finalization/cleanup ordering, and - * result aggregation — is private to `internal/`. - * - * The scheduler is format-agnostic: it imports neither engine, and a source reaches it only as - * a `ReplayTestManifest`. Host authority arrives as narrow capabilities on the runtime-dependency - * half of `runReplayTestSuite`'s parameter; none of them hands over a daemon request, a session - * store, mutable session state, or an engine. - * - * The parameter and result types themselves are not named here. The single caller builds the - * bag inline and TypeScript infers both, so re-exporting the names would add surface no consumer - * asks for; a consumer that needs to name one earns it back through the R11 pin. - */ +/** Suite scheduling consumes shared contracts and explicit host capabilities. */ export { runReplayTestSuite } from './internal/session-test.ts'; - -export type { - ReplayTestAttemptFailed, - ReplayTestAttemptOutcome, - ReplayTestAttemptStepSink, - ReplayTestBindAttemptCancellation, - ReplayTestDiscoverSources, - ReplayTestManifest, - ReplayTestSource, - ReplayTestSuiteRequest, -} from './internal/session-test-types.ts'; - -export type { - ReplayTestResolveShardTargets, - ReplayTestShardContext, - ReplayTestShardMode, - ReplayTestShardTarget, -} from './internal/session-test-sharding.ts'; diff --git a/packages/replay-test/src/internal/__tests__/session-test-artifacts.test.ts b/packages/replay-test/src/internal/__tests__/session-test-artifacts.test.ts index ef16fc0b92..9be8ddb2cc 100644 --- a/packages/replay-test/src/internal/__tests__/session-test-artifacts.test.ts +++ b/packages/replay-test/src/internal/__tests__/session-test-artifacts.test.ts @@ -9,7 +9,7 @@ import { prepareReplayTestAttemptArtifacts, resolveReplayTestArtifactsDir, } from '../session-test-artifacts.ts'; -import type { ReplayTestAttemptOutcome } from '../session-test-types.ts'; +import type { ReplayTestAttemptOutcome } from '@agent-device/contracts/replay-test-execution'; import { mkdtempForTestSync } from '../../tmp-dir.fixtures.ts'; test('resolveReplayTestArtifactsDir falls back to the default root when artifactsDir is omitted', () => { diff --git a/packages/replay-test/src/internal/__tests__/session-test-attempt.test.ts b/packages/replay-test/src/internal/__tests__/session-test-attempt.test.ts index e42b3788a5..a584c7b8cc 100644 --- a/packages/replay-test/src/internal/__tests__/session-test-attempt.test.ts +++ b/packages/replay-test/src/internal/__tests__/session-test-attempt.test.ts @@ -3,7 +3,7 @@ import path from 'node:path'; import { expect, test } from 'vitest'; import { runReplayTestCase } from '../session-test-attempt.ts'; import type { ReplayTestRunEntry } from '../session-test-discovery.ts'; -import type { ReplayTestAttemptOutcome } from '../session-test-types.ts'; +import type { ReplayTestAttemptOutcome } from '@agent-device/contracts/replay-test-execution'; import type { ReplaySuiteTestFailed } from '@agent-device/contracts/replay'; import { mkdtempForTestSync } from '../../tmp-dir.fixtures.ts'; diff --git a/packages/replay-test/src/internal/__tests__/session-test-discovery.test.ts b/packages/replay-test/src/internal/__tests__/session-test-discovery.test.ts index 2f620df7d5..a7cb8e8344 100644 --- a/packages/replay-test/src/internal/__tests__/session-test-discovery.test.ts +++ b/packages/replay-test/src/internal/__tests__/session-test-discovery.test.ts @@ -8,7 +8,10 @@ import { } from '../session-test-discovery.ts'; import { trimEdgeDashes } from '@agent-device/kernel/collections'; import { buildReplayTestArtifactSlug } from '../session-test-artifacts.ts'; -import type { ReplayTestManifest, ReplayTestSource } from '../session-test-types.ts'; +import type { + ReplayTestManifest, + ReplayTestSource, +} from '@agent-device/contracts/replay-test-execution'; // Scheduler-owned discovery policy (#1478 P3b): which sources a --platform filter runs, which // it skips and with what message, and rejecting a suite that matched nothing. Inspection is the diff --git a/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts b/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts index fa1f8ec1d3..f19cb89c77 100644 --- a/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts +++ b/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts @@ -5,7 +5,7 @@ import { afterEach, expect, test, vi } from 'vitest'; import { runReplayTestAttempt } from '../session-test-runtime.ts'; -import type { ReplayTestAttemptOutcome } from '../session-test-types.ts'; +import type { ReplayTestAttemptOutcome } from '@agent-device/contracts/replay-test-execution'; import { mkdtempForTestSync } from '../../tmp-dir.fixtures.ts'; // What the scheduler owes its host around cancellation (#1478 P3b): cancel exactly once when diff --git a/packages/replay-test/src/internal/session-test-artifacts.ts b/packages/replay-test/src/internal/session-test-artifacts.ts index aa052def70..a900fea499 100644 --- a/packages/replay-test/src/internal/session-test-artifacts.ts +++ b/packages/replay-test/src/internal/session-test-artifacts.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { trimEdgeDashes } from '@agent-device/kernel/collections'; -import type { ReplayTestAttemptOutcome } from '@agent-device/replay-test'; +import type { ReplayTestAttemptOutcome } from '@agent-device/contracts/replay-test-execution'; /** * `test`'s default artifacts root when `--artifacts-dir` is not given. `packages/remote/src/daemon-artifacts.ts` diff --git a/packages/replay-test/src/internal/session-test-attempt-failure.ts b/packages/replay-test/src/internal/session-test-attempt-failure.ts new file mode 100644 index 0000000000..fd102161a1 --- /dev/null +++ b/packages/replay-test/src/internal/session-test-attempt-failure.ts @@ -0,0 +1,23 @@ +import type { + ReplayTestAttemptError, + ReplayTestAttemptFailed, +} from '@agent-device/contracts/replay-test-execution'; +import type { SnapshotDiagnosticsSummary } from '@agent-device/contracts/capture'; + +/** Neutral failure outcome helper; keeps timeout/unknown construction in one place. */ +export function replayTestAttemptFailure(params: { + error: ReplayTestAttemptError; + artifactPaths?: readonly string[]; + warnings?: readonly string[]; + infrastructure?: boolean; + snapshotDiagnostics?: SnapshotDiagnosticsSummary; +}): ReplayTestAttemptFailed { + return { + status: 'failed', + error: params.error, + artifactPaths: params.artifactPaths ?? [], + warnings: params.warnings ?? [], + infrastructure: params.infrastructure ?? false, + ...(params.snapshotDiagnostics ? { snapshotDiagnostics: params.snapshotDiagnostics } : {}), + }; +} diff --git a/packages/replay-test/src/internal/session-test-attempt.ts b/packages/replay-test/src/internal/session-test-attempt.ts index 11101da418..c40821acca 100644 --- a/packages/replay-test/src/internal/session-test-attempt.ts +++ b/packages/replay-test/src/internal/session-test-attempt.ts @@ -13,10 +13,10 @@ import { } from './session-test-discovery.ts'; import { runReplayTestAttempt } from './session-test-runtime.ts'; import type { + ReplayTestShardContext, ReplayTestAttemptOutcome, ReplayTestExecutionDependencies, -} from './session-test-types.ts'; -import type { ReplayTestShardContext } from './session-test-sharding.ts'; +} from '@agent-device/contracts/replay-test-execution'; type ReplayTestCaseResult = Extract; type ReplayTestAttemptFailure = NonNullable< diff --git a/packages/replay-test/src/internal/session-test-discovery.ts b/packages/replay-test/src/internal/session-test-discovery.ts index 57e77bd7b5..33b857f431 100644 --- a/packages/replay-test/src/internal/session-test-discovery.ts +++ b/packages/replay-test/src/internal/session-test-discovery.ts @@ -6,7 +6,7 @@ import type { ReplayTestDiscoverSources, ReplayTestManifest, ReplayTestPlatform, -} from './session-test-types.ts'; +} from '@agent-device/contracts/replay-test-execution'; const MAX_REPLAY_TEST_RETRIES = 3; diff --git a/packages/replay-test/src/internal/session-test-runtime.ts b/packages/replay-test/src/internal/session-test-runtime.ts index ecdf22b2fa..0c8c50ab2d 100644 --- a/packages/replay-test/src/internal/session-test-runtime.ts +++ b/packages/replay-test/src/internal/session-test-runtime.ts @@ -1,9 +1,9 @@ +import { replayTestAttemptFailure } from './session-test-attempt-failure.ts'; import fs from 'node:fs'; import path from 'node:path'; import { setTimeout as sleep } from 'node:timers/promises'; import { normalizeError } from '@agent-device/kernel/errors'; import { - replayTestAttemptFailure, type ReplayTestAttemptFailed, type ReplayTestAttemptOutcome, type ReplayTestAttemptStepSink, @@ -12,7 +12,7 @@ import { type ReplayTestRunReplayParams, type ReplayTestTarget, type ReplayTestRuntimeDependencies, -} from './session-test-types.ts'; +} from '@agent-device/contracts/replay-test-execution'; const REPLAY_TIMEOUT_CLEANUP_GRACE_MS = 2_000; const REPLAY_TEST_TIMEOUT_HINT = diff --git a/packages/replay-test/src/internal/session-test-sharding.ts b/packages/replay-test/src/internal/session-test-sharding.ts index 6cb81ff6cd..79be86b323 100644 --- a/packages/replay-test/src/internal/session-test-sharding.ts +++ b/packages/replay-test/src/internal/session-test-sharding.ts @@ -1,37 +1,8 @@ -import type { ReplayTestPlatform, ReplayTestTarget } from './session-test-types.ts'; - -export type ReplayTestShardMode = 'all' | 'split'; - -/** - * The device a shard runs against, in neutral vocabulary. - * - * The scheduler reads `id`/`name` for session labels and progress metadata. `platform` and - * `target` are here because the host needs them to bind a nested request, and both are already - * neutral kernel types — so `DeviceInfo` itself never crosses into scheduling. - */ -export type ReplayTestShardTarget = Readonly<{ - id: string; - name: string; - platform: ReplayTestPlatform; - target?: ReplayTestTarget; -}>; - -export type ReplayTestShardContext = { - shardIndex: number; - shardCount: number; - device: ReplayTestShardTarget; -}; - -/** - * Resolves the devices a sharded run will use (#1478 P3b). - * - * Enumerating inventory, applying allowlists and simulator set paths, and rejecting a run with - * too few devices are all host concerns. The scheduler decides how many shards there are and - * which entries go to each; it never enumerates hardware. - */ -export type ReplayTestResolveShardTargets = ( - shardCount: number, -) => Promise; +import type { + ReplayTestShardContext, + ReplayTestShardMode, + ReplayTestResolveShardTargets, +} from '@agent-device/contracts/replay-test-execution'; export type ReplayTestShardPlan = { mode: ReplayTestShardMode; diff --git a/packages/replay-test/src/internal/session-test.ts b/packages/replay-test/src/internal/session-test.ts index 410ed3c37d..c8e7160443 100644 --- a/packages/replay-test/src/internal/session-test.ts +++ b/packages/replay-test/src/internal/session-test.ts @@ -14,6 +14,8 @@ import { } from './session-test-discovery.ts'; import { runReplayTestCase, type ReplayTestCaseReport } from './session-test-attempt.ts'; import type { + ReplayTestResolveShardTargets, + ReplayTestShardContext, ReplayTestEmitProgress, ReplayTestIsCanceled, ReplayTestExecutionDependencies, @@ -21,13 +23,8 @@ import type { ReplayTestSuiteOutcome, ReplayTestSuiteRequest, ReplayTestDiscoverSources, -} from './session-test-types.ts'; -import { - buildReplayTestShardPlan, - type ReplayTestResolveShardTargets, - type ReplayTestShardContext, - type ReplayTestShardPlan, -} from './session-test-sharding.ts'; +} from '@agent-device/contracts/replay-test-execution'; +import { buildReplayTestShardPlan, type ReplayTestShardPlan } from './session-test-sharding.ts'; import { mergeSnapshotDiagnostics } from '@agent-device/contracts/capture'; type ReplayTestEntry = ReturnType[number]; diff --git a/packages/replay/README.md b/packages/replay/README.md new file mode 100644 index 0000000000..5b1b7b548d --- /dev/null +++ b/packages/replay/README.md @@ -0,0 +1,50 @@ +# Run native replay and test suites + +Install `@agent-device/replay` on the daemon host before running native `.ad` scripts or any `test` suite: + +```sh +agent-device plugins add @agent-device/replay +``` + +Finish your sessions, then restart the daemon on that host. Retry your original command with all its arguments. Existing `.ad` syntax, variables, target identity, divergence reports, resume and repair do not need a migration. + +The plugin uses API version 2 and supports core `>=0.22.0-0 <0.23.0`. The extraction's pinned development host, `0.21.38-dev`, is also accepted. Other core releases, including the next development bump, fail with `incompatible_plugin` until compatibility is verified and the declared range is updated. The managed API version 2 check also applies. Use matching core and plugin releases. The package remains private until a maintainer publishes a non-`latest` npm placeholder and configures trusted publishing for `.github/workflows/release.yml`, job `npm-publish`. + +## Choose the installation host + +| Workflow | Client host | Daemon host | +| --- | --- | --- | +| Native `.ad` replay | Core reads and sends the source | `@agent-device/replay` | +| Native `.ad` test suites | Core discovers and sends sources | `@agent-device/replay` | +| Maestro replay | `@agent-device/maestro` collects includes | `@agent-device/maestro` | +| Maestro test suites | `@agent-device/maestro` collects includes | Both plugins | +| `replay export` to Maestro | `@agent-device/maestro` | No daemon required | + +Installing locally does not install anything on a remote daemon. Run `plugins add` on each host that needs the package. + +For an embedded daemon, supply the factory explicitly: + +```js +import { startAgentDevice } from 'agent-device'; +import replay from '@agent-device/replay/agent-device'; + +const runtime = await startAgentDevice({ + stateDir: '/tmp/checkout-agent', + plugins: [replay()], +}); +try { + await runtime.client.replay.run({ path: './checkout.ad' }); +} finally { + await runtime.close(); +} +``` + +An embedded runtime uses its supplied plugins, including an empty list. It does not borrow a conflicting plugin store. Its host must close and recreate it to change that set. + +## Recover from an unavailable plugin + +`plugin-not-installed` includes the exact package and `installCommand`. Install it on the named host, restart that daemon, then retry the original invocation with all its arguments. + +`plugin_load_failed`, `invalid_plugin`, `incompatible_plugin` and `plugin_setup_failed` describe a selected package that failed. Repair or update that package; another backend is never selected automatically. `daemon-plugin-set-stale` means the running daemon has an older set than the store. Finish your sessions and restart it. No error installs a package or terminates your sessions automatically. + +Ordinary `open --save-script`, `session save-script` and `close` recording remain in core. Replay-specific `--save-script` repair requires this plugin. Core retains sessions, dispatch, selectors, refs, recording, cancellation and cleanup. The plugin receives the existing explicit step and suite ports; shared `.ad` data and divergence readers remain independent of execution. diff --git a/packages/replay/package.json b/packages/replay/package.json new file mode 100644 index 0000000000..26fdfe76dc --- /dev/null +++ b/packages/replay/package.json @@ -0,0 +1,37 @@ +{ + "name": "@agent-device/replay", + "version": "0.0.0", + "private": true, + "sideEffects": false, + "type": "module", + "description": "Optional native .ad replay and test-suite execution plugin for agent-device.", + "exports": { + "./agent-device": { + "types": "./src/plugin.ts", + "default": "./src/plugin.ts" + } + }, + "devDependencies": { + "@agent-device/ad-replay": "workspace:*", + "@agent-device/replay-test": "workspace:*", + "agent-device": "workspace:*", + "@agent-device/plugins": "workspace:*", + "@agent-device/test-kit": "workspace:*" + }, + "scripts": { + "build": "tsdown --config tsdown.config.ts", + "prepack": "pnpm build" + }, + "files": [ + "dist" + ], + "publishConfig": { + "exports": { + "./agent-device": { + "types": "./dist/agent-device.d.mts", + "import": "./dist/agent-device.mjs" + } + }, + "access": "public" + } +} diff --git a/packages/replay/src/plugin.test.ts b/packages/replay/src/plugin.test.ts new file mode 100644 index 0000000000..b76d5e3db5 --- /dev/null +++ b/packages/replay/src/plugin.test.ts @@ -0,0 +1,86 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { expect, test, vi } from 'vitest'; +import { createPluginHost } from '@agent-device/plugins/host'; +import { resolveProviderPlugins, startProviderRegistry } from '@agent-device/plugins/registry'; +import replayPlugin from './plugin.ts'; + +test('the first-party factory uses the managed registry and preserves native script syntax', async () => { + const registry = await startProviderRegistry( + await resolveProviderPlugins([{ source: 'embedder', load: replayPlugin }]), + { env: {}, cwd: '/' }, + { + adaptWebDriver: async () => { + throw new Error('Replay cannot create providers'); + }, + }, + ); + try { + const execution = await registry.resolveReplayExecution(); + const manifest = execution.inspectAdReplay( + 'open com.example.app\nfill "id=password" "${PASSWORD}"\nclose', + ); + expect(manifest.actions.map((action) => action.command)).toEqual(['open', 'fill', 'close']); + expect(manifest.actions[1]?.positionals).toContain('${PASSWORD}'); + const artifactsDir = mkdtempForTestSync('replay-plugin-suite-'); + const sourcePath = path.join(artifactsDir, 'flow.ad'); + fs.writeFileSync(sourcePath, 'open com.example.app\nclose\n'); + const runReplay = vi.fn(async () => ({ + status: 'passed' as const, + replayed: 2, + healed: 0, + warnings: [], + artifactPaths: [], + })); + const cleanupSession = vi.fn(async () => {}); + const release = vi.fn(); + const suite = await execution.runReplayTestSuite({ + request: { + inputs: [sourcePath], + sessionName: 'package-suite', + artifactsDir, + }, + runReplay, + cleanupSession, + emitProgress: () => {}, + isCanceled: () => false, + emitDiagnostic: () => {}, + bindAttemptCancellation: () => ({ cancel: () => {}, release }), + discoverSources: () => [ + { path: sourcePath, manifest: { device: { platform: { kind: 'unspecified' } } } }, + ], + resolveShardTargets: async () => [], + }); + expect(suite, JSON.stringify(suite)).toMatchObject({ + status: 'completed', + data: { passed: 1, failed: 0 }, + }); + expect(runReplay).toHaveBeenCalledOnce(); + expect(cleanupSession).toHaveBeenCalledOnce(); + expect(release).toHaveBeenCalledOnce(); + } finally { + await registry.close(); + } +}); + +test.each(['0.23.0', '0.21.39-dev'])('the package rejects unverified core %s', (clientVersion) => { + const host = { ...createPluginHost({ env: {}, cwd: '/' }, undefined), clientVersion }; + expect(() => replayPlugin().setup(host)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'incompatible_plugin' }), + }), + ); +}); + +test.each(['0.21.38-dev', '0.22.0-beta.1', '0.22.0'])( + 'the package accepts declared core %s', + (clientVersion) => { + expect( + replayPlugin().setup({ + ...createPluginHost({ env: {}, cwd: '/' }, undefined), + clientVersion, + }), + ).toMatchObject({ execution: { create: expect.any(Function) } }); + }, +); diff --git a/packages/replay/src/plugin.ts b/packages/replay/src/plugin.ts new file mode 100644 index 0000000000..c4029905b8 --- /dev/null +++ b/packages/replay/src/plugin.ts @@ -0,0 +1,32 @@ +import type { ReplayEnginePlugin } from 'agent-device/plugins'; + +/** Native .ad execution and suite scheduling use host-owned dispatch, sessions and cancellation. */ +function replayPlugin(): ReplayEnginePlugin<'ad'> { + return { + apiVersion: 2, + kind: 'replay-backend', + backend: 'ad', + setup: (host) => { + if (host.clientVersion !== '0.21.38-dev' && !host.clientVersion.startsWith('0.22.')) { + throw host.createError('INVALID_ARGS', 'The replay plugin requires agent-device 0.22', { + reason: 'incompatible_plugin', + supportedCoreVersions: '>=0.22.0-0 <0.23.0 || 0.21.38-dev', + hint: 'Install matching agent-device and @agent-device/replay releases, then restart the daemon.', + }); + } + return { + execution: { + create: async () => { + const [{ inspectAdReplay, runAdReplay }, { runReplayTestSuite }] = await Promise.all([ + import('@agent-device/ad-replay'), + import('@agent-device/replay-test'), + ]); + return { inspectAdReplay, runAdReplay, runReplayTestSuite }; + }, + }, + }; + }, + }; +} + +export { replayPlugin as default }; diff --git a/packages/replay/test/package-smoke.mjs b/packages/replay/test/package-smoke.mjs new file mode 100644 index 0000000000..75414bbc7d --- /dev/null +++ b/packages/replay/test/package-smoke.mjs @@ -0,0 +1,236 @@ +import assert from 'node:assert/strict'; +import { runCmdSync } from '@agent-device/host-kit/command'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; + +const root = path.resolve(import.meta.dirname, '../../..'); +function run(command, args, cwd) { + return runCmdSync(command, args, { + cwd, + env: process.env, + timeoutMs: 120_000, + maxBuffer: 16 * 1024 * 1024, + }).stdout; +} +function runCli(cli, args, cwd, env, expectedExitCode = 0) { + const result = runCmdSync(process.execPath, [cli, ...args], { + cwd, + env, + timeoutMs: 120_000, + maxBuffer: 16 * 1024 * 1024, + allowFailure: true, + }); + assert.equal(result.exitCode, expectedExitCode, result.stderr || result.stdout); + return JSON.parse(result.stdout); +} +function files(directory) { + return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const file = path.join(directory, entry.name); + return entry.isDirectory() ? files(file) : [file]; + }); +} + +/** + * Stops the detached daemon the packed CLI started for this state dir and proves from the + * daemon's own status that none survives. `--clean` is allowed only on proven detached ownership, + * so a live record refusing that stop would mean the CLI held something this test does not own. + */ +function assertIsolatedDaemonStopped(cli, cwd, env, stateDir) { + const stop = runCli( + cli, + ['daemon', 'stop', '--clean', '--state-dir', stateDir, '--json'], + cwd, + env, + ); + const status = runCli(cli, ['daemon', 'status', '--state-dir', stateDir, '--json'], cwd, env); + assert.equal(status.data.state, 'stopped', JSON.stringify({ stop, status })); +} + +test('packed core excludes native execution and a standalone replay plugin uses the real host', () => { + const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-replay-package-')); + try { + const coreTarball = path.join( + scratch, + JSON.parse( + run('npm', ['pack', '--ignore-scripts', '--json', '--pack-destination', scratch], root), + )[0].filename, + ); + const pluginTarball = path.join(scratch, 'replay.tgz'); + run('pnpm', ['pack', '--out', pluginTarball], path.join(root, 'packages/replay')); + const consumer = path.join(scratch, 'consumer'); + fs.mkdirSync(consumer); + fs.writeFileSync(path.join(consumer, 'package.json'), '{"private":true,"type":"module"}'); + run( + 'npm', + ['install', '--ignore-scripts', '--no-audit', '--no-fund', coreTarball, pluginTarball], + consumer, + ); + const core = path.join(consumer, 'node_modules/agent-device'); + const plugin = path.join(consumer, 'node_modules/@agent-device/replay'); + const manifest = JSON.parse(fs.readFileSync(path.join(plugin, 'package.json'), 'utf8')); + assert.deepEqual(Object.keys(manifest.exports), ['./agent-device']); + assert.equal(manifest.dependencies, undefined); + assert.equal(manifest.peerDependencies, undefined); + assert.ok(!fs.existsSync(path.join(plugin, 'node_modules/agent-device'))); + const coreCode = files(path.join(core, 'dist')) + .filter((file) => file.endsWith('.js')) + .map((file) => fs.readFileSync(file, 'utf8')) + .join('\n'); + for (const engineMarker of [ + 'Expected passing replay test outcome.', + 'replay accepts .ad script files. JSON replay payloads are no longer supported.', + ]) + assert.ok( + !coreCode.includes(engineMarker), + `Executable native engine leaked: ${engineMarker}`, + ); + const pluginCode = files(path.join(plugin, 'dist')) + .filter((file) => file.endsWith('.mjs')) + .map((file) => fs.readFileSync(file, 'utf8')) + .join('\n'); + assert.ok(pluginCode.includes('Expected passing replay test outcome.')); + assert.ok(pluginCode.includes('JSON replay payloads are no longer supported.')); + for (const command of ['replay', 'test']) { + const help = run( + process.execPath, + [path.join(core, 'bin/agent-device.mjs'), 'help', command], + consumer, + ); + assert.match(help, /plugin, install separately/); + assert.match(help, /agent-device plugins add @agent-device\/replay/); + } + assert.match( + run( + process.execPath, + [path.join(root, 'packages/replay/test/packed-runtime.mjs'), core, plugin, scratch], + consumer, + ), + /Packed native replay/, + ); + + // The managed route: the same packed core CLI selects the archive through its own public + // `plugins add`, with no embedded factory and no workspace to borrow an engine from. + const cli = path.join(core, 'bin/agent-device.mjs'); + const managedHome = path.join(scratch, 'managed-home'); + const managedStateDir = path.join(scratch, 'managed-state'); + const unclaimedHome = path.join(scratch, 'unclaimed-home'); + const managedEnv = { + ...Object.fromEntries( + Object.entries(process.env).filter(([name]) => !name.startsWith('AGENT_DEVICE_')), + ), + AGENT_DEVICE_HOME: managedHome, + AGENT_DEVICE_STATE_DIR: managedStateDir, + AGENT_DEVICE_CLAIMS_DIR: path.join(scratch, 'managed-claims'), + HOME: unclaimedHome, + }; + const script = path.join(consumer, 'noop.ad'); + fs.writeFileSync(script, '# managed CLI replay entrypoint and suite transport\n'); + let primaryError; + try { + // Before the selection exists, the CLI's own daemon has no ad engine to borrow. + const unselected = runCli( + cli, + ['replay', script, '--session', 'package-managed-unselected', '--json'], + consumer, + managedEnv, + 1, + ); + assert.equal(unselected.success, false); + assert.equal(unselected.error.code, 'INVALID_ARGS'); + const details = unselected.error.details; + assert.equal(details.reason, 'plugin-not-installed'); + assert.equal(details.backend, 'ad'); + assert.equal(details.package, '@agent-device/replay'); + assert.equal(details.installCommand, 'agent-device plugins add @agent-device/replay'); + assertIsolatedDaemonStopped(cli, consumer, managedEnv, managedStateDir); + + const added = runCli(cli, ['plugins', 'add', pluginTarball, '--json'], consumer, managedEnv); + const expectedIntegrity = `sha512-${crypto + .createHash('sha512') + .update(fs.readFileSync(pluginTarball)) + .digest('base64')}`; + assert.equal(added.data.artifact.name, '@agent-device/replay'); + assert.equal(added.data.artifact.integrity, expectedIntegrity); + assert.equal(added.data.artifact.compatibility, 'unchecked'); + assert.equal(added.data.restartRequired, true); + assert.equal(fs.existsSync(path.join(unclaimedHome, '.agent-device', 'config.json')), false); + assert.equal(fs.existsSync(path.join(unclaimedHome, '.agent-device', 'plugins')), false); + const inventory = runCli(cli, ['plugins', 'list', '--json'], consumer, managedEnv); + const selected = inventory.data.plugins.find( + (entry) => entry.name === '@agent-device/replay', + ); + assert.equal(typeof added.data.artifact.installation, 'string'); + assert.equal(selected?.installation, added.data.artifact.installation); + assert.equal(selected?.integrity, expectedIntegrity); + assert.equal(selected?.backend, 'ad'); + assert.equal(selected?.compatible, true); + + const replay = runCli( + cli, + ['replay', script, '--session', 'package-managed-replay', '--json'], + consumer, + managedEnv, + ); + assert.equal(replay.success, true); + assert.equal(replay.data.replayed, 0); + assert.equal(replay.data.sessionActive, false); + assert.deepEqual(replay.data.artifactPaths, []); + + const suite = runCli( + cli, + [ + 'test', + script, + '--session', + 'package-managed-suite', + '--artifacts-dir', + path.join(scratch, 'managed-artifacts'), + '--json', + ], + consumer, + managedEnv, + ); + assert.equal(suite.success, true); + assert.equal(suite.data.executed, 1); + assert.equal(suite.data.passed, 1); + assert.equal(suite.data.failed, 0); + assert.deepEqual(suite.data.failures, []); + const [suiteTest] = suite.data.tests; + assert.equal(suiteTest.status, 'passed'); + assert.equal(suiteTest.replayed, 0); + assert.ok(fs.existsSync(suiteTest.artifactsDir)); + + // The daemon that served both commands came from the store selection in this scratch home. + const running = runCli( + cli, + ['daemon', 'status', '--state-dir', managedStateDir, '--json'], + consumer, + managedEnv, + ); + assert.equal(running.data.state, 'running'); + assert.equal(running.data.ownership, 'detached'); + const served = running.data.plugins.find((entry) => entry.package === '@agent-device/replay'); + assert.equal(served?.source, 'store'); + assert.equal(served?.state, 'active'); + } catch (error) { + primaryError = error; + } + try { + assertIsolatedDaemonStopped(cli, consumer, managedEnv, managedStateDir); + } catch (cleanupError) { + if (primaryError !== undefined) { + throw new AggregateError( + [primaryError, cleanupError], + 'Replay smoke and daemon cleanup failed', + ); + } + throw cleanupError; + } + if (primaryError !== undefined) throw primaryError; + } finally { + fs.rmSync(scratch, { recursive: true, force: true }); + } +}); diff --git a/packages/replay/test/packed-runtime.mjs b/packages/replay/test/packed-runtime.mjs new file mode 100644 index 0000000000..e3fbc65bdd --- /dev/null +++ b/packages/replay/test/packed-runtime.mjs @@ -0,0 +1,96 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const [core, plugin, scratch] = process.argv.slice(2); +const { startAgentDevice } = await import(pathToFileURL(path.join(core, 'dist/src/index.js'))); +const { default: replayPlugin } = await import( + pathToFileURL(path.join(plugin, 'dist/agent-device.mjs')) +); +const script = path.join(scratch, 'empty.ad'); +fs.writeFileSync(script, '# native replay entrypoint and suite transport\n'); +const host = { + cwd: scratch, + env: { + AGENT_DEVICE_HOME: path.join(scratch, 'conflicting-home'), + AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0', + }, +}; +fs.mkdirSync(host.env.AGENT_DEVICE_HOME, { recursive: true }); +fs.writeFileSync( + path.join(host.env.AGENT_DEVICE_HOME, 'config.json'), + JSON.stringify({ + plugins: { '@agent-device/replay': { installation: 'invalid-conflicting-store' } }, + }), +); +async function embedded(label, plugins) { + return await startAgentDevice({ host, plugins, stateDir: path.join(scratch, label) }); +} +const absent = await embedded('absent', []); +try { + for (const run of [ + () => absent.client.replay.run({ path: script }), + () => absent.client.replay.test({ paths: [script] }), + ]) + await assert.rejects(run(), (error) => { + assert.equal(error.code, 'INVALID_ARGS'); + assert.equal(error.details.reason, 'plugin-not-installed'); + assert.equal(error.details.package, '@agent-device/replay'); + assert.equal(error.details.installCommand, 'agent-device plugins add @agent-device/replay'); + return true; + }); +} finally { + await absent.close(); +} +for (const [label, plugin, reason] of [ + ['incompatible', { ...replayPlugin(), apiVersion: 99 }, 'incompatible_plugin'], + ['invalid', { ...replayPlugin(), setup: () => ({ execution: {} }) }, 'invalid_plugin'], + [ + 'setup', + { + ...replayPlugin(), + setup: () => { + throw new Error('selected setup failed'); + }, + }, + 'plugin_setup_failed', + ], +]) { + const runtime = await embedded(label, [plugin]); + try { + await assert.rejects(runtime.client.replay.run({ path: script }), (error) => { + assert.equal(error.details.reason, reason); + return true; + }); + } finally { + await runtime.close(); + } +} +const installed = await embedded('installed', [replayPlugin()]); +try { + const replay = await installed.client.replay.run({ path: script }); + assert.equal(replay.replayed, 0); + assert.equal(replay.sessionActive, false); + assert.deepEqual(replay.artifactPaths, []); + const suite = await installed.client.replay.test({ + paths: [script], + artifactsDir: path.join(scratch, 'artifacts'), + }); + assert.equal(suite.passed, 1); + assert.equal(suite.failed, 0); + assert.equal(suite.tests[0].status, 'passed'); + assert.ok(fs.existsSync(suite.artifactsDir)); + const malformed = path.join(scratch, 'legacy.ad'); + fs.writeFileSync(malformed, '[{"command":"open"}]'); + await assert.rejects(installed.client.replay.run({ path: malformed }), (error) => { + assert.equal(error.code, 'INVALID_ARGS'); + assert.match(error.message, /JSON replay payloads are no longer supported/); + return true; + }); +} finally { + await installed.close(); +} +process.stdout.write( + 'Packed native replay, suites, failure isolation and embedded scopes passed.\n', +); diff --git a/packages/replay/tsconfig.json b/packages/replay/tsconfig.json new file mode 100644 index 0000000000..9b836387f6 --- /dev/null +++ b/packages/replay/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "composite": true, + "noEmit": false, + "emitDeclarationOnly": true, + "declaration": true, + "declarationDir": "./dist-types", + "rootDir": ".", + "tsBuildInfoFile": "./dist-types/index.tsbuildinfo", + "paths": { + "agent-device/plugins": ["./node_modules/agent-device/src/sdk/plugins.ts"] + } + }, + "include": ["src"], + "references": [ + { + "path": "../ad-replay" + }, + { + "path": "../replay-test" + }, + { + "path": "../plugins" + }, + { + "path": "../test-kit" + } + ] +} diff --git a/packages/replay/tsdown.config.ts b/packages/replay/tsdown.config.ts new file mode 100644 index 0000000000..84fe67d349 --- /dev/null +++ b/packages/replay/tsdown.config.ts @@ -0,0 +1,26 @@ +import { defineConfig } from 'tsdown'; + +type BuildLog = Readonly<{ code?: string; message: string }>; + +function rejectUnresolvedWorkspaceImports( + level: string, + log: BuildLog, + handler: (level: string, log: BuildLog) => void, +): void { + if (log.code === 'UNRESOLVED_IMPORT') throw new Error(log.message); + handler(level, log); +} + +export default defineConfig({ + entry: { 'agent-device': 'src/plugin.ts' }, + outDir: 'dist', + tsconfig: '../../tsconfig.lib.json', + format: 'esm', + platform: 'node', + target: 'es2022', + minify: true, + dts: true, + hash: false, + deps: { alwaysBundle: [/^@agent-device\//] }, + inputOptions: { onLog: rejectUnresolvedWorkspaceImports }, +}); diff --git a/packages/test-kit/src/index.ts b/packages/test-kit/src/index.ts index 5d74593d59..02cb6ff37c 100644 --- a/packages/test-kit/src/index.ts +++ b/packages/test-kit/src/index.ts @@ -101,13 +101,9 @@ export { } from './loopback.ts'; export { pluginHome, - registrationSource, - selectPlugin, - selectPluginManifest, selectV2Plugin, v2RegistrationSource, webDriverPluginSource, - writePlugin, } from './plugin.fixtures.ts'; export { formatRef, @@ -181,3 +177,12 @@ export { type StreamCapture, type StreamCaptureOptions, } from './stream-capture.ts'; + +export { maestroValidationArb, MAESTRO_MUTATION_NAMES } from './maestro-validation-arbitraries.ts'; +export { + ACCEPT, + SAFE_VALUES, + encodeValidationCase, + type ValidationCase, + type ValidationExpectation, +} from './validation-values.ts'; diff --git a/scripts/fuzz/validation-arbitraries-maestro.ts b/packages/test-kit/src/maestro-validation-arbitraries.ts similarity index 94% rename from scripts/fuzz/validation-arbitraries-maestro.ts rename to packages/test-kit/src/maestro-validation-arbitraries.ts index 6b47745bb7..0e924dc013 100644 --- a/scripts/fuzz/validation-arbitraries-maestro.ts +++ b/packages/test-kit/src/maestro-validation-arbitraries.ts @@ -7,8 +7,7 @@ // cannot silently drift from the converter. import fc from 'fast-check'; -import { encodeValidationCase } from './validation-case.ts'; -import { ACCEPT, SAFE_VALUES } from './validation-values.ts'; +import { ACCEPT, SAFE_VALUES, encodeValidationCase } from './validation-values.ts'; // --------------------------------------------------------------------------------------------- @@ -49,6 +48,8 @@ function validMaestroCommand(pick: number, salt: number): string[] { () => ['- scrollUntilVisible:', ' element:', ` text: ${text}`], () => ['- repeat:', ' times: 2', ' commands:', ' - back'], () => ['- runFlow: other.yaml'], + () => ['- retry:', ' maxRetries: 2', ' commands:', ' - back'], + () => ['- runScript: checks.js'], () => ['- setPermissions:', ' permissions:', ' camera: allow'], () => ['- setPermissions:', ' permissions:', ' all: deny'], () => ['- launchApp:', ' appId: com.example.app', ' permissions:', ' camera: allow'], @@ -92,6 +93,11 @@ const MAESTRO_MUTATIONS: readonly MaestroMutation[] = [ lines: (salt) => salt % 2 === 0 ? ['- inputText:'] : ['- extendedWaitUntil:', ' timeout: 500'], }, + { + name: 'bad-retry-max-retries', + code: 'INVALID_ARGS', + lines: () => ['- retry:', ' maxRetries: invalid', ' commands:', ' - back'], + }, { name: 'bad-press-key', code: 'INVALID_ARGS', lines: () => ['- pressKey: sleep'] }, { name: 'scroll-options', code: 'INVALID_ARGS', lines: () => ['- scroll:', ' direction: UP'] }, { diff --git a/packages/test-kit/src/plugin.fixtures.ts b/packages/test-kit/src/plugin.fixtures.ts index 7b65aa248b..d402e0b116 100644 --- a/packages/test-kit/src/plugin.fixtures.ts +++ b/packages/test-kit/src/plugin.fixtures.ts @@ -9,58 +9,44 @@ export function pluginHome() { return { home, env: { AGENT_DEVICE_HOME: home } }; } -export function writePlugin( - project: string, - name = '@example/provider', - apiVersion = 1, - provider = 'example', - source = 'throw new Error("evaluated");', +/** + * Installs a plugin package: no `agentDevicePlugin` manifest, an `./agent-device` export, options + * recorded. `exports` and `manifest` override the package.json fields, `files` adds extra files. + */ +export function selectV2Plugin( + home: string, + name: string, + source: string, + options: { + exports?: unknown; + manifest?: Record; + files?: Record; + selectionOptions?: unknown; + } = {}, ) { - const directory = path.join(project, 'node_modules', name); + const installation = crypto.randomUUID(); + const directory = path.join(home, 'plugins', installation, 'node_modules', name); fs.mkdirSync(directory, { recursive: true }); fs.writeFileSync( path.join(directory, 'package.json'), JSON.stringify({ name, - version: '1.2.3', + version: '2.0.0', type: 'module', - agentDevicePlugin: { apiVersion, provider, entry: './plugin.js' }, + exports: + 'exports' in options ? options.exports : { './agent-device': { import: './plugin.mjs' } }, + ...options.manifest, }), ); - fs.writeFileSync(path.join(directory, 'plugin.js'), source); + fs.writeFileSync(path.join(directory, 'plugin.mjs'), source); + for (const [file, contents] of Object.entries(options.files ?? {})) { + fs.mkdirSync(path.dirname(path.join(directory, file)), { recursive: true }); + fs.writeFileSync(path.join(directory, file), contents); + } + recordSelection(home, name, installation, options.selectionOptions); return directory; } -export function selectPlugin( - home: string, - name: string, - provider: string, - source: string, - apiVersion = 1, -) { - const installation = crypto.randomUUID(); - writePlugin(path.join(home, 'plugins', installation), name, apiVersion, provider, source); - recordSelection(home, name, installation); -} - -/** Installs `manifest` as-is, with an entry file that throws if evaluated. */ -export function selectPluginManifest( - home: string, - manifest: { - name: string; - version: string; - agentDevicePlugin: Record & { entry: string }; - }, -) { - const installation = crypto.randomUUID(); - const directory = path.join(home, 'plugins', installation, 'node_modules', manifest.name); - const entry = path.join(directory, manifest.agentDevicePlugin.entry); - fs.mkdirSync(path.dirname(entry), { recursive: true }); - fs.writeFileSync(path.join(directory, 'package.json'), JSON.stringify(manifest)); - fs.writeFileSync(entry, 'throw new Error("evaluated");'); - recordSelection(home, manifest.name, installation); -} - function recordSelection( home: string, name: string, @@ -74,19 +60,6 @@ function recordSelection( fs.writeFileSync(configPath, JSON.stringify(config)); } -export function registrationSource(provider: string, shutdownFile?: string) { - return `import fs from 'node:fs'; - export default host => ({ - runtime: { provider: ${JSON.stringify(provider)}, - ownsDevice: () => false, getInteractor: () => undefined, - deviceInventoryProvider: async () => [], leaseLifecycle: {}, - shutdown: async () => { ${shutdownFile ? `fs.writeFileSync(${JSON.stringify(shutdownFile)}, 'shutdown');` : ''} }, - options: host.options, env: host.env, createError: host.createError }, - platformModule: { owner: { kind: 'provider-runtime', provider: ${JSON.stringify(provider)}, instance: 'test' }, - loadRuntime: async () => { throw new Error('lazy'); } } - });`; -} - const CONSUMED_PROFILE_FIELDS: Record = { providerApp: 'consumed', providerOsVersion: 'consumed', @@ -112,31 +85,8 @@ const CONSUMED_PROFILE_FIELDS: Record = { awsInteractionMode: 'consumed', }; -/** A `{ webDriver }` factory with a total field declaration; `connection` is a JS expression. */ -export function webDriverPluginSource( - provider: string, - refused: readonly ProviderProfileField[] = [], - connection?: string, -) { - const fields = { - ...CONSUMED_PROFILE_FIELDS, - ...Object.fromEntries(refused.map((field) => [field, 'refused'])), - }; - const webDriver = { - provider, - endpoint: 'https://webdriver.test/wd/hub/', - platform: 'android', - deviceName: provider, - profileFields: { provider, label: provider, fields }, - requestPolicy: { retryAttempts: 0 }, - }; - return `export default (host) => ({ webDriver: ${JSON.stringify(webDriver)}${ - connection ? `, connection: ${connection}` : '' - } });`; -} - /** - * A v2 plugin factory module. `extra` is spliced into the returned plugin object, so a test can add + * A plugin factory module. `extra` is spliced into the returned plugin object, so a test can add * `connection` or override `credentials`; `shutdownFile` is written when the runtime shuts down. */ export function v2RegistrationSource( @@ -161,37 +111,25 @@ export function v2RegistrationSource( });`; } -/** Installs a v2 package: no `agentDevicePlugin` manifest, an `./agent-device` export, options recorded. */ -export function selectV2Plugin( - home: string, - name: string, - source: string, - options: { - exports?: unknown; - manifest?: Record; - files?: Record; - selectionOptions?: unknown; - } = {}, +/** A `{ webDriver }` factory with a total field declaration; `refused` fields the engine must refuse. */ +export function webDriverPluginSource( + provider: string, + refused: readonly ProviderProfileField[] = [], ) { - const installation = crypto.randomUUID(); - const directory = path.join(home, 'plugins', installation, 'node_modules', name); - fs.mkdirSync(directory, { recursive: true }); - fs.writeFileSync( - path.join(directory, 'package.json'), - JSON.stringify({ - name, - version: '2.0.0', - type: 'module', - exports: - 'exports' in options ? options.exports : { './agent-device': { import: './plugin.mjs' } }, - ...options.manifest, - }), - ); - fs.writeFileSync(path.join(directory, 'plugin.mjs'), source); - for (const [file, contents] of Object.entries(options.files ?? {})) { - fs.mkdirSync(path.dirname(path.join(directory, file)), { recursive: true }); - fs.writeFileSync(path.join(directory, file), contents); - } - recordSelection(home, name, installation, options.selectionOptions); - return directory; + const fields = { + ...CONSUMED_PROFILE_FIELDS, + ...Object.fromEntries(refused.map((field) => [field, 'refused'])), + }; + const webDriver = { + provider, + endpoint: 'https://webdriver.test/wd/hub/', + platform: 'android', + deviceName: provider, + profileFields: { provider, label: provider, fields }, + requestPolicy: { retryAttempts: 0 }, + }; + return `export default () => ({ + apiVersion: 2, provider: ${JSON.stringify(provider)}, credentials: { variables: [] }, + setup: async () => ({ webDriver: ${JSON.stringify(webDriver)} }), + });`; } diff --git a/scripts/fuzz/validation-values.ts b/packages/test-kit/src/validation-values.ts similarity index 66% rename from scripts/fuzz/validation-values.ts rename to packages/test-kit/src/validation-values.ts index 6d37e1fc53..7ce99fcb4a 100644 --- a/scripts/fuzz/validation-values.ts +++ b/packages/test-kit/src/validation-values.ts @@ -19,3 +19,15 @@ export const SAFE_VALUES = [ /** The accept expectation, shared so a valid case reads the same in both generators. */ export const ACCEPT = { outcome: 'accept' } as const; + +export type ValidationExpectation = { outcome: 'accept' } | { outcome: 'reject'; code: string }; + +export type ValidationCase = { + payload: string[] | string; + mutation: string; + expect: ValidationExpectation; +}; + +export function encodeValidationCase(validationCase: ValidationCase): string { + return JSON.stringify(validationCase); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 655e62ee8e..d66ab4b184 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -23,15 +23,18 @@ importers: .: devDependencies: - '@agent-device/ad-replay': - specifier: workspace:* - version: link:packages/ad-replay '@agent-device/ad-script': specifier: workspace:* version: link:packages/ad-script '@agent-device/apple-runner': specifier: workspace:* version: link:packages/apple-runner + '@agent-device/aws-device-farm': + specifier: workspace:* + version: link:packages/provider-aws-device-farm + '@agent-device/browserstack': + specifier: workspace:* + version: link:packages/provider-browserstack '@agent-device/capture-kit': specifier: workspace:* version: link:packages/capture-kit @@ -71,9 +74,6 @@ importers: '@agent-device/kernel': specifier: workspace:* version: link:packages/kernel - '@agent-device/maestro': - specifier: workspace:* - version: link:packages/maestro '@agent-device/platform-android': specifier: workspace:* version: link:packages/platform-android @@ -116,9 +116,6 @@ importers: '@agent-device/replay-port': specifier: workspace:* version: link:packages/replay-port - '@agent-device/replay-test': - specifier: workspace:* - version: link:packages/replay-test '@agent-device/revyl': specifier: workspace:* version: link:packages/provider-revyl @@ -244,13 +241,16 @@ importers: version: 3.2.0 tsdown: specifier: ^0.22.14 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(@volar/typescript@2.4.30(typescript@7.0.2))(publint@0.3.24)(typescript@7.0.2) + version: 0.22.14(@arethetypeswrong/core@0.18.5)(@volar/typescript@2.4.30(typescript@7.0.2))(publint@0.3.24)(typescript@7.0.2)(unrun@0.3.1) typescript: specifier: ^7.0.2 version: 7.0.2 undici: specifier: 7.30.1 version: 7.30.1 + unrun: + specifier: 0.3.1 + version: 0.3.1 vite: specifier: ^8.3.5 version: 8.3.8(@types/node@22.20.1)(yaml@2.9.1) @@ -313,6 +313,12 @@ importers: specifier: workspace:* version: link:../test-kit + packages/build-config: + devDependencies: + rolldown: + specifier: 1.2.5 + version: 1.2.5 + packages/capture-kit: dependencies: '@agent-device/contracts': @@ -380,9 +386,6 @@ importers: packages/command-output: dependencies: - '@agent-device/ad-replay': - specifier: workspace:* - version: link:../ad-replay '@agent-device/capture-kit': specifier: workspace:* version: link:../capture-kit @@ -505,9 +508,6 @@ importers: packages/daemon: dependencies: - '@agent-device/ad-replay': - specifier: workspace:* - version: link:../ad-replay '@agent-device/ad-script': specifier: workspace:* version: link:../ad-script @@ -532,9 +532,6 @@ importers: '@agent-device/kernel': specifier: workspace:* version: link:../kernel - '@agent-device/maestro': - specifier: workspace:* - version: link:../maestro '@agent-device/platform-android': specifier: workspace:* version: link:../platform-android @@ -547,9 +544,6 @@ importers: '@agent-device/replay-port': specifier: workspace:* version: link:../replay-port - '@agent-device/replay-test': - specifier: workspace:* - version: link:../replay-test '@agent-device/selectors': specifier: workspace:* version: link:../selectors @@ -557,12 +551,24 @@ importers: specifier: workspace:* version: link:../session-journal devDependencies: + '@agent-device/ad-replay': + specifier: workspace:* + version: link:../ad-replay '@agent-device/apple-runner': specifier: workspace:* version: link:../apple-runner + '@agent-device/maestro': + specifier: workspace:* + version: link:../maestro + '@agent-device/plugins': + specifier: workspace:* + version: link:../plugins '@agent-device/proxy': specifier: workspace:* version: link:../proxy + '@agent-device/replay': + specifier: workspace:* + version: link:../replay '@agent-device/test-kit': specifier: workspace:* version: link:../test-kit @@ -584,9 +590,6 @@ importers: packages/daemon-client: dependencies: - '@agent-device/ad-replay': - specifier: workspace:* - version: link:../ad-replay '@agent-device/command-registry': specifier: workspace:* version: link:../command-registry @@ -682,7 +685,7 @@ importers: packages/kernel: {} packages/maestro: - dependencies: + devDependencies: '@agent-device/ad-script': specifier: workspace:* version: link:../ad-script @@ -704,7 +707,12 @@ importers: '@agent-device/selectors': specifier: workspace:* version: link:../selectors - devDependencies: + '@agent-device/test-kit': + specifier: workspace:* + version: link:../test-kit + agent-device: + specifier: workspace:* + version: link:../.. undici: specifier: 7.30.1 version: 7.30.1 @@ -865,6 +873,45 @@ importers: specifier: workspace:* version: link:../test-kit + packages/provider-aws-device-farm: + devDependencies: + '@agent-device/build-config': + specifier: workspace:* + version: link:../build-config + '@agent-device/contracts': + specifier: workspace:* + version: link:../contracts + '@agent-device/kernel': + specifier: workspace:* + version: link:../kernel + '@agent-device/provider-webdriver': + specifier: workspace:* + version: link:../provider-webdriver + agent-device: + specifier: workspace:* + version: link:../.. + + packages/provider-browserstack: + devDependencies: + '@agent-device/build-config': + specifier: workspace:* + version: link:../build-config + '@agent-device/contracts': + specifier: workspace:* + version: link:../contracts + '@agent-device/kernel': + specifier: workspace:* + version: link:../kernel + '@agent-device/provider-webdriver': + specifier: workspace:* + version: link:../provider-webdriver + '@agent-device/test-kit': + specifier: workspace:* + version: link:../test-kit + agent-device: + specifier: workspace:* + version: link:../.. + packages/provider-limrun: dependencies: '@agent-device/capture-kit': @@ -892,6 +939,9 @@ importers: packages/provider-revyl: devDependencies: + '@agent-device/build-config': + specifier: workspace:* + version: link:../build-config '@agent-device/capture-kit': specifier: workspace:* version: link:../capture-kit @@ -916,6 +966,9 @@ importers: packages/provider-testmu: devDependencies: + '@agent-device/build-config': + specifier: workspace:* + version: link:../build-config '@agent-device/contracts': specifier: workspace:* version: link:../contracts @@ -1008,6 +1061,9 @@ importers: packages/proxy: devDependencies: + '@agent-device/build-config': + specifier: workspace:* + version: link:../build-config '@agent-device/contracts': specifier: workspace:* version: link:../contracts @@ -1065,11 +1121,26 @@ importers: specifier: ^3.2.0 version: 3.2.0 - packages/replay-port: - dependencies: + packages/replay: + devDependencies: '@agent-device/ad-replay': specifier: workspace:* version: link:../ad-replay + '@agent-device/plugins': + specifier: workspace:* + version: link:../plugins + '@agent-device/replay-test': + specifier: workspace:* + version: link:../replay-test + '@agent-device/test-kit': + specifier: workspace:* + version: link:../test-kit + agent-device: + specifier: workspace:* + version: link:../.. + + packages/replay-port: + dependencies: '@agent-device/ad-script': specifier: workspace:* version: link:../ad-script @@ -1091,12 +1162,9 @@ importers: '@agent-device/kernel': specifier: workspace:* version: link:../kernel - '@agent-device/maestro': - specifier: workspace:* - version: link:../maestro - '@agent-device/replay-test': + '@agent-device/plugins': specifier: workspace:* - version: link:../replay-test + version: link:../plugins '@agent-device/selectors': specifier: workspace:* version: link:../selectors @@ -5508,6 +5576,16 @@ packages: unist-util-visit@5.1.0: resolution: {integrity: sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==} + unrun@0.3.1: + resolution: {integrity: sha512-onIck/oNnCaytwths1ZVp1LK2Gq2hPoyFhiHebObuUXqR3S0uHuLLaBK8K6mRRgV7Ptip8AnNvaUsgzwWwBZuA==} + engines: {node: ^22.13.0 || >=24.0.0} + hasBin: true + peerDependencies: + synckit: ^0.11.11 + peerDependenciesMeta: + synckit: + optional: true + unstorage@1.17.6: resolution: {integrity: sha512-gjKtcmn/KwZuJZO9o2sc0esAQnhmTw0LviDHwevTXbJMYs0dRTp8ZEEWXHU0vTpzbN3cA0yxlTeyXssMp3zDqw==} peerDependencies: @@ -5738,23 +5816,17 @@ packages: resolution: {integrity: sha512-9K2k72s4n7rV9s4bX0MyjbX9iBribvKZbBJKuEmTCZfeWJXs6Yh7bGpY4eoc7UufAjvpheBqwyZCOIPBvxCv0A==} peerDependencies: '@volar/language-service': ~2.4.0 - typescript: '*' peerDependenciesMeta: '@volar/language-service': optional: true - typescript: - optional: true volar-service-typescript@0.0.71: resolution: {integrity: sha512-yTtM/BVT6hoyEYnDtaCyAtNhdNeS/mhTTABlBOdw3NNiRBUin3IznFJpgfjer4c6RYopiPjjQjc9VFhxVl1mLw==} peerDependencies: '@volar/language-service': ~2.4.0 - typescript: '*' peerDependenciesMeta: '@volar/language-service': optional: true - typescript: - optional: true volar-service-yaml@0.0.71: resolution: {integrity: sha512-qYGWGuVpUTnZGu5P/CR4KLK4aIR8RrcVnmfZ2eRcj9q/I8VZCoC5yy9FtEvfNvnDp4MU17yhdJcvpQPIqhJS2Q==} @@ -6068,8 +6140,8 @@ snapshots: volar-service-emmet: 0.0.71(@volar/language-service@2.4.30(typescript@5.9.3)) volar-service-html: 0.0.71(@volar/language-service@2.4.30(typescript@5.9.3)) volar-service-prettier: 0.0.71(@volar/language-service@2.4.30(typescript@5.9.3))(prettier@3.9.10) - volar-service-typescript: 0.0.71(@volar/language-service@2.4.30(typescript@5.9.3))(typescript@5.9.3) - volar-service-typescript-twoslash-queries: 0.0.71(@volar/language-service@2.4.30(typescript@5.9.3))(typescript@5.9.3) + volar-service-typescript: 0.0.71(@volar/language-service@2.4.30(typescript@5.9.3)) + volar-service-typescript-twoslash-queries: 0.0.71(@volar/language-service@2.4.30(typescript@5.9.3)) volar-service-yaml: 0.0.71(@volar/language-service@2.4.30(typescript@5.9.3)) vscode-html-languageservice: 5.6.2 vscode-uri: 3.2.0 @@ -10090,7 +10162,7 @@ snapshots: dependencies: typescript: 7.0.2 - tsdown@0.22.14(@arethetypeswrong/core@0.18.5)(@volar/typescript@2.4.30(typescript@7.0.2))(publint@0.3.24)(typescript@7.0.2): + tsdown@0.22.14(@arethetypeswrong/core@0.18.5)(@volar/typescript@2.4.30(typescript@7.0.2))(publint@0.3.24)(typescript@7.0.2)(unrun@0.3.1): dependencies: ansis: 4.3.1 cac: 7.0.0 @@ -10111,6 +10183,7 @@ snapshots: '@arethetypeswrong/core': 0.18.5 publint: 0.3.24 typescript: 7.0.2 + unrun: 0.3.1 transitivePeerDependencies: - '@typescript/native-preview' - '@volar/typescript' @@ -10243,6 +10316,10 @@ snapshots: unist-util-is: 6.0.1 unist-util-visit-parents: 6.0.2 + unrun@0.3.1: + dependencies: + rolldown: 1.2.19 + unstorage@1.17.6: dependencies: anymatch: 3.1.3 @@ -10359,14 +10436,13 @@ snapshots: '@volar/language-service': 2.4.30(typescript@5.9.3) prettier: 3.9.10 - volar-service-typescript-twoslash-queries@0.0.71(@volar/language-service@2.4.30(typescript@5.9.3))(typescript@5.9.3): + volar-service-typescript-twoslash-queries@0.0.71(@volar/language-service@2.4.30(typescript@5.9.3)): dependencies: vscode-uri: 3.2.0 optionalDependencies: '@volar/language-service': 2.4.30(typescript@5.9.3) - typescript: 5.9.3 - volar-service-typescript@0.0.71(@volar/language-service@2.4.30(typescript@5.9.3))(typescript@5.9.3): + volar-service-typescript@0.0.71(@volar/language-service@2.4.30(typescript@5.9.3)): dependencies: path-browserify: 1.0.1 semver: 7.8.5 @@ -10376,7 +10452,6 @@ snapshots: vscode-uri: 3.2.0 optionalDependencies: '@volar/language-service': 2.4.30(typescript@5.9.3) - typescript: 5.9.3 volar-service-yaml@0.0.71(@volar/language-service@2.4.30(typescript@5.9.3)): dependencies: diff --git a/scripts/__tests__/help-conformance-sample-producers.ts b/scripts/__tests__/help-conformance-sample-producers.ts index 75e3df243b..587ac727d8 100644 --- a/scripts/__tests__/help-conformance-sample-producers.ts +++ b/scripts/__tests__/help-conformance-sample-producers.ts @@ -1,5 +1,11 @@ import type { CapturedSample } from '../help-conformance-sample-outputs.mjs'; -import { withCapturedStderrAsync } from '@agent-device/test-kit'; +import { + withCapturedStderrAsync, + pluginHome, + selectV2Plugin, + restoreEnv, +} from '@agent-device/test-kit'; +import { primePluginConnections } from '@agent-device/plugins/connection'; import { AMBIGUOUS_MATCH_SAMPLE, APP_NOT_INSTALLED_SAMPLE, @@ -449,40 +455,55 @@ export const SAMPLE_PRODUCERS: SampleProducer[] = [ name: 'BROWSERSTACK_CONNECT_SAMPLE', producer: 'the connect success renderer with verified BrowserStack readiness', sample: BROWSERSTACK_CONNECT_SAMPLE, - render: () => { - const state = { - version: 1, - session: 'adc-browserstack', - tenant: 'direct-browserstack', - runId: 'run-browserstack', - leaseProvider: 'browserstack', - platform: 'android', - remoteConfigPath: '/tmp/browserstack.json', - remoteConfigHash: 'fixture', - connectedAt: '2026-08-03T00:00:00.000Z', - updatedAt: '2026-08-03T00:00:00.000Z', - } satisfies RemoteConnectionState; - const facts = { - provider: 'browserstack', - service: 'BrowserStack', - verificationMessage: 'Credentials, device, and uploaded app verified.', - device: { - status: 'verified', - name: 'Google Pixel 8', + render: async () => { + const { home } = pluginHome(); + selectV2Plugin( + home, + '@agent-device/browserstack', + `import browserstack from ${JSON.stringify(import.meta.resolve('@agent-device/browserstack'))}; export default browserstack;`, + { selectionOptions: {} }, + ); + const previousHome = process.env.AGENT_DEVICE_HOME; + process.env.AGENT_DEVICE_HOME = home; + try { + await primePluginConnections(process.env); + const state = { + version: 1, + session: 'adc-browserstack', + tenant: 'direct-browserstack', + runId: 'run-browserstack', + leaseProvider: 'browserstack', platform: 'android', - osVersion: '14.0', - }, - app: { - status: 'verified', - name: 'sample.apk', - reference: 'bs://app-id', - version: '1.2.3', - }, - } satisfies ConnectVerification; - return renderConnectSuccess({ - state, - readiness: presentConnectReadiness(state, facts), - }); + remoteConfigPath: '/tmp/browserstack.json', + remoteConfigHash: 'fixture', + connectedAt: '2026-08-03T00:00:00.000Z', + updatedAt: '2026-08-03T00:00:00.000Z', + } satisfies RemoteConnectionState; + const facts = { + provider: 'browserstack', + service: 'BrowserStack', + verificationMessage: 'Credentials, device, and uploaded app verified.', + device: { + status: 'verified', + name: 'Google Pixel 8', + platform: 'android', + osVersion: '14.0', + }, + app: { + status: 'verified', + name: 'sample.apk', + reference: 'bs://app-id', + version: '1.2.3', + }, + } satisfies ConnectVerification; + return renderConnectSuccess({ + state, + readiness: presentConnectReadiness(state, facts, process.env), + env: process.env, + }); + } finally { + restoreEnv('AGENT_DEVICE_HOME', previousHome); + } }, }, ]; diff --git a/scripts/__tests__/install-workspace-replay-plugins.test.ts b/scripts/__tests__/install-workspace-replay-plugins.test.ts new file mode 100644 index 0000000000..366527c79f --- /dev/null +++ b/scripts/__tests__/install-workspace-replay-plugins.test.ts @@ -0,0 +1,42 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { afterEach, test, vi } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { installWorkspaceReplayPlugins } from '../install-workspace-replay-plugins.ts'; + +afterEach(() => vi.restoreAllMocks()); + +test('failed second staging keeps the previous config and removes both new installations', () => { + const home = mkdtempForTestSync('workspace-plugin-staging-'); + const config = '{"platform":"android","plugins":{"existing":{"installation":"kept"}}}'; + const file = path.join(home, 'config.json'); + fs.writeFileSync(file, config); + const symlink = fs.symlinkSync; + vi.spyOn(fs, 'symlinkSync').mockImplementation((target, destination, type) => { + if (path.basename(String(target)) === 'replay') throw new Error('second staging failed'); + symlink(target, destination, type); + }); + assert.throws( + () => installWorkspaceReplayPlugins({ AGENT_DEVICE_HOME: home }, true), + /second staging failed/, + ); + assert.equal(fs.readFileSync(file, 'utf8'), config); + assert.deepEqual(fs.readdirSync(path.join(home, 'plugins')), []); +}); + +test('failed publication keeps the previous config and removes staged installations', () => { + const home = mkdtempForTestSync('workspace-plugin-publish-'); + const config = '{"platform":"android"}'; + const file = path.join(home, 'config.json'); + fs.writeFileSync(file, config); + vi.spyOn(fs, 'renameSync').mockImplementation(() => { + throw new Error('publish failed'); + }); + assert.throws( + () => installWorkspaceReplayPlugins({ AGENT_DEVICE_HOME: home }, true), + /publish failed/, + ); + assert.equal(fs.readFileSync(file, 'utf8'), config); + assert.deepEqual(fs.readdirSync(path.join(home, 'plugins')), []); +}); diff --git a/scripts/build-entries.ts b/scripts/build-entries.ts index d97666fbaa..0467a6eff3 100644 --- a/scripts/build-entries.ts +++ b/scripts/build-entries.ts @@ -7,7 +7,6 @@ export const buildEntries = { 'remote-config': 'src/sdk/remote-config.ts', 'install-source': 'src/sdk/install-source.ts', 'android-adb': 'src/sdk/android-adb.ts', - limrun: 'src/sdk/limrun.ts', plugins: 'src/sdk/plugins.ts', 'plugins/webdriver': 'src/sdk/plugin-webdriver.ts', contracts: 'src/sdk/contracts.ts', @@ -17,8 +16,6 @@ export const buildEntries = { 'internal/bin': 'src/bin.ts', 'internal/companion-tunnel': 'packages/react-native/src/companion/companion-tunnel.ts', 'internal/daemon': 'src/daemon.ts', - 'internal/run-script-child': 'packages/maestro/src/daemon-port/run-script-child.ts', - 'internal/run-script-http-child': 'packages/maestro/src/daemon-port/run-script-http-child.ts', 'internal/png-worker': 'packages/capture-kit/src/png-worker.ts', 'internal/update-check-entry': 'src/cli/update-check-entry.ts', } as const; diff --git a/scripts/capability-matrix/collect.ts b/scripts/capability-matrix/collect.ts index 2752911eef..2c3e7b08ca 100644 --- a/scripts/capability-matrix/collect.ts +++ b/scripts/capability-matrix/collect.ts @@ -16,11 +16,11 @@ import { runtimeModule as webRuntimeModule } from '@agent-device/platform-web'; import { runtimeModule as vegaRuntimeModule } from '@agent-device/platform-vega'; import { runtimeModule as harmonyosRuntimeModule } from '@agent-device/platform-harmonyos'; import { runtimeModule as linuxRuntimeModule } from '@agent-device/platform-linux'; -import { BUNDLED_CLOUD_WEBDRIVER_PROVIDERS } from '@agent-device/provider-webdriver'; import { createCloudWebDriverRuntime } from '@agent-device/provider-webdriver/plugin'; -import { CLOUD_WEBDRIVER_PROVIDERS } from '@agent-device/provider-webdriver/providers'; -import type { RunHostCommand } from '@agent-device/provider-webdriver'; +import { createPluginHost, type RunHostCommand } from '@agent-device/plugins/host'; import testmuPlugin from '@agent-device/testmu'; +import browserstackPlugin from '@agent-device/browserstack'; +import awsDeviceFarmPlugin from '@agent-device/aws-device-farm'; import revylPlugin from '@agent-device/revyl'; import type { DeviceLease, ProviderDeviceRuntime } from '@agent-device/contracts/device'; import type { @@ -112,43 +112,32 @@ async function loadLocalRuntimes(host: PlatformRuntimeHost): Promise> = { - [CLOUD_WEBDRIVER_PROVIDERS.browserStack]: 'browserstack', - [CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm]: 'aws-device-farm', +/** The plugin packages whose factory setup() builds the WebDriver the matrix asks for. */ +const CLOUD_WEBDRIVER_PLUGINS: Readonly> = { + testmu: testmuPlugin, + browserstack: browserstackPlugin, + 'aws-device-farm': awsDeviceFarmPlugin, }; -/** The provider's WebDriver options, from the bundled registration or the plugin package. */ +/** The provider's WebDriver options, from the plugin package the target names. */ async function cloudWebDriverOptions( plugin: string, runHostCommand: RunHostCommand, ): Promise> { - if (plugin === 'testmu') { - // The package's default export is the plugin factory; the WebDriver is what its setup() builds. - const plugin_ = testmuPlugin(); - if (!plugin_.setup) - throw new Error('The TestMu plugin exposes no setup() to build a WebDriver from.'); - const created = (await plugin_.setup({ - env: PROVIDER_ENV, - clientVersion: '0.0.0', - } as never)) as { - webDriver: Record; - }; - return created.webDriver; - } - const providerName = CLOUD_WEBDRIVER_PLUGIN_PROVIDERS[plugin]; - if (!providerName) throw new Error(`Unknown cloud WebDriver plugin "${plugin}".`); - const registration = BUNDLED_CLOUD_WEBDRIVER_PROVIDERS.find( - (candidate) => candidate.declaration.provider === providerName, - ); - if (!registration) { - throw new Error(`No bundled cloud WebDriver registration for plugin "${plugin}".`); - } - const created = await registration.create({ - env: PROVIDER_ENV, + const factory = CLOUD_WEBDRIVER_PLUGINS[plugin]; + if (!factory) throw new Error(`Unknown cloud WebDriver plugin "${plugin}".`); + // The package's default export is the plugin factory; the WebDriver is what its setup() builds. + const plugin_ = factory(); + if (!plugin_.setup) + throw new Error(`The ${plugin} plugin exposes no setup() to build a WebDriver from.`); + const created = (await plugin_.setup({ + ...createPluginHost({ env: PROVIDER_ENV, cwd: '/' }, undefined), clientVersion: '0.0.0', runHostCommand, - } as never); - return created.webDriver as unknown as Record; + })) as { + webDriver: Record; + }; + return created.webDriver; } function cloudLease(target: Target & { readonly kind: 'cloud-webdriver' }): DeviceLease { diff --git a/scripts/capability-matrix/seams.ts b/scripts/capability-matrix/seams.ts index 156c436642..4a10951e34 100644 --- a/scripts/capability-matrix/seams.ts +++ b/scripts/capability-matrix/seams.ts @@ -8,7 +8,7 @@ import moduleHooks from 'node:module'; import { createAgentBrowserWebProvider, withWebProvider } from '@agent-device/platform-web'; import { createWebInteractor } from '@agent-device/platform-web/interactor'; -import type { RunHostCommand } from '@agent-device/provider-webdriver'; +import type { RunHostCommand } from '@agent-device/plugins/host'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { resolveWebNetworkTransport } from '../../src/platform-runtime-network-web-transport.ts'; diff --git a/scripts/check-affected/device-lanes.test.ts b/scripts/check-affected/device-lanes.test.ts index 72452fa6ba..9e04dfea8f 100644 --- a/scripts/check-affected/device-lanes.test.ts +++ b/scripts/check-affected/device-lanes.test.ts @@ -7,6 +7,7 @@ import fs from 'node:fs'; import { test } from 'node:test'; import { deviceLaneLeaf, deviceLanesFor, isDeviceLaneSurface, isUnitTest } from './device-lanes.ts'; import { selectChecks, type CheckId } from './model.ts'; +import { selectMacosSmoke } from '../apple-ci-impact.ts'; const IOS: readonly CheckId[] = ['replay-ios', 'replay-ios-device']; @@ -143,10 +144,15 @@ test('unit tests under src/ and packages/*/src own no lane', () => { const imeFixture = 'packages/platform-android/src/fixtures/android-ime-capture.raw.json'; assert.ok(fs.existsSync(imeFixture), imeFixture); assert.ok(!isUnitTest(imeFixture)); - // Package tests outside src/ have no owner and keep failing open. assert.ok(!isUnitTest('packages/maestro/test/conformance/verify.test.ts')); + const conformance = selectChecks({ + changedFiles: ['packages/maestro/test/conformance/verify.test.ts'], + }); + assert.equal(conformance.failOpen, false); + assert.ok(conformance.checks.includes('maestro-conformance')); + assert.ok(conformance.checks.includes('maestro-differential')); assert.equal( - selectChecks({ changedFiles: ['packages/maestro/test/conformance/verify.test.ts'] }).failOpen, + selectChecks({ changedFiles: ['packages/unknown/test/unowned.test.ts'] }).failOpen, true, ); }); @@ -198,3 +204,11 @@ test('a tooling change beside an Android-only change still fails open to the ful assert.ok(plan.checks.includes('replay-ios'), tooling); } }); + +test('the moved differential test selects its macOS lane in a test-only PR', () => { + const changedFiles = ['packages/capture-kit/test/ios-snapshot-differential.test.ts']; + const selected = selectChecks({ changedFiles }); + assert.equal(selected.failOpen, false); + assert.ok(selected.checks.includes('ios-snapshot-differential')); + assert.equal(selectMacosSmoke('pull_request', changedFiles).run, true); +}); diff --git a/scripts/check-affected/model.test.ts b/scripts/check-affected/model.test.ts index 46aee98647..7f15cdaa9d 100644 --- a/scripts/check-affected/model.test.ts +++ b/scripts/check-affected/model.test.ts @@ -552,3 +552,49 @@ test('every configured scan root selects native duplication regardless of extens assert.ok(ids([file]).includes('native-dupes-model'), file); } }); + +test('managed engine and loading changes retain every Maestro oracle lane', () => { + for (const file of [ + 'packages/maestro/src/plugin.ts', + 'packages/plugins/src/registry.ts', + 'packages/plugins/src/replay-backend.ts', + 'packages/plugins/src/store.ts', + 'packages/plugins/src/discovery.ts', + 'packages/plugins/src/validate.ts', + 'packages/replay-port/src/daemon-port/replay-backend-registry.ts', + ]) { + const result = plan([file]); + assert.equal(result.failOpen, false, file); + assert.ok(result.checks.includes('maestro-conformance'), file); + assert.ok(result.checks.includes('maestro-differential'), file); + } +}); + +test('Maestro conformance Vitest inputs retain their registered unit runner', () => { + for (const file of [ + 'packages/maestro/test/conformance/conformance-selector-projection.test.ts', + 'packages/maestro/test/conformance/conformance-selector-projection.ts', + 'packages/maestro/test/conformance/conformance-normalize.ts', + ]) { + assert.ok(fs.existsSync(path.join(repoRoot, file)), file); + const result = plan([file]); + assert.equal(result.failOpen, false, file); + assert.ok(result.checks.includes('unit'), `unit must run for ${file}`); + } +}); + +test('managed engine non-source inputs retain conservative full selection', () => { + for (const file of [ + 'packages/maestro/package.json', + 'packages/maestro/tsdown.config.ts', + 'packages/maestro/test/package-artifact.test.mjs', + 'packages/replay-port/package.json', + 'packages/replay-port/test/artifact.test.mjs', + ]) { + const result = plan([file]); + assert.equal(result.failOpen, true, file); + assert.ok(result.checks.includes('build'), file); + assert.ok(result.checks.includes('typecheck'), file); + assert.ok(result.checks.includes('package'), file); + } +}); diff --git a/scripts/check-affected/model.ts b/scripts/check-affected/model.ts index 3a2aa8494c..be1eec3ad0 100644 --- a/scripts/check-affected/model.ts +++ b/scripts/check-affected/model.ts @@ -256,6 +256,38 @@ const vitestRelatedOwnership: OwnershipRule = ({ file, isTs, underSrc, underTest ] : []; +const replayBackendOwnership: OwnershipRule = ({ file }) => + (file.endsWith('.ts') && + (file.startsWith('packages/maestro/src/') || + file.startsWith('packages/maestro/test/conformance/') || + file.startsWith('packages/replay-port/src/'))) || + /^packages\/plugins\/src\/(?:registry|replay-backend|store|discovery|validate)\./.test(file) + ? [ + reason( + 'maestro-conformance', + file, + 'own:replay-backend-conformance', + 'managed replay backends retain the generated conformance oracle', + ), + reason( + 'maestro-differential', + file, + 'own:replay-backend-differential', + 'installed replay backends retain live outcome and timing invariants', + ), + ...(file.startsWith('packages/maestro/test/conformance/') + ? [ + reason( + 'unit', + file, + 'own:maestro-conformance-unit', + 'the unit suite covers conformance selector projection and its shared helpers', + ), + ] + : []), + ] + : []; + // Workspace package source (#1490 W0): bundled into the published artifact, // type-checked in the root graph, covered by Vitest's module graph, and // guarded by layering R11. Fallow scans it too — the W0 ignorePatterns entry @@ -441,6 +473,7 @@ const BUILD_OWNERSHIP: ReadonlyArray<{ detail: 'the required macOS lane runs the Swift/TypeScript snapshot differential', owns: (file) => file.startsWith('packages/capture-kit/src/ios-snapshot-engine/') || + file === 'packages/capture-kit/test/ios-snapshot-differential.test.ts' || file.startsWith('apple/snapshot-presentation/') || file === 'packages/kernel/src/rect.ts' || file === 'contracts/fixtures/ios-snapshot-engine-conformance.json' || @@ -689,6 +722,7 @@ const OWNERSHIP_RULES: readonly OwnershipRule[] = [ macosCoverageOwnership, testAppOwnership, replayCompatOwnership, + replayBackendOwnership, daemonWireCompatOwnership, buildOwnership, nativeDupesOwnership, diff --git a/scripts/check-provider-plugin.mjs b/scripts/check-provider-plugin.mjs index 513aecad63..470fdfc6b0 100644 --- a/scripts/check-provider-plugin.mjs +++ b/scripts/check-provider-plugin.mjs @@ -54,6 +54,14 @@ try { // of packing this checkout, to prove a plugin still loads on a host without the newest contract. const coreSpec = process.env.AGENT_DEVICE_CORE_SPEC ?? (await pack(root)); const pluginTarball = await pack(plugin); + const sha256 = async (file) => + crypto + .createHash('sha256') + .update(await fs.readFile(file)) + .digest('hex'); + if (!process.env.AGENT_DEVICE_CORE_SPEC) + console.log(`Core tarball sha256: ${await sha256(coreSpec)}`); + console.log(`Plugin tarball sha256: ${await sha256(pluginTarball)}`); for (const directory of [consumer, project]) { await fs.mkdir(directory, { recursive: true }); await fs.writeFile(path.join(directory, 'package.json'), '{"private":true,"type":"module"}'); @@ -69,20 +77,55 @@ try { await fs.readFile(path.join(project, 'node_modules', manifest.name, 'package.json'), 'utf8'), ); assert.deepEqual(installed.exports, { - '.': { import: './dist/agent-device.mjs' }, - './agent-device': { import: './dist/agent-device.mjs' }, + ...fixture.additionalExports, + '.': fixture.primaryExport ?? { import: './dist/agent-device.mjs' }, + './agent-device': fixture.primaryExport ?? { import: './dist/agent-device.mjs' }, }); assert.equal(installed.dependencies, undefined); assert.equal(installed.peerDependencies, undefined); await assert.rejects(fs.stat(path.join(project, 'node_modules', 'agent-device')), { code: 'ENOENT', }); + for (const subpath of Object.keys(fixture.additionalExports ?? {})) { + const specifier = `${manifest.name}${subpath.slice(1)}`; + await run( + process.execPath, + [ + '--input-type=module', + '--eval', + `await import(${JSON.stringify(specifier)}, ${JSON.stringify( + subpath.endsWith('.json') ? { with: { type: 'json' } } : {}, + )});`, + ], + project, + ); + } + if (fixture.verifyTypes) { + await run( + 'npm', + ['install', '--ignore-scripts', '--no-audit', '--no-fund', pluginTarball], + consumer, + ); + await fixture.verifyTypes({ consumer, run, root }); + console.log(`Packed ${manifest.name}: TypeScript consumer passed.`); + } await fs.writeFile( path.join(home, 'config.json'), JSON.stringify({ plugins: { [manifest.name]: { installation } } }), ); const core = path.join(consumer, 'node_modules', 'agent-device'); const coreManifest = JSON.parse(await fs.readFile(path.join(core, 'package.json'), 'utf8')); + if (fixture.verifyPacked) { + const pluginRoot = path.join(project, 'node_modules', manifest.name); + const loadExport = async (directory, exports, name) => + await import(pathToFileURL(path.resolve(directory, exports[name].import)).href); + await fixture.verifyPacked({ + core: await loadExport(core, coreManifest.exports, '.'), + contracts: await loadExport(core, coreManifest.exports, './contracts'), + plugin: await loadExport(pluginRoot, installed.exports, './agent-device'), + }); + console.log(`Packed ${manifest.name}: failure contract passed.`); + } const bin = path.resolve(core, coreManifest.bin['agent-device']); const env = { ...process.env, diff --git a/scripts/fuzz/envelope.ts b/scripts/fuzz/envelope.ts index d604e2e0fa..746ef0b7af 100644 --- a/scripts/fuzz/envelope.ts +++ b/scripts/fuzz/envelope.ts @@ -90,8 +90,9 @@ export const CASE_GENERATION_INPUTS = [ 'invariant.ts', 'validation-arbitraries.ts', 'validation-arbitraries-cli.ts', - 'validation-arbitraries-maestro.ts', - 'validation-values.ts', + '../../packages/test-kit/src/maestro-validation-arbitraries.ts', + '../../packages/test-kit/src/validation-values.ts', + '../../packages/test-kit/src/index.ts', 'validation-case.ts', '../../src/commands/replay/replay-script.fixtures.ts', ] as const; diff --git a/scripts/fuzz/execute.ts b/scripts/fuzz/execute.ts index 385598c960..58a18f3827 100644 --- a/scripts/fuzz/execute.ts +++ b/scripts/fuzz/execute.ts @@ -187,11 +187,11 @@ export async function createCaseRunner( caseTimeoutMs: number, ): Promise { let session = await startSession(target.name); - let closed = false; + let closePromise: Promise | undefined; return { run: async (input) => { - if (closed) throw new Error('fuzz case runner is closed'); + if (closePromise) throw new Error('fuzz case runner is closed'); const { failure, usable } = await runCase(session, target, input, caseTimeoutMs); if (!usable) { await endSession(session); @@ -199,9 +199,21 @@ export async function createCaseRunner( } return failure; }, - close: async () => { - closed = true; - await endSession(session); + close: () => { + closePromise ??= (async () => { + try { + if (session.death() === null && session.child.connected) { + const answer = awaitWorker(session.child, caseTimeoutMs); + session.child.send({ kind: 'close' }); + const outcome = await answer; + if (outcome.kind !== 'message' || outcome.message.kind !== 'closed') + throw new Error(`fuzz target cleanup did not finish within ${caseTimeoutMs}ms`); + } + } finally { + await endSession(session); + } + })(); + return closePromise; }, }; } diff --git a/scripts/fuzz/harness.test.ts b/scripts/fuzz/harness.test.ts index c525064b8c..bc1f9245e8 100644 --- a/scripts/fuzz/harness.test.ts +++ b/scripts/fuzz/harness.test.ts @@ -14,7 +14,7 @@ import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'vitest'; import { LANE_ENVELOPE_SCHEMA_VERSION } from '@agent-device/test-kit'; import { CASE_GENERATION_INPUTS } from './envelope.ts'; -import { runCases } from './execute.ts'; +import { createCaseRunner, runCases } from './execute.ts'; import { checkCase } from './invariant.ts'; import { SELF_CHECK_TARGETS } from './self-check-targets.ts'; @@ -246,3 +246,32 @@ describe('artifact promotion', () => { fs.rmSync(dir, { recursive: true, force: true }); }); }); + +it.each([['--help'], ['--target', 'selector', '--iterations', '1']])( + 'fuzz entrypoint %j does not require an installed Maestro plugin', + (...args) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fuzz-no-plugin-')); + try { + const result = runHarness([...args, '--artifact-dir', dir], { + AGENT_DEVICE_HOME: path.join(dir, 'empty-home'), + }); + expect(result.status).toBe(0); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }, +); + +it('concurrent close waits for the worker cleanup and exit', async () => { + const runner = await createCaseRunner(targetNamed('self-check-untyped-throw'), 750); + let closed = false; + const first = runner.close().then(() => { + closed = true; + }); + try { + await runner.close(); + expect(closed).toBe(true); + } finally { + await first; + } +}); diff --git a/scripts/fuzz/target-types.ts b/scripts/fuzz/target-types.ts index 08542cdfde..e84faa4c36 100644 --- a/scripts/fuzz/target-types.ts +++ b/scripts/fuzz/target-types.ts @@ -50,6 +50,8 @@ export type FuzzFailure = { export type FuzzTarget = { name: FuzzTargetName; + /** Opens optional parser services for this target and returns their cleanup. */ + prepare?: () => Promise<() => Promise>; /** Human-readable description used in failure reports. */ description: string; /** Runs the parser on one case; may throw. */ diff --git a/scripts/fuzz/targets.ts b/scripts/fuzz/targets.ts index 75f9019076..56dd2ccf71 100644 --- a/scripts/fuzz/targets.ts +++ b/scripts/fuzz/targets.ts @@ -11,8 +11,19 @@ import { parseArgs } from '../../src/cli/parser/args.ts'; import { validateSelectorExpression } from '@agent-device/selectors'; import { parseReplayScriptDetailed } from '@agent-device/ad-script'; import { readCliBatchStepsJson } from '@agent-device/command-surface'; -import { inspectMaestroFlow } from '@agent-device/maestro'; +import { openReplayBackend } from '@agent-device/replay-port/replay-backend-registry'; + import type { FuzzTarget } from './target-types.ts'; +import type { ReplayBackend } from '@agent-device/contracts/replay-backend'; + +let inspectMaestroFlow: ReplayBackend['inspectSource']; +async function prepareMaestro(): Promise<() => Promise> { + const scope = await openReplayBackend('maestro', { env: process.env, cwd: process.cwd() }); + inspectMaestroFlow = scope.backend.inspectSource; + return async () => { + await scope.close(); + }; +} import { acceptCase, makeValidationCheck, rejectCase } from './validation-case.ts'; // argv is carried as one string so a case (and its corpus entry, artifact, and repro @@ -123,6 +134,7 @@ export const FUZZ_TARGETS: readonly FuzzTarget[] = [ // Same contract for Maestro flows: shape-valid YAML with one planted violation, so the // failure surfaces in the command-shape validation behind the YAML tokenizer. name: 'maestro-validation', + prepare: prepareMaestro, description: 'inspectMaestroFlow via shape-derived flows with expected outcomes', run: (input) => void inspectMaestroFlow(JSON.parse(input).payload as string, 'fuzz.yaml'), check: makeValidationCheck( @@ -137,6 +149,7 @@ export const FUZZ_TARGETS: readonly FuzzTarget[] = [ }, { name: 'maestro', + prepare: prepareMaestro, description: 'parseMaestroProgram (Maestro compat)', run: (input) => void inspectMaestroFlow(input, 'fuzz.yaml'), seeds: [ diff --git a/scripts/fuzz/validation-arbitraries-cli.ts b/scripts/fuzz/validation-arbitraries-cli.ts index 05d4a6a57c..c50daf01bd 100644 --- a/scripts/fuzz/validation-arbitraries-cli.ts +++ b/scripts/fuzz/validation-arbitraries-cli.ts @@ -13,7 +13,7 @@ import { getFlagDefinitions } from '@agent-device/command-registry/flag-registry import type { FlagDefinition } from '@agent-device/command-registry/flag-types'; import { getCliCommandSchema, isFlagSupportedForCommand } from '@agent-device/command-surface'; import { encodeValidationCase, type ValidationCase } from './validation-case.ts'; -import { ACCEPT, SAFE_VALUES } from './validation-values.ts'; +import { ACCEPT, SAFE_VALUES } from '@agent-device/test-kit'; type CliCommandSurface = { name: string; diff --git a/scripts/fuzz/validation-arbitraries-maestro.test.ts b/scripts/fuzz/validation-arbitraries-maestro.test.ts index 68f2d18c52..1fa0a134e0 100644 --- a/scripts/fuzz/validation-arbitraries-maestro.test.ts +++ b/scripts/fuzz/validation-arbitraries-maestro.test.ts @@ -7,17 +7,23 @@ // than by the YAML tokenizer. import fc from 'fast-check'; -import { describe, expect, it } from 'vitest'; -import { SUPPORTED_MAESTRO_COMMAND_NAMES } from '../../packages/maestro/src/internal/program-ir-command-parser.ts'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { getFuzzTarget } from './registry.ts'; import { decodeValidationCase } from './validation-case.ts'; import { describeGeneratorContract } from './validation-generator-contract.ts'; -import { MAESTRO_MUTATION_NAMES, maestroValidationArb } from './validation-arbitraries-maestro.ts'; +import { MAESTRO_MUTATION_NAMES, maestroValidationArb } from '@agent-device/test-kit'; const SAMPLE_SIZE = 3_000; const SEED = 1; const target = getFuzzTarget('maestro-validation'); +let dispose: (() => Promise) | undefined; +beforeAll(async () => { + dispose = await target.prepare?.(); +}); +afterAll(async () => { + await dispose?.(); +}); const sample = fc.sample(maestroValidationArb, { numRuns: SAMPLE_SIZE, seed: SEED }); describeGeneratorContract({ @@ -56,30 +62,3 @@ describe('planted Maestro violations are refused by command-shape validation', ( ); }); }); - -describe('shape coverage against the converter', () => { - // The valid Maestro shapes are rendered by hand here, so the one thing that cannot be left to - // drift is which commands they cover: a command the converter accepts but this generator never - // emits is a hole the nightly cannot see. Waivers are explicit and must say why. - const NOT_GENERATED = new Set([ - // Both take a nested command list whose bodies the repeat/runFlow cases already cover. - 'retry', - // Needs a JS file on disk to resolve, which a generated case has no way to provide. - 'runScript', - ]); - - it('emits every command the converter supports, or waives it explicitly', () => { - const emitted = new Set( - sample.flatMap((entry) => { - const { payload } = decodeValidationCase(entry)!; - return typeof payload === 'string' ? payload.split('\n') : []; - }), - ); - const covered = (command: string) => - [...emitted].some((line) => line.trim().startsWith(`- ${command}`)); - const missing = SUPPORTED_MAESTRO_COMMAND_NAMES.filter( - (command) => !NOT_GENERATED.has(command) && !covered(command), - ); - expect(missing).toEqual([]); - }); -}); diff --git a/scripts/fuzz/validation-arbitraries.ts b/scripts/fuzz/validation-arbitraries.ts index 81799b7a08..a532834ad8 100644 --- a/scripts/fuzz/validation-arbitraries.ts +++ b/scripts/fuzz/validation-arbitraries.ts @@ -7,7 +7,7 @@ import type fc from 'fast-check'; import type { FuzzTargetName } from './target-types.ts'; import { cliValidationArb } from './validation-arbitraries-cli.ts'; -import { maestroValidationArb } from './validation-arbitraries-maestro.ts'; +import { maestroValidationArb } from '@agent-device/test-kit'; /** The generator for a validation target, or `undefined` for the classic targets. */ export function validationArbitraryFor(target: FuzzTargetName): fc.Arbitrary | undefined { diff --git a/scripts/fuzz/validation-case.ts b/scripts/fuzz/validation-case.ts index 8f59421df9..80c94a7ffa 100644 --- a/scripts/fuzz/validation-case.ts +++ b/scripts/fuzz/validation-case.ts @@ -1,3 +1,9 @@ +import { + encodeValidationCase, + type ValidationCase, + type ValidationExpectation, +} from '@agent-device/test-kit'; +export { encodeValidationCase, type ValidationCase } from '@agent-device/test-kit'; // Expectation-carrying cases for the validation fuzz targets (#1781 B2). // // The classic targets judge only rejections ("fails well"), which cannot see the bug class @@ -11,20 +17,6 @@ import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { describeThrown } from './invariant.ts'; import type { FuzzFailure, FuzzTargetName } from './target-types.ts'; -export type ValidationExpectation = { outcome: 'accept' } | { outcome: 'reject'; code: string }; - -export type ValidationCase = { - /** CLI argv vector or Maestro flow source, depending on the target. */ - payload: string[] | string; - /** Which generator rule produced the case — names the finding and the calibration row. */ - mutation: string; - expect: ValidationExpectation; -}; - -export function encodeValidationCase(validationCase: ValidationCase): string { - return JSON.stringify(validationCase); -} - /** A pinned case the parser must accept. */ export function acceptCase(payload: ValidationCase['payload']): string { return encodeValidationCase({ payload, mutation: 'valid', expect: { outcome: 'accept' } }); diff --git a/scripts/fuzz/worker.ts b/scripts/fuzz/worker.ts index c642339572..46923b8c3b 100644 --- a/scripts/fuzz/worker.ts +++ b/scripts/fuzz/worker.ts @@ -11,14 +11,18 @@ import { beginStderrCapture } from '@agent-device/test-kit'; import { checkCase, type FuzzFailure } from './invariant.ts'; import { getFuzzTarget } from './registry.ts'; -export type FuzzWorkerRequest = { kind: 'case'; input: string }; +export type FuzzWorkerRequest = { kind: 'case'; input: string } | { kind: 'close' }; -export type FuzzWorkerMessage = { kind: 'ready' } | { kind: 'result'; failure: FuzzFailure | null }; +export type FuzzWorkerMessage = + | { kind: 'ready' } + | { kind: 'closed' } + | { kind: 'result'; failure: FuzzFailure | null }; const send = process.send?.bind(process); if (!send) throw new Error('scripts/fuzz/worker.ts must be run as a forked child process.'); const target = getFuzzTarget(process.argv[2] ?? ''); +const dispose = await target.prepare?.(); // The batch-steps parser warns on deprecated step shapes; a fuzz run would emit thousands of // those lines and bury the failure report. Only JavaScript writes go through here: a fatal @@ -26,7 +30,12 @@ const target = getFuzzTarget(process.argv[2] ?? ''); // piped rather than discarded. beginStderrCapture({ discard: true }); -process.on('message', (request: FuzzWorkerRequest) => { +process.on('message', async (request: FuzzWorkerRequest) => { + if (request.kind === 'close') { + await dispose?.(); + send({ kind: 'closed' } satisfies FuzzWorkerMessage); + return; + } const failure = checkCase(target, request.input); send({ kind: 'result', failure } satisfies FuzzWorkerMessage); }); diff --git a/scripts/gate/workflows.test.ts b/scripts/gate/workflows.test.ts index fad6ac94d0..c4875fea9f 100644 --- a/scripts/gate/workflows.test.ts +++ b/scripts/gate/workflows.test.ts @@ -68,9 +68,13 @@ function planted(files: Record): ReturnType { } test('a command repeating a script body verbatim credits that script', () => { - const body = model.scripts['check:package'] as string; - assert.deepEqual(verbatimScripts(body, model.scripts), ['check:package']); - assert.deepEqual(verbatimScripts('node scripts/something-else.ts', model.scripts), []); + const scripts = { + verify: 'node scripts/verify.ts', + combined: 'node scripts/verify.ts && node scripts/other.ts', + }; + assert.deepEqual(verbatimScripts(scripts.verify, scripts), ['verify']); + assert.deepEqual(verbatimScripts(scripts.combined, scripts), ['verify', 'combined']); + assert.deepEqual(verbatimScripts('node scripts/something-else.ts', scripts), []); }); test('path filters use GitHub glob semantics', () => { diff --git a/scripts/gate/workflows.ts b/scripts/gate/workflows.ts index 5bafa455d2..b45c10205c 100644 --- a/scripts/gate/workflows.ts +++ b/scripts/gate/workflows.ts @@ -255,7 +255,9 @@ export function verbatimScripts( command: string, scripts: Readonly>, ): string[] { - const wanted = commandSegments(command).map((segment) => segment.replaceAll(/\s+/g, ' ')); + const wanted = [command, ...commandSegments(command)].map((segment) => + segment.replaceAll(/\s+/g, ' '), + ); return Object.entries(scripts) .filter(([, body]) => wanted.includes(body.replaceAll(/\s+/g, ' '))) .map(([name]) => name); diff --git a/scripts/install-workspace-replay-plugins.ts b/scripts/install-workspace-replay-plugins.ts new file mode 100644 index 0000000000..2fcf3be114 --- /dev/null +++ b/scripts/install-workspace-replay-plugins.ts @@ -0,0 +1,68 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { publishFileSync, resolveUserConfigPath } from '@agent-device/host-kit/file'; + +/** Installs the explicitly selected workspace build into an isolated validation plugin store. */ +export function installWorkspaceReplayPlugins(env: NodeJS.ProcessEnv, source: boolean): void { + if (!env.AGENT_DEVICE_HOME) + throw new Error('Workspace plugin installation requires AGENT_DEVICE_HOME'); + const configPath = resolveUserConfigPath(env); + const home = path.dirname(configPath); + const staged = ['maestro', 'replay'].map((packageId) => ({ + packageId, + installation: crypto.randomUUID(), + })); + try { + for (const { packageId, installation } of staged) + installWorkspacePlugin(source, home, packageId, installation); + const config = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, 'utf8')) : {}; + const selections = Object.fromEntries( + staged.map(({ packageId, installation }) => [`@agent-device/${packageId}`, { installation }]), + ); + publishFileSync({ + destination: configPath, + contents: JSON.stringify({ ...config, plugins: { ...config.plugins, ...selections } }), + mode: 0o600, + preserveExistingMode: true, + }); + } catch (error) { + for (const { installation } of staged) + fs.rmSync(path.join(home, 'plugins', installation), { recursive: true, force: true }); + throw error; + } +} + +function installWorkspacePlugin( + source: boolean, + home: string, + packageId: string, + installation: string, +): void { + const directory = path.join( + home, + 'plugins', + installation, + 'node_modules', + `@agent-device/${packageId}`, + ); + const workspace = path.resolve(import.meta.dirname, `../packages/${packageId}`); + fs.mkdirSync(path.dirname(directory), { recursive: true }); + if (source) fs.symlinkSync(workspace, directory, 'dir'); + else { + fs.mkdirSync(directory); + fs.cpSync(path.join(workspace, 'dist'), path.join(directory, 'dist'), { recursive: true }); + const manifest = JSON.parse(fs.readFileSync(path.join(workspace, 'package.json'), 'utf8')); + fs.writeFileSync( + path.join(directory, 'package.json'), + JSON.stringify({ + name: manifest.name, + version: manifest.version, + type: 'module', + exports: manifest.publishConfig.exports, + }), + ); + } +} + +if (process.argv[1] === import.meta.filename) installWorkspaceReplayPlugins(process.env, false); diff --git a/scripts/layering/architecture-ownership.ts b/scripts/layering/architecture-ownership.ts index fdd4efc310..7c0850a3d5 100644 --- a/scripts/layering/architecture-ownership.ts +++ b/scripts/layering/architecture-ownership.ts @@ -176,7 +176,12 @@ export const LOGICAL_MODULE_POLICIES = [ { name: 'replay-port', roots: ['packages/replay-port/src/'], - forbiddenTargetRoots: [DAEMON_SOURCE_ROOT, 'src/providers/', 'src/compat/'], + forbiddenTargetRoots: [ + DAEMON_SOURCE_ROOT, + 'src/providers/', + 'src/compat/', + 'packages/maestro/', + ], }, { name: 'daemon-session-lifecycle', @@ -303,6 +308,8 @@ export const ARCHITECTURE_OWNERSHIP = { 'packages/platform-linux/', 'packages/platform-vega/', 'packages/platform-web/', + 'packages/provider-aws-device-farm/', + 'packages/provider-browserstack/', 'packages/provider-limrun/', 'packages/provider-revyl/', 'packages/provider-testmu/', diff --git a/scripts/layering/contracts-exports.snapshot.json b/scripts/layering/contracts-exports.snapshot.json index 368cb971b4..28387cd2a0 100644 --- a/scripts/layering/contracts-exports.snapshot.json +++ b/scripts/layering/contracts-exports.snapshot.json @@ -1,4 +1,5 @@ [ + "@agent-device/contracts/ad-replay-execution", "@agent-device/contracts/alert-contract", "@agent-device/contracts/alert-runtime", "@agent-device/contracts/android-clipboard-support", @@ -103,6 +104,10 @@ "@agent-device/contracts/remote", "@agent-device/contracts/replay", "@agent-device/contracts/replay-backend", + "@agent-device/contracts/replay-divergence-data", + "@agent-device/contracts/replay-execution", + "@agent-device/contracts/replay-script-data", + "@agent-device/contracts/replay-test-execution", "@agent-device/contracts/runner-lease-context", "@agent-device/contracts/runtime-contract", "@agent-device/contracts/runtime-contract-error", diff --git a/scripts/layering/model.ts b/scripts/layering/model.ts index c77ce379d4..512dafc880 100644 --- a/scripts/layering/model.ts +++ b/scripts/layering/model.ts @@ -55,6 +55,7 @@ export type BackEdgeMap = Record; // ranked here or listed as unranked — `unclassifiedZones` and `model.test.ts` guard // that no zone is silently unclassified. const TARGET_DAG_RANK = new Map([ + ['build-config', 1], ['ad-replay', 1], ['ad-script', 1], ['command-registry', 1], @@ -62,6 +63,7 @@ const TARGET_DAG_RANK = new Map([ ['device-selection', 1], ['maestro', 1], ['replay-port', 1], + ['replay', 1], ['replay-test', 1], ['selectors', 1], ['session-journal', 1], @@ -118,6 +120,8 @@ export const UNRANKED_ZONES: ReadonlySet = new Set([ 'apple-runner', ...PLATFORMS.map((family) => `platform-${family}`), 'provider-webdriver', + 'provider-aws-device-farm', + 'provider-browserstack', 'provider-limrun', 'provider-revyl', 'provider-testmu', diff --git a/scripts/layering/package-boundaries-dev-dependencies.test.ts b/scripts/layering/package-boundaries-dev-dependencies.test.ts index 7d0ff537ef..b0fb9f54e7 100644 --- a/scripts/layering/package-boundaries-dev-dependencies.test.ts +++ b/scripts/layering/package-boundaries-dev-dependencies.test.ts @@ -101,3 +101,17 @@ test('a published package keeps its siblings in devDependencies for every file', assert.deepEqual(violations(published, file), [], file); } }); + +test('a private publication placeholder keeps bundled dependencies in the publication field', () => { + const staged = { + ...DEV_ONLY, + publishConfig: { exports: { './agent-device': { import: './dist/plugin.mjs' } } }, + }; + assert.deepEqual(violations(staged, 'packages/owner/src/thing.ts'), []); + const undeclared = violations({ ...staged, devDependencies: {} }, 'packages/owner/src/thing.ts'); + assert.equal(undeclared.length, 1); + assert.match(undeclared[0]!.message, /without declaring "@agent-device\/helper"/); + const privateDevOnly = violations(DEV_ONLY, 'packages/owner/src/thing.ts'); + assert.equal(privateDevOnly.length, 1); + assert.match(privateDevOnly[0]!.message, /declare it in dependencies/); +}); diff --git a/scripts/layering/package-boundaries-script-tests.test.ts b/scripts/layering/package-boundaries-script-tests.test.ts new file mode 100644 index 0000000000..5bd8c1aed0 --- /dev/null +++ b/scripts/layering/package-boundaries-script-tests.test.ts @@ -0,0 +1,72 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { test } from 'node:test'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { checkPackageBoundaries } from './package-boundaries.ts'; + +test('R11 discovers real workspace imports in script tests without parsing fixture strings', () => { + const repo = mkdtempForTestSync('package-boundaries-script-tests-'); + const helper = path.join(repo, 'packages/helper'); + fs.mkdirSync(path.join(helper, 'src'), { recursive: true }); + fs.mkdirSync(path.join(repo, 'scripts/nested'), { recursive: true }); + fs.writeFileSync( + path.join(helper, 'package.json'), + JSON.stringify({ name: '@agent-device/helper', private: true, exports: './src/index.ts' }), + ); + fs.writeFileSync(path.join(helper, 'src/index.ts'), 'export const value = 1;'); + fs.writeFileSync(path.join(repo, 'package.json'), JSON.stringify({ private: true })); + fs.writeFileSync( + path.join(repo, 'scripts/nested/probe.test.ts'), + `import { value } from '@agent-device/helper'; + const fixture = "import { missing } from '@agent-device/absent';";`, + ); + execFileSync('git', ['init', '-q'], { cwd: repo }); + execFileSync('git', ['add', '.'], { cwd: repo }); + const violations = checkPackageBoundaries(repo); + assert.equal(violations.length, 1); + assert.equal(violations[0]!.rule, 'R11 package-boundaries'); + assert.equal(violations[0]!.file, 'scripts/nested/probe.test.ts'); + assert.equal(violations[0]!.line, 1); + assert.match(violations[0]!.message, /helper.*not a.*workspace:\*/); + + fs.writeFileSync( + path.join(repo, 'package.json'), + JSON.stringify({ private: true, devDependencies: { '@agent-device/helper': 'workspace:*' } }), + ); + assert.deepEqual(checkPackageBoundaries(repo), []); +}); + +test('R11 scans script test relative tunnels, unknown packages and unexported subpaths', () => { + const repo = mkdtempForTestSync('package-boundaries-script-routes-'); + fs.mkdirSync(path.join(repo, 'packages/helper/src'), { recursive: true }); + fs.mkdirSync(path.join(repo, 'scripts/nested'), { recursive: true }); + fs.writeFileSync( + path.join(repo, 'packages/helper/package.json'), + JSON.stringify({ name: '@agent-device/helper', exports: './src/index.ts' }), + ); + fs.writeFileSync(path.join(repo, 'packages/helper/src/index.ts'), 'export const value = 1;'); + fs.writeFileSync( + path.join(repo, 'package.json'), + JSON.stringify({ devDependencies: { '@agent-device/helper': 'workspace:*' } }), + ); + fs.writeFileSync( + path.join(repo, 'scripts/nested/probe.test.ts'), + `import './ordinary.ts'; +import '../../packages/helper/src/index.ts'; +import '@agent-device/absent'; +import '@agent-device/helper/private'; +import '@agent-device/helper';`, + ); + execFileSync('git', ['init', '-q'], { cwd: repo }); + execFileSync('git', ['add', '.'], { cwd: repo }); + const violations = checkPackageBoundaries(repo); + assert.deepEqual( + violations.map((item) => item.line), + [2, 3, 4], + ); + assert.match(violations[0]!.message, /bypasses the package boundary/); + assert.match(violations[1]!.message, /unknown workspace package/); + assert.match(violations[2]!.message, /not named by .*exports/); +}); diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index cee6d6dc56..01bd9cc385 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -6,6 +6,7 @@ import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; +import { createRequire } from 'node:module'; import path from 'node:path'; import { test } from 'node:test'; import { listSourceFiles } from './check.ts'; @@ -675,13 +676,9 @@ test('the real tree parses, declares, and passes R11', () => { ]); const maestroPackage = packages.find((pkg) => pkg.name === '@agent-device/maestro'); assert.ok(maestroPackage, 'maestro package must exist'); - // Locks the export surface: `.` (the engine), the replay backend plugin (#3377) with its - // engine-free declaration, and the runScript HTTP helper. The eager-closure budget gate - // (scripts/__tests__/eager-closure-budgets.test.ts) is what keeps the plugin off `.`. assert.deepEqual([...maestroPackage.exportTargets.keys()].sort(), [ '@agent-device/maestro', - '@agent-device/maestro/replay-backend', - '@agent-device/maestro/replay-backend-declaration', + '@agent-device/maestro/agent-device', '@agent-device/maestro/run-script-http', ]); assert.deepEqual([...maestroPackage.workspaceDependencies].sort(), [ @@ -692,6 +689,8 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/kernel', '@agent-device/provision-kit', '@agent-device/selectors', + '@agent-device/test-kit', + 'agent-device', ]); const adScriptPackage = packages.find((pkg) => pkg.name === '@agent-device/ad-script'); assert.ok(adScriptPackage, 'ad-script package must exist'); @@ -703,58 +702,19 @@ test('the real tree parses, declares, and passes R11', () => { ]); const adReplayPackage = packages.find((pkg) => pkg.name === '@agent-device/ad-replay'); assert.ok(adReplayPackage, 'ad-replay package must exist'); - // Locks the export surface: `.` (the engine) and `./divergence` (the - // divergence report/sanitization vocabulary, off the engine entry so CLI/MCP - // surfaces don't load the step loop). Any other subpath widens this key - // list and fails the assertion. - assert.deepEqual( - [...adReplayPackage.exportTargets.keys()], - ['@agent-device/ad-replay', '@agent-device/ad-replay/divergence'], - ); + assert.deepEqual([...adReplayPackage.exportTargets.keys()], ['@agent-device/ad-replay']); assert.deepEqual([...adReplayPackage.workspaceDependencies].sort(), [ '@agent-device/ad-script', '@agent-device/contracts', '@agent-device/kernel', '@agent-device/selectors', ]); - // #1555 review P1 ("add the reviewer-required exact exported-symbol - // gate"; second pass, "enforce the accepted two-entrypoint facade"; the - // structural-quality review, "typed façade replaces the zero-type rule"): - // the exports-subpath assertion above only proves the package exposes one - // `.` entry point — it says nothing about what that entry point actually - // NAMES. This pins the exact symbol list `packages/ad-replay/src/index.ts` - // exports: the binding design's two VALUE entrypoints, `inspectAdReplay` - // and `runAdReplay` (never a third value), plus the neutral vocabulary - // their signatures are built from, named explicitly instead of every root - // consumer hand-deriving `Parameters<...>`/`ReturnType<...>` off them (the - // shim `src/daemon/ad-replay-facade-types.ts` used to centralize — since - // deleted). `formatReplaySuccessMessage` (presentation, not engine policy) - // stays out on purpose — it sits daemon-side beside its one caller. A - // stray export — intentional or not, including a form `readNamedExports` - // cannot enumerate a name for (`export *`, `export default` — see the - // rejection tests below) — must edit this list too, not just slip through - // the exports-subpath check. + // The engine exports two value entrypoints. Shared port vocabulary belongs to contracts. assert.deepEqual( readNamedExports( fs.readFileSync(path.join(repoRoot, 'packages/ad-replay/src/index.ts'), 'utf8'), ), - [ - 'AdReplayDispatchGuard', - 'AdReplayDispatchOutcome', - 'AdReplayGuardMismatchEvidence', - 'AdReplayLandmarkMismatchEvidence', - 'AdReplayManifest', - 'AdReplayScrubValue', - 'AdReplayStepFailure', - 'AdReplayStepRuntime', - 'AdReplayTargetBindingEvidence', - 'AdReplayTargetClassification', - 'AdReplayTargetObservation', - 'AdReplayVarSources', - 'AdReplayVerificationEntry', - 'inspectAdReplay', - 'runAdReplay', - ], + ['inspectAdReplay', 'runAdReplay'], ); const selectorsPackage = packages.find((pkg) => pkg.name === '@agent-device/selectors'); assert.ok(selectorsPackage, 'selectors package must exist'); @@ -844,9 +804,7 @@ test('the real tree parses, declares, and passes R11', () => { ); assert.ok(providerWebDriverPackage, 'provider-webdriver package must exist'); assert.deepEqual([...providerWebDriverPackage.exportTargets.keys()].sort(), [ - '@agent-device/provider-webdriver', '@agent-device/provider-webdriver/android-snapshot', - '@agent-device/provider-webdriver/connection-verification', '@agent-device/provider-webdriver/plugin', '@agent-device/provider-webdriver/providers', ]); @@ -898,16 +856,17 @@ test('the real tree parses, declares, and passes R11', () => { 'root must declare the contracts workspace dependency', ); assert.ok( - rootWorkspaceDependencyNames(repoRoot).has('@agent-device/maestro'), - 'root must declare the maestro workspace dependency', + !rootWorkspaceDependencyNames(repoRoot).has('@agent-device/maestro'), + 'core must not depend on the optional Maestro plugin', ); assert.ok( rootWorkspaceDependencyNames(repoRoot).has('@agent-device/ad-script'), 'root must declare the ad-script workspace dependency', ); assert.ok( - rootWorkspaceDependencyNames(repoRoot).has('@agent-device/ad-replay'), - 'root must declare the ad-replay workspace dependency', + !rootWorkspaceDependencyNames(repoRoot).has('@agent-device/ad-replay') && + !rootWorkspaceDependencyNames(repoRoot).has('@agent-device/replay-test'), + 'core must not depend on the optional native execution engines', ); assert.ok( rootWorkspaceDependencyNames(repoRoot).has('@agent-device/selectors'), @@ -929,6 +888,7 @@ test('the real tree parses, declares, and passes R11', () => { }); test('Node resolution enforces the exports map at runtime', () => { + const replayPackageRequire = createRequire(path.join(repoRoot, 'packages/replay/package.json')); // Real resolver, not the gate's model: a deep import is a resolution error, // and the legal subpath realpaths OUTSIDE node_modules (pnpm symlink), which // is what lets --experimental-strip-types load package sources in dev. @@ -955,11 +915,15 @@ test('Node resolution enforces the exports map at runtime', () => { '@agent-device/ad-replay/testing', '@agent-device/ad-replay/internal/target-verification.ts', '@agent-device/ad-replay/src/index.ts', + '@agent-device/replay-test/src/internal/session-test.ts', '@agent-device/selectors/internal/parse.ts', '@agent-device/selectors/src/index.ts', ]) { assert.throws( - () => import.meta.resolve(deep), + () => + deep.startsWith('@agent-device/ad-replay/') || deep.startsWith('@agent-device/replay-test/') + ? replayPackageRequire.resolve(deep) + : import.meta.resolve(deep), /ERR_PACKAGE_PATH_NOT_EXPORTED|Package subpath|No "exports" main/, `${deep} must not resolve`, ); @@ -978,9 +942,12 @@ test('Node resolution enforces the exports map at runtime', () => { contractsReactNativeOverlayResolved.endsWith('packages/contracts/src/react-native-overlay.ts'), contractsReactNativeOverlayResolved, ); - const providerWebDriverResolved = import.meta.resolve('@agent-device/provider-webdriver'); + assert.throws(() => import.meta.resolve('@agent-device/provider-webdriver'), { + code: 'ERR_PACKAGE_PATH_NOT_EXPORTED', + }); + const providerWebDriverResolved = import.meta.resolve('@agent-device/provider-webdriver/plugin'); assert.ok( - providerWebDriverResolved.endsWith('packages/provider-webdriver/src/index.ts'), + providerWebDriverResolved.endsWith('packages/provider-webdriver/src/plugin.ts'), providerWebDriverResolved, ); const providerLimrunResolved = import.meta.resolve('@agent-device/provider-limrun'); @@ -992,7 +959,9 @@ test('Node resolution enforces the exports map at runtime', () => { assert.ok(xmlResolved.endsWith('packages/xml/src/index.ts'), xmlResolved); const adScriptResolved = import.meta.resolve('@agent-device/ad-script'); assert.ok(adScriptResolved.endsWith('packages/ad-script/src/index.ts'), adScriptResolved); - const adReplayResolved = import.meta.resolve('@agent-device/ad-replay'); + const adReplayResolved = replayPackageRequire.resolve('@agent-device/ad-replay'); + const replayTestResolved = replayPackageRequire.resolve('@agent-device/replay-test'); + assert.ok(replayTestResolved.endsWith('packages/replay-test/src/index.ts'), replayTestResolved); assert.ok(adReplayResolved.endsWith('packages/ad-replay/src/index.ts'), adReplayResolved); const selectorsResolved = import.meta.resolve('@agent-device/selectors'); assert.ok(selectorsResolved.endsWith('packages/selectors/src/index.ts'), selectorsResolved); diff --git a/scripts/layering/package-boundaries.ts b/scripts/layering/package-boundaries.ts index 0b4a70f31d..7bcd879507 100644 --- a/scripts/layering/package-boundaries.ts +++ b/scripts/layering/package-boundaries.ts @@ -147,6 +147,7 @@ export function workspacePackagesFromManifests( const manifest = JSON.parse(manifests.get(manifestFile)!) as { name?: string; private?: boolean; + publishConfig?: { exports?: unknown }; exports?: | string | Record; @@ -179,14 +180,16 @@ export function workspacePackagesFromManifests( ), ), ); - const workspaceDependencyField = manifest.private === true ? 'dependencies' : 'devDependencies'; + const bundledForPublication = + manifest.private !== true || manifest.publishConfig?.exports !== undefined; + const workspaceDependencyField = bundledForPublication ? 'devDependencies' : 'dependencies'; const workspaceDependencies = new Set( Object.entries(manifest[workspaceDependencyField] ?? {}) .filter(([, range]) => range.startsWith('workspace:')) .map(([name]) => name), ); const workspaceDevDependencies = new Set( - manifest.private === true + !bundledForPublication ? Object.entries(manifest.devDependencies ?? {}) .filter(([, range]) => range.startsWith('workspace:')) .map(([name]) => name) @@ -579,18 +582,10 @@ export function checkPackageBoundaries(repoRoot: string): PackageBoundaryViolati } for (const root of ['src', 'test', 'scripts']) { for (const file of walkTsFiles(repoRoot, root)) { - // Gate tests under scripts/ carry import syntax inside fixture strings - // (which is why this reads module records instead of scanning lines); - // src/ and test/ suites stay covered — they import packages for real. - if (root === 'scripts' && file.endsWith('.test.ts')) continue; const source = fs.readFileSync(path.join(repoRoot, file), 'utf8'); + const sites = specifierSites(file, source); violations.push( - ...checkRootSites( - specifierSites(file, source), - packages, - rootDependencies, - insideCompiledSources(file), - ), + ...checkRootSites(sites, packages, rootDependencies, insideCompiledSources(file)), ); } } diff --git a/scripts/layering/process-globals-policy.test.ts b/scripts/layering/process-globals-policy.test.ts index 2b416afc6e..bd14f82baa 100644 --- a/scripts/layering/process-globals-policy.test.ts +++ b/scripts/layering/process-globals-policy.test.ts @@ -61,8 +61,6 @@ test('entry declarations permit process reads but do not permit ambient command- 'packages/capture-kit/src/png-worker.ts', 'packages/maestro/src/daemon-port/run-script-http-child.ts', 'packages/react-native/src/companion/client-companion-tunnel-worker.ts', - 'src/sdk/host.ts', - 'packages/host-kit/src/local-artifact-adapter.ts', ]) { assert.deepEqual(check('process.env; process.on("SIGINT", stop);', file), [], file); assert.equal(check('commandHostEnvironment();', file).length, 1, file); @@ -124,17 +122,22 @@ test('bare process values are captures in calls, aliases, spreads, returns and c "import * as p from 'node:process'; captureHostEnvironment(p.default);", ]) { assert.equal(check(source).length, 1, source); - assert.deepEqual(check(source, 'src/sdk/host.ts'), [], source); + assert.equal(check(source, 'src/sdk/host.ts').length, 1, source); + assert.equal( + check(source, 'packages/host-kit/src/local-artifact-adapter.ts').length, + 1, + source, + ); } }); -test('SDK adapters capture their default host only through the shared entry', () => { +test('SDK adapters cannot capture a process host', () => { for (const file of [ 'src/sdk/android-adb.ts', 'src/sdk/artifacts.ts', 'src/sdk/metro.ts', 'src/sdk/remote-config.ts', - 'src/provider-limrun-runtime.ts', + 'src/sdk/limrun-runtime-dependencies.ts', ]) { assert.equal(check('captureHostEnvironment(process);', file).length, 1, file); } diff --git a/scripts/layering/process-globals-policy.ts b/scripts/layering/process-globals-policy.ts index e42b332759..8c8663b6b6 100644 --- a/scripts/layering/process-globals-policy.ts +++ b/scripts/layering/process-globals-policy.ts @@ -17,9 +17,6 @@ const PROCESS_ENTRIES = new Set([ 'packages/react-native/src/companion/client-companion-tunnel-worker.ts', 'packages/maestro/src/daemon-port/run-script-child.ts', 'packages/maestro/src/daemon-port/run-script-http-child.ts', - // Released SDK defaults; #3759 removes these captures in 0.22. - 'packages/host-kit/src/local-artifact-adapter.ts', - 'src/sdk/host.ts', 'src/mcp/command-tools.ts', 'packages/daemon-client/src/index.ts', 'packages/daemon-client/src/daemon-client-ensure.ts', diff --git a/scripts/layering/project-references.test.ts b/scripts/layering/project-references.test.ts index e6836b5380..333f94614b 100644 --- a/scripts/layering/project-references.test.ts +++ b/scripts/layering/project-references.test.ts @@ -1,11 +1,7 @@ -// The TypeScript project graph is three hand-written views of one fact: the workspace package -// set, the root manifest's `workspace:*` declarations, and the `references` lists in the root -// build node (tsconfig.typecheck.json), examples/sdk, and per-package tsconfigs. `tsc -b` fails -// loudly on a MISSING reference it needs but silently tolerates EXTRA ones (#3289 review), so a -// package added to the workspace while a references list goes un-updated keeps building a stale -// graph that still exits 0. -// These tests read the committed declarations against each other so the four views cannot -// drift: an added, renamed, or removed workspace package must edit every list or fail here. +// The TypeScript project graph covers every workspace package. Root and example references +// must match that set, and each package's references must match its own manifest dependencies. +// Root workspace dependency declarations follow root imports, which R11 checks separately. +// A package-local build dependency does not require a root declaration. import assert from 'node:assert/strict'; import fs from 'node:fs'; @@ -115,7 +111,7 @@ test('the compiled-set predicate is licensed by the tsconfig include/exclude sha } }); -test('the root manifest declares every workspace package as a workspace dependency', () => { +test('root workspace dependencies name existing packages and exclude optional engines', () => { const manifest = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8')) as { dependencies?: Record; devDependencies?: Record; @@ -127,15 +123,20 @@ test('the root manifest declares every workspace package as a workspace dependen .filter(([, range]) => String(range).startsWith('workspace:')) .map(([name]) => name) .sort(); - const expected = readWorkspacePackages(repoRoot) - .map((pkg) => pkg.name) - .sort(); + const workspaceNames = new Set(readWorkspacePackages(repoRoot).map((pkg) => pkg.name)); assert.deepEqual( - declared, - expected, - 'a workspace package the root program consumes must be declared workspace:* in the root ' + - 'manifest (its tsconfig references already name it; the root project resolves package ' + - 'specifiers through these declarations)', + declared.filter((name) => !workspaceNames.has(name)), + [], + 'every root workspace:* dependency must name an existing workspace package', + ); + assert.ok( + ![ + '@agent-device/maestro', + '@agent-device/replay', + '@agent-device/ad-replay', + '@agent-device/replay-test', + ].some((name) => declared.includes(name)), + 'The optional engine must be installed through the plugin store. R11 rejects undeclared imports from core.', ); }); diff --git a/scripts/layering/root-module-zones.ts b/scripts/layering/root-module-zones.ts index fe4a230613..525eb0ff84 100644 --- a/scripts/layering/root-module-zones.ts +++ b/scripts/layering/root-module-zones.ts @@ -53,7 +53,6 @@ export const ROOT_MODULE_ZONES: Readonly> = { 'src/provider-device-runtimes.ts', 'src/provider-limrun-credentials.ts', 'src/provider-plugin-policy.ts', - 'src/provider-webdriver.ts', ], // The operation host the platform runtime loads through `import()` (`loadHost`) and its facets. // It ranks above every spine zone, so a static import of it is a back-edge from anywhere but @@ -98,7 +97,7 @@ export const ROOT_MODULE_ZONES: Readonly> = { 'src/platform-runtime-screen-recording-web-host.ts', 'src/platform-runtime-toolchain-host.ts', ], - sdk: ['src/finders.ts', 'src/provider-limrun-runtime.ts'], + sdk: ['src/finders.ts'], }; const ZONE_BY_ROOT_MODULE: ReadonlyMap = new Map( diff --git a/scripts/release-workspace.mjs b/scripts/release-workspace.mjs index d526775a92..23659ead61 100644 --- a/scripts/release-workspace.mjs +++ b/scripts/release-workspace.mjs @@ -69,7 +69,11 @@ function checkPublishedDependencies(packed) { const unpublishableNames = new Set( packages.filter((pkg) => pkg.manifest.private === true).map((pkg) => pkg.manifest.name), ); - if (packed.agentDevicePlugin) unpublishableNames.add(rootPackage.manifest.name); + // A provider plugin exports its factory as `./agent-device` and imports only types from + // agent-device, so it must never carry the core as a runtime dependency. The root and `main` + // loading fallbacks stay a loader convenience; a published plugin package names `./agent-device`. + if (packed.exports && Object.hasOwn(packed.exports, './agent-device')) + unpublishableNames.add(rootPackage.manifest.name); for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies']) { checkDependencyField(field, packed[field] ?? {}, unpublishableNames); } diff --git a/scripts/vitest-tmpdir-global-setup.ts b/scripts/vitest-tmpdir-global-setup.ts index 48e4192398..90659584ce 100644 --- a/scripts/vitest-tmpdir-global-setup.ts +++ b/scripts/vitest-tmpdir-global-setup.ts @@ -1,3 +1,4 @@ +import { installWorkspaceReplayPlugins } from './install-workspace-replay-plugins.ts'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; @@ -25,6 +26,7 @@ import { let testRunTmpDir: string; let previousTmpDir: string | undefined; +let previousPluginHome: string | undefined; let previousSwiftCacheDir: string | undefined; // setup/teardown are vitest's globalSetup contract: it imports this file by @@ -53,6 +55,9 @@ export function setup(): void { path.join(TEST_RUN_TMP_ROOT, `${TEST_RUN_TMP_PREFIX}${process.pid}-`), ); process.env.TMPDIR = testRunTmpDir; + previousPluginHome = process.env.AGENT_DEVICE_HOME; + process.env.AGENT_DEVICE_HOME = path.join(testRunTmpDir, 'plugin-home'); + installWorkspaceReplayPlugins(process.env, true); } // fallow-ignore-next-line unused-export @@ -63,6 +68,8 @@ export async function teardown(): Promise { await stopRunDirectoryConsumers(testRunTmpDir), ); } finally { + if (previousPluginHome === undefined) delete process.env.AGENT_DEVICE_HOME; + else process.env.AGENT_DEVICE_HOME = previousPluginHome; fs.rmSync(testRunTmpDir, { recursive: true, force: true }); restoreEnv('TMPDIR', previousTmpDir); restoreEnv('AGENT_DEVICE_SWIFT_CACHE_DIR', previousSwiftCacheDir); diff --git a/server.json b/server.json index 3b09763b8b..abc83af3db 100644 --- a/server.json +++ b/server.json @@ -7,12 +7,12 @@ "url": "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/callstack/agent-device", "source": "github" }, - "version": "0.21.39-dev", + "version": "0.22.0-dev", "packages": [ { "registryType": "npm", "identifier": "agent-device", - "version": "0.21.39-dev", + "version": "0.22.0-dev", "transport": { "type": "stdio" }, diff --git a/src/__tests__/cli-leased-session.test.ts b/src/__tests__/cli-leased-session.test.ts index f0b8f22c43..526a8ab1aa 100644 --- a/src/__tests__/cli-leased-session.test.ts +++ b/src/__tests__/cli-leased-session.test.ts @@ -146,6 +146,7 @@ async function leaseIdsOnRealDaemon(allocations: CapturedDaemonRequest[]): Promi daemonBaseUrl: daemon.baseUrl, daemonAuthToken: daemon.runtime.token, daemonTransport: 'http', + session: 'lease-reader', }); const leaseIds = []; for (const allocate of allocations) { @@ -164,6 +165,40 @@ async function leaseIdsOnRealDaemon(allocations: CapturedDaemonRequest[]): Promi } } +test('the Node client is refused a provider lease until it names a session', async () => { + const daemon = await startPublicDaemonRuntime({ serverMode: 'http' }); + const connection = { + daemonBaseUrl: daemon.baseUrl, + daemonAuthToken: daemon.runtime.token, + daemonTransport: 'http', + } as const; + const lease = { + tenant: 'acme', + runId: 'run-a', + leaseBackend: 'android-instance', + leaseProvider: 'proxy', + clientId: 'client-a', + } as const; + try { + await assert.rejects( + createAgentDeviceClient(connection).leases.allocate(lease), + (error: { details?: { reason?: string } }) => + error.details?.reason === 'REMOTE_SESSION_REQUIRED', + ); + + const named = createAgentDeviceClient({ ...connection, session: 'agent-a' }); + const leaseId = (await named.leases.allocate(lease)).leaseId; + assert.ok(leaseId); + const namedPerCall = await createAgentDeviceClient(connection).leases.allocate({ + ...lease, + session: 'agent-a', + }); + assert.equal(namedPerCall.leaseId, leaseId); + } finally { + await daemon.close(); + } +}); + function allocationOf(result: Awaited>): CapturedDaemonRequest { const allocate = result.calls.find((call) => call.command === 'lease_allocate'); assert.ok(allocate, result.stdout); @@ -302,6 +337,7 @@ test('a session named by flag, env or config never falls back onto the pointer', result.calls.map((call) => call.command), ['snapshot'], ); + assert.equal(result.calls[0]?.meta?.sessionExplicit, true); assert.equal(scopeOf(result.calls[0]!, 'tenantId'), undefined); assert.equal(leaseIdOf(result.calls[0]), undefined); } diff --git a/src/__tests__/cli-maestro-suite.test.ts b/src/__tests__/cli-maestro-suite.test.ts new file mode 100644 index 0000000000..e792ae7899 --- /dev/null +++ b/src/__tests__/cli-maestro-suite.test.ts @@ -0,0 +1,47 @@ +import { test } from 'vitest'; +import { installedReplayCliTestEnv } from './cli-test-env.ts'; +import assert from 'node:assert/strict'; +import { promises as fs } from 'node:fs'; +import path from 'node:path'; +import { runCliCapture } from './cli-capture.ts'; +import { mkdtempForTest } from '@agent-device/test-kit'; + +test('test --maestro forwards Maestro backend and platform for directory suites', async () => { + const tmpDir = await mkdtempForTest('agent-device-cli-maestro-suite-'); + await fs.writeFile( + path.join(tmpDir, 'auth-flow.yml'), + ['appId: demo.app', '---', '- launchApp', ''].join('\n'), + ); + + try { + const result = await runCliCapture( + ['test', '--maestro', '--platform', 'android', tmpDir], + async () => ({ + ok: true, + data: { + total: 1, + executed: 1, + passed: 1, + failed: 0, + skipped: 0, + notRun: 0, + durationMs: 5, + failures: [], + tests: [], + }, + }), + { cwd: tmpDir, env: installedReplayCliTestEnv() }, + ); + + assert.equal(result.code, null); + assert.equal(result.calls.length, 1); + assert.equal(result.calls[0]?.command, 'test'); + assert.deepEqual(result.calls[0]?.positionals, [tmpDir]); + assert.equal(result.calls[0]?.flags?.replayBackend, 'maestro'); + assert.equal(result.calls[0]?.flags?.platform, 'android'); + assert.equal(result.calls[0]?.meta?.requestProgress, 'replay-test'); + assert.doesNotMatch(result.stderr, /Running replay suite\.\.\./); + } finally { + await fs.rm(tmpDir, { recursive: true, force: true }); + } +}); diff --git a/src/__tests__/cli-network.test.ts b/src/__tests__/cli-network.test.ts index af178c0772..8b93f0344d 100644 --- a/src/__tests__/cli-network.test.ts +++ b/src/__tests__/cli-network.test.ts @@ -703,45 +703,6 @@ test('test command --debug prints failed attempt step window when timing trace e } }); -test('test --maestro forwards Maestro backend and platform for directory suites', async () => { - const tmpDir = await mkdtempForTest('agent-device-cli-maestro-suite-'); - await fs.writeFile( - path.join(tmpDir, 'auth-flow.yml'), - ['appId: demo.app', '---', '- launchApp', ''].join('\n'), - ); - - try { - const result = await runTestSuiteCli( - ['test', '--maestro', '--platform', 'android', tmpDir], - async () => ({ - ok: true, - data: { - total: 1, - executed: 1, - passed: 1, - failed: 0, - skipped: 0, - notRun: 0, - durationMs: 5, - failures: [], - tests: [], - }, - }), - ); - - assert.equal(result.code, null); - assert.equal(result.calls.length, 1); - assert.equal(result.calls[0]?.command, 'test'); - assert.deepEqual(result.calls[0]?.positionals, [tmpDir]); - assert.equal(result.calls[0]?.flags?.replayBackend, 'maestro'); - assert.equal(result.calls[0]?.flags?.platform, 'android'); - assert.equal(result.calls[0]?.meta?.requestProgress, 'replay-test'); - assert.doesNotMatch(result.stderr, /Running replay suite\.\.\./); - } finally { - await fs.rm(tmpDir, { recursive: true, force: true }); - } -}); - test('test forwards shard flags and comma device lists', async () => { const result = await runTestSuiteCli( ['test', '--maestro', '--device', 'udid1,emulator-5554', '--shard-all', '2', './suite'], diff --git a/src/__tests__/cli-replay-script-sources.test.ts b/src/__tests__/cli-replay-script-sources.test.ts index 7a28590105..4ca757191f 100644 --- a/src/__tests__/cli-replay-script-sources.test.ts +++ b/src/__tests__/cli-replay-script-sources.test.ts @@ -9,6 +9,7 @@ import path from 'node:path'; import assert from 'node:assert/strict'; import { test } from 'vitest'; import type { ReplayScriptSourceBundle } from '@agent-device/contracts/replay'; +import { installedReplayCliTestEnv } from './cli-test-env.ts'; import { runCliCapture } from './cli-capture.ts'; import { mkdtempForTestSync } from '@agent-device/test-kit'; @@ -83,7 +84,11 @@ test('a Maestro replay against a remote daemon sends its runFlow includes too', const result = await runCliCapture( ['replay', './flows/checkout.yaml', '--maestro', '--platform', 'ios'], - { cwd, env: REMOTE_DAEMON_ENV, defaultResponse: { ok: true, data: { replayed: 1 } } }, + { + cwd, + env: { ...REMOTE_DAEMON_ENV, ...installedReplayCliTestEnv() }, + defaultResponse: { ok: true, data: { replayed: 1 } }, + }, ); const bundle = result.calls[0]?.flags?.replayScriptSource as ReplayScriptSourceBundle | undefined; @@ -110,7 +115,7 @@ test.each(['native', 'maestro'])( ['test', maestro ? './*.yaml' : './*.ad', '--json', ...(maestro ? ['--maestro'] : [])], { cwd, - env: REMOTE_DAEMON_ENV, + env: { ...REMOTE_DAEMON_ENV, ...(maestro ? installedReplayCliTestEnv() : {}) }, defaultResponse: { ok: true, data: { tests: [], total: 0, passed: 0, failed: 0 } }, }, ); diff --git a/src/__tests__/cli-startup-import-closure.test.ts b/src/__tests__/cli-startup-import-closure.test.ts index 19d668bc0c..a5ba6f846f 100644 --- a/src/__tests__/cli-startup-import-closure.test.ts +++ b/src/__tests__/cli-startup-import-closure.test.ts @@ -27,6 +27,9 @@ const LAZY_HTTP_MODULES = new Set(['node:http', 'node:https']); */ function isLazyEngineModule(specifier: string): boolean { return ( + ['@agent-device/replay', '@agent-device/ad-replay', '@agent-device/replay-test'].some( + (name) => specifier === name || specifier.startsWith(`${name}/`), + ) || specifier === '@agent-device/maestro' || (specifier.startsWith('@agent-device/maestro/') && specifier !== '@agent-device/maestro/replay-backend-declaration') @@ -34,6 +37,15 @@ function isLazyEngineModule(specifier: string): boolean { } test('the lazy engine set covers the plugin subpath but not its engine-free declaration', () => { + for (const name of [ + '@agent-device/replay', + '@agent-device/ad-replay', + '@agent-device/replay-test', + ]) { + expect(isLazyEngineModule(name)).toBe(true); + expect(isLazyEngineModule(`${name}/agent-device`)).toBe(true); + expect(isLazyEngineModule(`${name}ish`)).toBe(false); + } expect(isLazyEngineModule('@agent-device/maestro')).toBe(true); expect(isLazyEngineModule('@agent-device/maestro/replay-backend')).toBe(true); expect(isLazyEngineModule('@agent-device/maestro/replay-backend-declaration')).toBe(false); @@ -116,7 +128,7 @@ test('the CLI startup import closure never evaluates node:http or node:https', ( ).toEqual([]); }); -test('the CLI startup import closure never evaluates the Maestro engine', () => { +test('the CLI startup import closure never evaluates a lazy replay engine', () => { const offenders: string[] = []; for (const file of eagerClosureOf(path.join(srcRoot, 'cli.ts'))) { for (const specifier of eagerlyEvaluatedModules(file, fs.readFileSync(file, 'utf8'))) { @@ -128,13 +140,12 @@ test('the CLI startup import closure never evaluates the Maestro engine', () => expect( offenders, - 'Load @agent-device/maestro on demand instead: the command registry evaluates every command ' + - 'family on startup, so importing the engine here costs every warm CLI command ~28ms of ' + - 'YAML-parser evaluation and a 131 kB startup chunk, for a format most runs never use.', + 'Load replay engine packages on demand instead: the command registry evaluates every command ' + + 'family on startup, so eager engine imports add their parsing and execution code to every CLI invocation.', ).toEqual([]); }); -test('the replay command source closure keeps Maestro behind flow selection', () => { +test('the replay command source closure keeps replay engines behind execution or source selection', () => { const replayEntry = path.join(srcRoot, '../packages/command-surface/src/replay/index.ts'); const replayClosure = eagerClosureOf(replayEntry); const sourceBundle = path.join(srcRoot, '../packages/replay-port/src/script-source-bundle.ts'); @@ -149,7 +160,7 @@ test('the replay command source closure keeps Maestro behind flow selection', () expect( offenders, - 'The replay command may evaluate @agent-device/maestro only inside flow source collection.', + 'The replay command must load replay engines only for execution or flow source collection.', ).toEqual([]); }); diff --git a/src/__tests__/cli-test-env.ts b/src/__tests__/cli-test-env.ts index 188ea44d18..97119c682d 100644 --- a/src/__tests__/cli-test-env.ts +++ b/src/__tests__/cli-test-env.ts @@ -1,3 +1,4 @@ +import { installWorkspaceReplayPlugins } from '../../scripts/install-workspace-replay-plugins.ts'; import fs from 'node:fs'; import path from 'node:path'; import { mkdtempForTestSync } from '@agent-device/test-kit'; @@ -33,6 +34,13 @@ export function installIsolatedCliTestEnv( } } + if (!explicitKeys.has('AGENT_DEVICE_HOME') && !explicitKeys.has('HOME')) { + if (!previousEnv.has('AGENT_DEVICE_HOME')) + previousEnv.set('AGENT_DEVICE_HOME', process.env.AGENT_DEVICE_HOME); + process.env.AGENT_DEVICE_HOME = path.join(tempRoot, 'plugins'); + installWorkspaceReplayPlugins(process.env, true); + } + return () => { for (const [key, value] of previousEnv.entries()) { if (value === undefined) { @@ -44,3 +52,9 @@ export function installIsolatedCliTestEnv( fs.rmSync(tempRoot, { recursive: true, force: true }); }; } + +export function installedReplayCliTestEnv(): Record { + const env = { AGENT_DEVICE_HOME: mkdtempForTestSync('agent-device-cli-replay-') }; + installWorkspaceReplayPlugins(env, true); + return env; +} diff --git a/src/__tests__/cloud-connect-profile-fields.test.ts b/src/__tests__/cloud-connect-profile-fields.test.ts index 9d99f07da9..e66c08bf5c 100644 --- a/src/__tests__/cloud-connect-profile-fields.test.ts +++ b/src/__tests__/cloud-connect-profile-fields.test.ts @@ -3,7 +3,6 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; -import { resolveConnectProviderProfile } from '../cli/connection/connect-provider-adapters.ts'; import { resolveLimrunConnectProfile } from '../cli/connection/limrun-profile.ts'; import { runCliCapture } from './cli-capture.ts'; import { mkdtempForTestSync } from '@agent-device/test-kit'; @@ -63,35 +62,3 @@ test('connect limrun applies the same refusal when attaching to an existing inst fs.rmSync(tempRoot, { recursive: true, force: true }); } }); - -test('connect browserstack refuses AWS Device Farm flags', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-browserstack-reject-'); - - try { - await assert.rejects( - resolveConnectProviderProfile({ - provider: 'browserstack', - stateDir: path.join(tempRoot, '.state'), - cwd: tempRoot, - env: {}, - flags: { - json: false, - help: false, - version: false, - platform: 'android', - device: 'Google Pixel 8', - awsProjectArn: 'arn:aws:devicefarm:us-west-2:123:project:project-a', - }, - }), - (error: unknown) => { - assert.ok(error instanceof AppError); - assert.equal(error.code, 'INVALID_ARGS'); - assert.equal(error.details?.provider, 'browserstack'); - assert.deepEqual(error.details?.flags, ['--aws-project-arn']); - return true; - }, - ); - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); diff --git a/src/__tests__/cloud-connect-profile.test.ts b/src/__tests__/cloud-connect-profile.test.ts index ef155269ca..4e68d3453f 100644 --- a/src/__tests__/cloud-connect-profile.test.ts +++ b/src/__tests__/cloud-connect-profile.test.ts @@ -8,24 +8,17 @@ import { runCliCapture } from './cli-capture.ts'; import { hashRemoteConfigFile, readActiveConnectionState, - readRemoteConnectionState, type RemoteConnectionState, } from '@agent-device/remote/remote-connection-state'; import type { AgentDeviceClient } from '@agent-device/command-surface'; -import { resolveConnectProviderProfile } from '../cli/connection/connect-provider-adapters.ts'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { verifyLimrunConnection } from '@agent-device/provider-limrun'; -import { - verifyAwsDeviceFarmConnection, - verifyBrowserStackConnection, -} from '@agent-device/provider-webdriver/connection-verification'; import { mkdtempForTestSync, bindTestCommandHost, createTestHostEnvironment, beginStdoutCapture, } from '@agent-device/test-kit'; -import { connectWithGeneratedProviderProfile } from './test-utils/connect-command.ts'; bindTestCommandHost(); @@ -39,14 +32,6 @@ vi.mock('@agent-device/provider-limrun', async (importOriginal) => ({ verifyLimrunConnection: vi.fn(), })); -vi.mock('@agent-device/provider-webdriver/connection-verification', async (importOriginal) => ({ - ...(await importOriginal< - typeof import('@agent-device/provider-webdriver/connection-verification') - >()), - verifyBrowserStackConnection: vi.fn(), - verifyAwsDeviceFarmConnection: vi.fn(), -})); - afterEach(() => { vi.clearAllMocks(); vi.unstubAllGlobals(); @@ -54,8 +39,6 @@ afterEach(() => { const mockedResolveCloudAccessForConnect = vi.mocked(resolveCloudAccessForConnect); const mockedVerifyLimrunConnection = vi.mocked(verifyLimrunConnection); -const mockedVerifyBrowserStackConnection = vi.mocked(verifyBrowserStackConnection); -const mockedVerifyAwsDeviceFarmConnection = vi.mocked(verifyAwsDeviceFarmConnection); beforeEach(() => { mockedVerifyLimrunConnection.mockResolvedValue({ @@ -72,36 +55,6 @@ beforeEach(() => { message: 'Run apps to choose an uploaded asset before allocation.', }, }); - mockedVerifyBrowserStackConnection.mockImplementation(async (options) => ({ - provider: 'browserstack', - service: 'BrowserStack', - verificationMessage: 'Credentials, device, and uploaded app verified.', - device: { - status: 'verified', - name: options.deviceName, - platform: options.platform, - osVersion: options.osVersion, - }, - app: { status: 'verified', reference: options.app }, - })); - mockedVerifyAwsDeviceFarmConnection.mockImplementation(async (options) => ({ - provider: 'aws-device-farm', - service: 'AWS Device Farm', - verificationMessage: 'Credentials, project, and device verified.', - project: { name: 'Agent Device', reference: options.projectArn }, - device: { - status: 'verified', - name: 'iPhone 15', - reference: options.deviceArn, - platform: options.platform, - osVersion: '17', - }, - app: { - status: 'missing', - message: - 'No app upload is attached; AWS Device Farm does not support install after allocation.', - }, - })); }); test('connect without remote config generates one from cloud connection profile', async () => { @@ -423,199 +376,6 @@ test('connect without remote config reports unsupported cloud profile keys', asy } }); -test('connect browserstack generates local provider profile without credentials', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-browserstack-'); - const stateDir = path.join(tempRoot, '.state'); - vi.stubEnv('BROWSERSTACK_USERNAME', 'browser-user'); - vi.stubEnv('BROWSERSTACK_ACCESS_KEY', 'browser-key'); - - try { - await connectWithGeneratedProviderProfile({ - stateDir, - positionals: ['browserstack'], - flags: { - platform: 'android', - device: 'Google Pixel 8', - providerOsVersion: '14.0', - providerApp: 'bs://app-id', - providerProject: 'agent-device', - providerBuild: 'build-a', - }, - }); - - const state = readRequiredActiveState(stateDir); - assert.equal(state.tenant, 'browserstack'); - assert.equal(state.leaseProvider, 'browserstack'); - assert.equal(state.daemon?.baseUrl, undefined); - assert.match(state.remoteConfigPath, /generated\/browserstack-[a-f0-9]{16}\.json$/); - const generated = readGeneratedConfig(state.remoteConfigPath); - assert.equal(generated.providerApp, 'bs://app-id'); - assert.equal(generated.providerOsVersion, '14.0'); - assert.equal(generated.providerProject, 'agent-device'); - assert.equal(generated.providerBuild, 'build-a'); - assert.equal(JSON.stringify(generated).includes('browser-key'), false); - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); - -test('connect browserstack canonicalizes the app scheme and refuses a malformed bs:// id', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-browserstack-ref-'); - const stateDir = path.join(tempRoot, '.state'); - vi.stubEnv('BROWSERSTACK_USERNAME', 'browser-user'); - vi.stubEnv('BROWSERSTACK_ACCESS_KEY', 'browser-key'); - const flags = { - platform: 'android' as const, - device: 'Google Pixel 8', - providerOsVersion: '14.0', - }; - - try { - await connectWithGeneratedProviderProfile({ - stateDir, - positionals: ['browserstack'], - flags: { ...flags, providerApp: 'Bs://app-id' }, - }); - assert.equal( - readGeneratedConfig(readRequiredActiveState(stateDir).remoteConfigPath).providerApp, - 'bs://app-id', - ); - // Verification must look up the reference the profile saved, not the spelling typed. - assert.equal(mockedVerifyBrowserStackConnection.mock.calls[0]?.[0].app, 'bs://app-id'); - - for (const app of ['bs://', 'bs://a b', 'BS://a/b']) { - await assert.rejects( - resolveConnectProviderProfile({ - provider: 'browserstack', - stateDir, - cwd: tempRoot, - env: { BROWSERSTACK_USERNAME: 'browser-user', BROWSERSTACK_ACCESS_KEY: 'browser-key' }, - flags: { json: false, help: false, version: false, ...flags, providerApp: app }, - }), - (error: unknown) => { - assert.ok(error instanceof AppError); - assert.equal(error.code, 'INVALID_ARGS'); - assert.equal(error.message, `BrowserStack --provider-app ${app} is not a bs:// app id.`); - assert.deepEqual(error.details, { - providerApp: app, - hint: 'Pass .', - }); - return true; - }, - ); - } - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); - -test('connect --remote-config verifies a direct provider profile before saving state', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-provider-config-'); - const stateDir = path.join(tempRoot, '.state'); - const remoteConfig = path.join(tempRoot, 'browserstack.remote.json'); - fs.writeFileSync( - remoteConfig, - JSON.stringify({ - tenant: 'browserstack', - runId: 'browserstack-config', - sessionIsolation: 'tenant', - leaseProvider: 'browserstack', - leaseBackend: 'android-instance', - platform: 'android', - target: 'mobile', - device: 'Google Pixel 8', - providerOsVersion: '14.0', - providerApp: 'bs://app-id', - }), - ); - vi.stubEnv('BROWSERSTACK_USERNAME', 'browser-user'); - vi.stubEnv('BROWSERSTACK_ACCESS_KEY', 'browser-key'); - - try { - await connectWithGeneratedProviderProfile({ - stateDir, - positionals: [], - flags: { remoteConfig }, - }); - - assert.equal(mockedVerifyBrowserStackConnection.mock.calls.length, 1); - assert.deepEqual(mockedVerifyBrowserStackConnection.mock.calls[0]?.[0], { - username: 'browser-user', - accessKey: 'browser-key', - platform: 'android', - deviceName: 'Google Pixel 8', - osVersion: '14.0', - app: 'bs://app-id', - }); - assert.equal(readRequiredActiveState(stateDir).remoteConfigPath, remoteConfig); - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); - -test('connect browserstack persists a local app artifact as an absolute path', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-browserstack-app-'); - const stateDir = path.join(tempRoot, '.state'); - const appPath = path.join(tempRoot, 'sample.apk'); - fs.writeFileSync(appPath, 'fixture'); - vi.stubEnv('BROWSERSTACK_USERNAME', 'browser-user'); - vi.stubEnv('BROWSERSTACK_ACCESS_KEY', 'browser-key'); - - try { - // The host the command runs in decides what `./sample.apk` is relative to. - await connectWithGeneratedProviderProfile({ - stateDir, - host: { env: process.env, cwd: fs.realpathSync(tempRoot) }, - positionals: ['browserstack'], - flags: { - platform: 'android', - device: 'Google Pixel 8', - providerOsVersion: '14.0', - providerApp: './sample.apk', - }, - }); - - const state = readRequiredActiveState(stateDir); - assert.equal(readGeneratedConfig(state.remoteConfigPath).providerApp, fs.realpathSync(appPath)); - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); - -test('connect aws-device-farm generates local provider profile from flags', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-aws-'); - const stateDir = path.join(tempRoot, '.state'); - - try { - await connectWithGeneratedProviderProfile({ - stateDir, - positionals: ['aws-device-farm'], - flags: { - platform: 'ios', - device: 'Apple iPhone 15', - awsProjectArn: 'arn:aws:devicefarm:us-west-2:123:project:project-a', - awsDeviceArn: 'arn:aws:devicefarm:us-west-2::device:device-a', - awsAppArn: 'arn:aws:devicefarm:us-west-2:123:upload:app-a', - awsInteractionMode: 'INTERACTIVE', - }, - }); - - const state = readRequiredActiveState(stateDir); - assert.equal(state.tenant, 'aws-device-farm'); - assert.equal(state.leaseProvider, 'aws-device-farm'); - assert.equal(state.daemon?.baseUrl, undefined); - assert.match(state.remoteConfigPath, /generated\/aws-device-farm-[a-f0-9]{16}\.json$/); - const generated = readGeneratedConfig(state.remoteConfigPath); - assert.equal(generated.awsProjectArn, 'arn:aws:devicefarm:us-west-2:123:project:project-a'); - assert.equal(generated.awsDeviceArn, 'arn:aws:devicefarm:us-west-2::device:device-a'); - assert.equal(generated.awsAppArn, 'arn:aws:devicefarm:us-west-2:123:upload:app-a'); - assert.equal(generated.awsRegion, 'us-west-2'); - assert.equal(generated.awsInteractionMode, 'INTERACTIVE'); - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); - test('connect output makes verified configuration, deferred device allocation, and app recovery explicit', async () => { const environment = { LIMRUN_API_KEY: 'lim_test_key', AGENT_DEVICE_SESSION: 'ci' }; const result = await runCliCapture(['connect', 'limrun', '--platform', 'android'], { @@ -636,165 +396,13 @@ test('connect output makes verified configuration, deferred device allocation, a ); assert.match(result.stdout, /No live device session has been created/); assert.match(result.stdout, /Next:/); - assert.match(result.stdout, /agent-device apps/); - assert.match(result.stdout, /agent-device open /); - assert.doesNotMatch(result.stdout, /agent-device install/); + assert.match(result.stdout, /agent-device apps --session ci/); + assert.match(result.stdout, /agent-device open --session ci/); + assert.match(result.stdout, /agent-device install --session ci/); + assert.match(result.stdout, /agent-device open --relaunch --session ci/); assert.doesNotMatch(result.stdout, /lease pending/); }); -test('connect JSON exposes verification, device, app, live-session, and next-step state', async () => { - const result = await runCliCapture( - [ - 'connect', - 'aws-device-farm', - '--session=ci', - '--platform', - 'ios', - '--aws-project-arn', - 'project-arn', - '--aws-device-arn', - 'device-arn', - '--json', - ], - { stateDirPrefix: 'agent-device-connect-aws-output-' }, - ); - - assert.equal(result.code, null); - const output = (JSON.parse(result.stdout) as { data: Record }).data; - assert.equal(output.verification.status, 'verified'); - assert.equal(output.device.name, 'iPhone 15'); - assert.equal(output.app.status, 'missing'); - assert.equal(output.liveSession.status, 'not-created'); - assert.deepEqual(output.nextSteps, [ - `agent-device connect aws-device-farm --platform ios --aws-project-arn project-arn --aws-device-arn device-arn --aws-app-arn --force --session ${output.session}`, - `agent-device open --relaunch --session ${output.session}`, - ]); - assert.deepEqual(output.leasePreparation.nextSteps, output.nextSteps); - assert.deepEqual(output.notes, [ - `After close, run agent-device artifacts --json --session ${output.session} for provider video and logs.`, - ]); -}); - -test('connect JSON preserves BrowserStack workflow notes from human output', async () => { - const result = await runCliCapture( - [ - 'connect', - 'browserstack', - '--session=ci', - '--platform', - 'android', - '--device', - 'Google Pixel 8', - '--provider-os-version', - '14.0', - '--provider-app', - 'bs://app-id', - '--json', - ], - { - env: { - BROWSERSTACK_USERNAME: 'browser-user', - BROWSERSTACK_ACCESS_KEY: 'browser-key', - }, - stateDirPrefix: 'agent-device-connect-browserstack-json-', - }, - ); - - assert.equal(result.code, null); - const output = (JSON.parse(result.stdout) as { data: Record }).data; - assert.deepEqual(output.nextSteps, [ - `agent-device open --relaunch --session ${output.session}`, - ]); - assert.deepEqual(output.notes, [ - 'Use the installed package or bundle identifier in open, not the app artifact name.', - `After close, run agent-device artifacts --json --session ${output.session} for provider video and logs.`, - ]); -}); - -test('every command BrowserStack connect emits resolves back to the connection that emitted it', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-scoped-commands-'); - const stateDir = path.join(tempRoot, '.state'); - const browserstackArgs = [ - 'connect', - 'browserstack', - '--platform', - 'android', - '--device', - 'Google Pixel 8', - '--provider-os-version', - '14.0', - '--provider-app', - 'bs://app-id', - '--state-dir', - stateDir, - ]; - const captureOptions = { - env: { BROWSERSTACK_USERNAME: 'browser-user', BROWSERSTACK_ACCESS_KEY: 'browser-key' }, - }; - - try { - const json = await runCliCapture( - [...browserstackArgs, '--session=bs-1', '--json'], - captureOptions, - ); - const human = await runCliCapture([...browserstackArgs, '--session=bs-2'], captureOptions); - - assert.equal(json.code, null); - assert.equal(human.code, null); - const output = (JSON.parse(json.stdout) as { data: Record }).data; - const session: string = output.session; - - // Every emitted command — nextSteps AND the prose notes — must name a - // session, so following one cannot adopt whichever connection happens to - // be host-global active in a concurrent run. - for (const line of [...output.nextSteps, ...output.notes]) { - assertCommandsAreSessionScoped(line, session); - } - assert.deepEqual([...readEmittedSessions([...output.nextSteps, ...output.notes])], [session]); - - // The human run is a second connect under its own session; its commands must name THAT one, - // not the JSON run's. - const humanSessions = [...readEmittedSessions([human.stdout])]; - assert.equal(humanSessions.length, 1, human.stdout); - const humanSession = humanSessions[0] ?? ''; - assert.notEqual(humanSession, session); - assertCommandsAreSessionScoped(human.stdout, humanSession); - - // The scope is not decoration: resolving each emitted --session lands on - // the connection state that connect wrote. - for (const emittedSession of [session, humanSession]) { - const state = readRemoteConnectionState({ stateDir, session: emittedSession }); - assert.equal(state?.session, emittedSession); - assert.equal(state?.leaseProvider, 'browserstack'); - assert.equal(state?.tenant, 'browserstack'); - } - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); - -/** - * A command-bearing string must carry one `--session ` per `agent-device` - * invocation it suggests. Counting rather than matching means an added command - * cannot silently ship unscoped alongside a scoped sibling. - */ -function assertCommandsAreSessionScoped(text: string, session: string): void { - const commands = text.match(/agent-device\s+[a-z]/g)?.length ?? 0; - const scopes = text.split(`--session ${session}`).length - 1; - assert.equal(scopes, commands, `unscoped suggested command in: ${text}`); -} - -function readEmittedSessions(texts: readonly string[]): Set { - const sessions = new Set(); - for (const text of texts) { - for (const match of text.matchAll(/--session\s+(\S+)/g)) { - const value = match[1]; - if (value) sessions.add(value); - } - } - return sessions; -} - test('connect does not activate provider state when verification fails', async () => { const tempRoot = mkdtempForTestSync('agent-device-connect-verify-fail-'); const stateDir = path.join(tempRoot, '.state'); @@ -828,44 +436,6 @@ test('connect does not activate provider state when verification fails', async ( } }); -test('connect aws-device-farm rejects device-feature flags it does not read', async () => { - const tempRoot = mkdtempForTestSync('agent-device-connect-aws-reject-'); - - try { - await assert.rejects( - resolveConnectProviderProfile({ - provider: 'aws-device-farm', - stateDir: path.join(tempRoot, '.state'), - cwd: tempRoot, - env: {}, - flags: { - json: false, - help: false, - version: false, - platform: 'android', - device: 'Google Pixel 8', - providerDeviceOrientation: 'portrait', - providerTimezone: 'New_York', - }, - }), - (error: unknown) => { - assert.ok(error instanceof AppError); - assert.equal(error.code, 'INVALID_ARGS'); - // Names every offending flag, and fires before the provider's own required-arg checks so - // the caller is told what is unsupported rather than what else is missing. - assert.equal(error.details?.provider, 'aws-device-farm'); - assert.deepEqual(error.details?.flags, [ - '--provider-device-orientation', - '--provider-timezone', - ]); - return true; - }, - ); - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); - function mockCloudConnectionProfile(connection: Record): ReturnType { mockedResolveCloudAccessForConnect.mockResolvedValue({ accessToken: 'adc_agent_cloud', diff --git a/src/__tests__/cloud-connect-testmu.test.ts b/src/__tests__/cloud-connect-testmu.test.ts index ddb3b18311..f5c8ec96e9 100644 --- a/src/__tests__/cloud-connect-testmu.test.ts +++ b/src/__tests__/cloud-connect-testmu.test.ts @@ -15,7 +15,8 @@ import { resolveConnectProviderProfile } from '../cli/connection/connect-provide import { mkdtempForTestSync, pluginHome, - selectPlugin, + selectV2Plugin, + v2RegistrationSource, bindTestCommandHost, } from '@agent-device/test-kit'; import manifest from '@agent-device/testmu/package.json' with { type: 'json' }; @@ -50,20 +51,16 @@ const mockedVerifyWebDriverConnection = vi.mocked(verifyTestMuConnection); beforeEach(() => { const { home } = pluginHome(); - selectPlugin(home, manifest.name, 'testmu', 'export default () => {};'); - const { installation } = JSON.parse(fs.readFileSync(path.join(home, 'config.json'), 'utf8')) - .plugins[manifest.name]; - const manifestPath = path.join( + // The store declares the plugin installed with TestMu's capabilities; the mocked loader above + // supplies the workspace factory those assertions exercise. + selectV2Plugin( home, - 'plugins', - installation, - 'node_modules', manifest.name, - 'package.json', + v2RegistrationSource('testmu', { + extra: `connection: { capabilities: ${JSON.stringify(testmu().connection?.capabilities)}, resolve() {}, verify() {} },`, + credentials: '{ variables: ["LT_USERNAME", "LT_ACCESS_KEY"] }', + }), ); - const declared = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); - declared.agentDevicePlugin.connection = manifest.agentDevicePlugin.connection; - fs.writeFileSync(manifestPath, JSON.stringify(declared)); vi.stubEnv('AGENT_DEVICE_HOME', home); mockedVerifyWebDriverConnection.mockImplementation(async (options) => { assert.equal(options.provider, 'testmu'); @@ -129,17 +126,12 @@ test('connect testmu generates a local provider profile and verifies the virtual test('connect canonicalizes an upper-case app scheme and refuses an empty app id', async () => { const tempRoot = mkdtempForTestSync('agent-device-connect-app-scheme-'); const base = { json: false, help: false, version: false, platform: 'ios' as const }; - const connect = async (provider: 'testmu' | 'browserstack', providerApp: string) => + const connect = async (provider: 'testmu', providerApp: string) => await resolveConnectProviderProfile({ provider, stateDir: path.join(tempRoot, `.state-${provider}`), cwd: tempRoot, - env: { - LT_USERNAME: 'u', - LT_ACCESS_KEY: 'k', - BROWSERSTACK_USERNAME: 'u', - BROWSERSTACK_ACCESS_KEY: 'k', - }, + env: { LT_USERNAME: 'u', LT_ACCESS_KEY: 'k' }, flags: { ...base, device: 'iPhone 16', providerOsVersion: '18.0', providerApp }, }); @@ -148,22 +140,17 @@ test('connect canonicalizes an upper-case app scheme and refuses an empty app id assert.equal(readGeneratedConfig(upperCase.remoteConfigPath).providerApp, 'lt://APP1'); // Connect verification reads these flags, so they must carry the canonical reference too. assert.equal(upperCase.flags.providerApp, 'lt://APP1'); - assert.equal( - readGeneratedConfig((await connect('browserstack', 'Bs://abc')).remoteConfigPath).providerApp, - 'bs://abc', - ); for (const [provider, app] of [ ['testmu', 'lt://'], ['testmu', 'lt://a b'], ['testmu', 'LT://a/b'], - ['browserstack', 'bs://'], ] as const) { await assert.rejects( connect(provider, app), (error: unknown) => error instanceof AppError && error.code === 'INVALID_ARGS' && - /valid lt:\/\/ app reference|is not a bs:\/\/ app id/.test(error.message), + /valid lt:\/\/ app reference/.test(error.message), ); } } finally { @@ -292,25 +279,7 @@ test('providers other than TestMu refuse --provider-device-type before saving a try { for (const [provider, flags, env] of [ - [ - 'browserstack', - { - ...base, - device: 'Google Pixel 8', - providerOsVersion: '14.0', - providerApp: 'bs://app-id', - }, - { BROWSERSTACK_USERNAME: 'u', BROWSERSTACK_ACCESS_KEY: 'k' }, - ], - [ - 'aws-device-farm', - { - ...base, - awsProjectArn: 'arn:aws:devicefarm:us-west-2:123:project/p', - awsDeviceArn: 'arn:aws:devicefarm:us-west-2::device/d', - }, - {}, - ], + ['limrun', { ...base, tenant: 'team-a', runId: 'run-a' }, { LIMRUN_API_KEY: 'lim_test_key' }], ] as const) { await assert.rejects( resolveConnectProviderProfile({ diff --git a/src/__tests__/daemon-composition/snapshot-presentation-transitions.test.ts b/src/__tests__/daemon-composition/snapshot-presentation-transitions.test.ts index abe7231e1b..728291c636 100644 --- a/src/__tests__/daemon-composition/snapshot-presentation-transitions.test.ts +++ b/src/__tests__/daemon-composition/snapshot-presentation-transitions.test.ts @@ -68,7 +68,7 @@ test('promoted navigation title dispatches as its presented button semantics, no tappedPoint = point; }, }, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), policy: localCommandPolicy(), }); await device.sessions.set({ name: 'default', snapshot }); diff --git a/src/__tests__/lease-provider-profile-fields.test.ts b/src/__tests__/lease-provider-profile-fields.test.ts index 7733211aef..dd07a710d8 100644 --- a/src/__tests__/lease-provider-profile-fields.test.ts +++ b/src/__tests__/lease-provider-profile-fields.test.ts @@ -38,6 +38,7 @@ test('leases.allocate refuses an OS version Limrun cannot honour instead of igno daemonBaseUrl: daemon.baseUrl, daemonAuthToken: daemon.runtime.token, daemonTransport: 'http', + session: 'agent-a', }); await assert.rejects( client.leases.allocate({ diff --git a/src/__tests__/limrun-runtime.test.ts b/src/__tests__/limrun-runtime.test.ts index 8e8d4c9a5c..ee8e8df212 100644 --- a/src/__tests__/limrun-runtime.test.ts +++ b/src/__tests__/limrun-runtime.test.ts @@ -5,14 +5,24 @@ import { afterEach, expect, test, vi } from 'vitest'; import type { ClientOptions } from '@limrun/api'; import { createInstanceClient as createAndroidInstanceClient } from '@limrun/api/instance-client'; import { createInstanceClient as createIosInstanceClient } from '@limrun/api/ios-client'; -import { LimrunRuntime } from '../sdk/limrun.ts'; +import { createLimrunRuntime, type LimrunRuntimeOptions } from '@agent-device/provider-limrun'; +import { createLimrunRuntimeDependencies } from '../sdk/limrun-runtime-dependencies.ts'; import type { DeviceLease } from '@agent-device/contracts/device'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; -import { runCmd } from '@agent-device/host-kit/command'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { commandHostEnvironment, withCommandHost, runCmd } from '@agent-device/host-kit/command'; import { readVersion } from '@agent-device/host-kit/version'; import { mkdtempForTestSync } from '@agent-device/test-kit'; +// The daemon's own composition: the provider runtime over the host adapters the daemon builds. +function createTestRuntime( + options: LimrunRuntimeOptions, + host: HostEnvironment = { env: process.env, cwd: process.cwd() }, +): ReturnType { + return createLimrunRuntime(options, createLimrunRuntimeDependencies(host)); +} + type LimrunInstancePage = { getPaginatedItems: () => Array<{ metadata: { id: string } }>; }; @@ -147,20 +157,11 @@ afterEach(() => { }); test('Limrun runtime identifies direct CLI usage when creating an instance', async () => { - const runtime = new LimrunRuntime({ + const runtime = createTestRuntime({ apiKey: 'lim_test_key', }); - const lease: DeviceLease = { - leaseId: 'lease-a', - tenantId: 'team-a', - runId: 'run-a', - backend: 'ios-instance', - leaseProvider: 'limrun', - createdAt: 1, - heartbeatAt: 1, - expiresAt: 60_001, - }; + const lease = iosLease('lease-a'); try { const allocateLease = runtime.leaseLifecycle.allocate; @@ -193,17 +194,8 @@ test('Limrun runtime identifies direct CLI usage when creating an instance', asy }); test('Limrun refuses a refused field on a repeat allocation of its live lease', async () => { - const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' }); - const lease: DeviceLease = { - leaseId: 'lease-repeat', - tenantId: 'team-a', - runId: 'run-a', - backend: 'ios-instance', - leaseProvider: 'limrun', - createdAt: 1, - heartbeatAt: 1, - expiresAt: 60_001, - }; + const runtime = createTestRuntime({ apiKey: 'lim_test_key' }); + const lease = iosLease('lease-repeat'); try { const allocateLease = runtime.leaseLifecycle.allocate; if (!allocateLease) throw new Error('Limrun runtime must provide lease allocation'); @@ -222,7 +214,7 @@ test('Limrun refuses a refused field on a repeat allocation of its live lease', }); test('Limrun iOS uses shared deep-link classification', async () => { - const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' }); + const runtime = createTestRuntime({ apiKey: 'lim_test_key' }); const metadata = new Map([ ['com.apple.Preferences', ''], [ @@ -281,17 +273,8 @@ test('Limrun iOS uses shared deep-link classification', async () => { }); test('Limrun reclaims a labeled iOS instance without an in-memory session', async () => { - const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' }); - const lease: DeviceLease = { - leaseId: 'lease-recovered-ios', - tenantId: 'team-a', - runId: 'run-a', - backend: 'ios-instance', - leaseProvider: 'limrun', - createdAt: 1, - heartbeatAt: 1, - expiresAt: 60_001, - }; + const runtime = createTestRuntime({ apiKey: 'lim_test_key' }); + const lease = iosLease('lease-recovered-ios'); limrunMockState.iosList.mockResolvedValueOnce({ getPaginatedItems: () => [{ metadata: { id: 'ios-instance-recovered' } }], }); @@ -313,7 +296,7 @@ test('Limrun reclaims a labeled iOS instance without an in-memory session', asyn }); test('Limrun Android reverses localhost URL ports through the persistent ADB tunnel', async () => { - const runtime = new LimrunRuntime({ + const runtime = createTestRuntime({ apiKey: 'lim_test_key', }); @@ -340,7 +323,7 @@ test('Limrun Android reverses localhost URL ports through the persistent ADB tun test('Limrun keepAlive pings the session client every 30 s until release', async () => { vi.useFakeTimers(); try { - const runtime = new LimrunRuntime({ apiKey: 'lim_test_key', keepAlive: true }); + const runtime = createTestRuntime({ apiKey: 'lim_test_key', keepAlive: true }); const lease = androidLease(); await allocateLimrunDevice(runtime, lease); await vi.advanceTimersByTimeAsync(60_000); @@ -357,7 +340,7 @@ test('Limrun keepAlive pings the session client every 30 s until release', async test('Limrun keepAlive is off by default', async () => { vi.useFakeTimers(); try { - const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' }); + const runtime = createTestRuntime({ apiKey: 'lim_test_key' }); await allocateLimrunDevice(runtime, androidLease()); await vi.advanceTimersByTimeAsync(60_000); assert.equal(limrunMockState.androidKeepAlive.mock.calls.length, 0); @@ -373,7 +356,7 @@ test('Limrun keepAlive keeps pinging after the client throws', async () => { limrunMockState.androidKeepAlive.mockImplementationOnce(() => { throw new Error('socket closed'); }); - const runtime = new LimrunRuntime({ apiKey: 'lim_test_key', keepAlive: true }); + const runtime = createTestRuntime({ apiKey: 'lim_test_key', keepAlive: true }); await allocateLimrunDevice(runtime, androidLease()); await vi.advanceTimersByTimeAsync(60_000); assert.equal(limrunMockState.androidKeepAlive.mock.calls.length, 2); @@ -396,8 +379,12 @@ function androidLease(): DeviceLease { }; } +function iosLease(leaseId: string): DeviceLease { + return { ...androidLease(), leaseId, backend: 'ios-instance' }; +} + async function allocateLimrunDevice( - runtime: LimrunRuntime, + runtime: ReturnType, lease: DeviceLease, ): Promise { const allocateLease = runtime.leaseLifecycle.allocate; @@ -452,19 +439,10 @@ function assertAndroidTunnelLifecycle(openUrl: string): void { test('Limrun Android syncs direct local artifacts', async () => { const apkPath = path.join(mkdtempForTestSync('limrun-install-'), 'app-debug.apk'); fs.writeFileSync(apkPath, 'apk fixture'); - const runtime = new LimrunRuntime({ + const runtime = createTestRuntime({ apiKey: 'lim_test_key', }); - const lease: DeviceLease = { - leaseId: 'lease-android', - tenantId: 'team-a', - runId: 'run-a', - backend: 'android-instance', - leaseProvider: 'limrun', - createdAt: 1, - heartbeatAt: 1, - expiresAt: 60_001, - }; + const lease = androidLease(); try { const allocateLease = runtime.leaseLifecycle.allocate; @@ -474,11 +452,11 @@ test('Limrun Android syncs direct local artifacts', async () => { if (!device || typeof device !== 'object') { throw new Error('Limrun runtime must return allocated device metadata'); } - const allocatedDevice = device as Parameters[0]; + const allocatedDevice = device as DeviceInfo; assert.equal(allocatedDevice.platform, 'android'); assert.equal(allocatedDevice.id, 'limrun:android:lease-android'); - const result = await runtime.installApp(allocatedDevice, 'com.example.android', apkPath); + const result = await runtime.installApp?.(allocatedDevice, 'com.example.android', apkPath); assert.equal(limrunMockState.androidSendAsset.mock.calls.length, 0); expect(limrunMockState.androidSyncApp).toHaveBeenCalledWith(apkPath, { @@ -498,18 +476,18 @@ test('Limrun Android syncs direct local artifacts', async () => { }); test('Limrun Android shares an in-flight ADB tunnel across concurrent port reverse requests', async () => { - const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' }); + const runtime = createTestRuntime({ apiKey: 'lim_test_key' }); try { await allocateLimrunDevice(runtime, androidLease()); await Promise.all([ - runtime.configurePortReverse({ + runtime.configurePortReverse?.({ leaseId: 'lease-android', devicePort: 8081, hostPort: 8081, name: 'metro', }), - runtime.configurePortReverse({ + runtime.configurePortReverse?.({ leaseId: 'lease-android', devicePort: 8097, hostPort: 8097, @@ -527,19 +505,10 @@ test('Limrun iOS syncs direct local artifacts', async () => { const tempRoot = mkdtempForTestSync('agent-device-limrun-install-'); const ipaPath = path.join(tempRoot, 'Demo.ipa'); fs.writeFileSync(ipaPath, 'demo'); - const runtime = new LimrunRuntime({ + const runtime = createTestRuntime({ apiKey: 'lim_test_key', }); - const lease: DeviceLease = { - leaseId: 'lease-ios', - tenantId: 'team-a', - runId: 'run-a', - backend: 'ios-instance', - leaseProvider: 'limrun', - createdAt: 1, - heartbeatAt: 1, - expiresAt: 60_001, - }; + const lease = iosLease('lease-ios'); try { const allocateLease = runtime.leaseLifecycle.allocate; @@ -550,12 +519,9 @@ test('Limrun iOS syncs direct local artifacts', async () => { throw new Error('Limrun runtime must return allocated device metadata'); } - const result = await runtime.installApp( - device as Parameters[0], - 'com.example.ios', - ipaPath, - { relaunch: true }, - ); + const result = await runtime.installApp?.(device as DeviceInfo, 'com.example.ios', ipaPath, { + relaunch: true, + }); assert.equal(limrunMockState.iosInstallApp.mock.calls.length, 0); expect(limrunMockState.iosSyncApp).toHaveBeenCalledWith(ipaPath, { @@ -588,7 +554,7 @@ test('Limrun iOS reads the bundle display name before syncing an app bundle', as '', ].join(''), ); - const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' }); + const runtime = createTestRuntime({ apiKey: 'lim_test_key' }); try { const device = await allocateLimrunDevice(runtime, { @@ -596,11 +562,7 @@ test('Limrun iOS reads the bundle display name before syncing an app bundle', as leaseId: 'lease-ios-app-name', backend: 'ios-instance', }); - const result = await runtime.installApp( - device as Parameters[0], - 'com.example.ios', - appPath, - ); + const result = await runtime.installApp?.(device as DeviceInfo, 'com.example.ios', appPath); assert.equal(result?.appName, 'Actual App Name'); } finally { @@ -610,19 +572,10 @@ test('Limrun iOS reads the bundle display name before syncing an app bundle', as }); test('Limrun Android configures an explicit port reverse', async () => { - const runtime = new LimrunRuntime({ + const runtime = createTestRuntime({ apiKey: 'lim_test_key', }); - const lease: DeviceLease = { - leaseId: 'lease-android', - tenantId: 'team-a', - runId: 'run-a', - backend: 'android-instance', - leaseProvider: 'limrun', - createdAt: 1, - heartbeatAt: 1, - expiresAt: 60_001, - }; + const lease = androidLease(); try { const allocateLease = runtime.leaseLifecycle.allocate; @@ -630,7 +583,7 @@ test('Limrun Android configures an explicit port reverse', async () => { await allocateLease(lease); assert.deepEqual( - await runtime.configurePortReverse({ + await runtime.configurePortReverse?.({ leaseId: lease.leaseId, devicePort: 8097, hostPort: 8097, @@ -656,7 +609,7 @@ test('Limrun Android configures an explicit port reverse', async () => { }); test('Limrun Android preserves canonical ADB failure classification', async () => { - const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' }); + const runtime = createTestRuntime({ apiKey: 'lim_test_key' }); try { await allocateLimrunDevice(runtime, androidLease()); @@ -667,13 +620,14 @@ test('Limrun Android preserves canonical ADB failure classification', async () = }); await assert.rejects( - () => - runtime.configurePortReverse({ + async () => { + await runtime.configurePortReverse?.({ leaseId: 'lease-android', devicePort: 8097, hostPort: 8097, name: 'react-devtools', - }), + }); + }, (error) => typeof error === 'object' && error !== null && @@ -691,19 +645,10 @@ test('Limrun deletes iOS instance when post-create validation fails', async () = metadata: { id: 'ios-instance-missing-api' }, status: { token: 'instance-token' }, } as never); - const runtime = new LimrunRuntime({ + const runtime = createTestRuntime({ apiKey: 'lim_test_key', }); - const lease: DeviceLease = { - leaseId: 'lease-ios', - tenantId: 'team-a', - runId: 'run-a', - backend: 'ios-instance', - leaseProvider: 'limrun', - createdAt: 1, - heartbeatAt: 1, - expiresAt: 60_001, - }; + const lease = iosLease('lease-ios'); try { const allocateLease = runtime.leaseLifecycle.allocate; @@ -723,19 +668,10 @@ test('Limrun deletes Android instance when post-create validation fails', async apiUrl: 'https://android.example', }, } as never); - const runtime = new LimrunRuntime({ + const runtime = createTestRuntime({ apiKey: 'lim_test_key', }); - const lease: DeviceLease = { - leaseId: 'lease-android', - tenantId: 'team-a', - runId: 'run-a', - backend: 'android-instance', - leaseProvider: 'limrun', - createdAt: 1, - heartbeatAt: 1, - expiresAt: 60_001, - }; + const lease = androidLease(); try { const allocateLease = runtime.leaseLifecycle.allocate; @@ -748,19 +684,10 @@ test('Limrun deletes Android instance when post-create validation fails', async }); test('Limrun keeps session tracked when release fails so release can be retried', async () => { - const runtime = new LimrunRuntime({ + const runtime = createTestRuntime({ apiKey: 'lim_test_key', }); - const lease: DeviceLease = { - leaseId: 'lease-android', - tenantId: 'team-a', - runId: 'run-a', - backend: 'android-instance', - leaseProvider: 'limrun', - createdAt: 1, - heartbeatAt: 1, - expiresAt: 60_001, - }; + const lease = androidLease(); try { const allocateLease = runtime.leaseLifecycle.allocate; @@ -800,12 +727,8 @@ const ATTACHED_ANDROID = { adbUrl: 'wss://region.limrun.example/v1/android_attached/adb', }; -function iosLease(leaseId: string): DeviceLease { - return { ...androidLease(), leaseId, backend: 'ios-instance' }; -} - test('Limrun drives existing instances without an API key and never deletes them', async () => { - const runtime = new LimrunRuntime({ + const runtime = createTestRuntime({ instances: { ios: ATTACHED_IOS, android: ATTACHED_ANDROID }, }); const releaseLease = runtime.leaseLifecycle.release; @@ -845,7 +768,7 @@ test('Limrun drives existing instances without an API key and never deletes them }); test('Limrun removes only its own port reverse mappings from an attached Android instance', async () => { - const runtime = new LimrunRuntime({ instances: { android: ATTACHED_ANDROID } }); + const runtime = createTestRuntime({ instances: { android: ATTACHED_ANDROID } }); const lease = { ...androidLease(), leaseId: 'lease-attached-android' }; vi.mocked(runCmd).mockImplementation(async (_command, args) => ({ stdout: args.includes('--list') @@ -856,7 +779,7 @@ test('Limrun removes only its own port reverse mappings from an attached Android })); const device = await allocateLimrunDevice(runtime, lease); - await runtime.configurePortReverse({ + await runtime.configurePortReverse?.({ leaseId: lease.leaseId, devicePort: 8097, hostPort: 8097, @@ -875,7 +798,7 @@ test('Limrun removes only its own port reverse mappings from an attached Android }); test('Limrun refuses to replace an owner port reverse on an attached Android instance', async () => { - const runtime = new LimrunRuntime({ instances: { android: ATTACHED_ANDROID } }); + const runtime = createTestRuntime({ instances: { android: ATTACHED_ANDROID } }); const lease = { ...androidLease(), leaseId: 'lease-attached-android' }; vi.mocked(runCmd).mockImplementation(async (_command, args) => args.includes('--no-rebind') @@ -891,16 +814,14 @@ test('Limrun refuses to replace an owner port reverse on an attached Android ins 'android_port_reverse_rebind_refused'; const device = await allocateLimrunDevice(runtime, lease); - await assert.rejects( - () => - runtime.configurePortReverse({ - leaseId: lease.leaseId, - devicePort: 8081, - hostPort: 8081, - name: 'metro', - }), - isRebindRefusal, - ); + await assert.rejects(async () => { + await runtime.configurePortReverse?.({ + leaseId: lease.leaseId, + devicePort: 8081, + hostPort: 8081, + name: 'metro', + }); + }, isRebindRefusal); const interactor = runtime.getInteractor(device); if (!interactor) throw new Error('Limrun runtime must return an interactor'); await assert.rejects(() => interactor.open('exp://127.0.0.1:8081'), isRebindRefusal); @@ -917,7 +838,7 @@ test('Limrun refuses to replace an owner port reverse on an attached Android ins }); test('Limrun instance access wins over the API key for its platform only', async () => { - const runtime = new LimrunRuntime({ apiKey: 'lim_test_key', instances: { ios: ATTACHED_IOS } }); + const runtime = createTestRuntime({ apiKey: 'lim_test_key', instances: { ios: ATTACHED_IOS } }); await allocateLimrunDevice(runtime, iosLease('lease-attached-ios')); await allocateLimrunDevice(runtime, androidLease()); @@ -933,7 +854,7 @@ test('Limrun instance access wins over the API key for its platform only', async }); test('Limrun without an API key refuses operations that need one', async () => { - const runtime = new LimrunRuntime({ instances: { ios: ATTACHED_IOS } }); + const runtime = createTestRuntime({ instances: { ios: ATTACHED_IOS } }); try { await assert.rejects(allocateLimrunDevice(runtime, androidLease()), { @@ -943,11 +864,11 @@ test('Limrun without an API key refuses operations that need one', async () => { } finally { await runtime.shutdown(); } - assert.throws(() => new LimrunRuntime({}), /requires an apiKey or instance access/); + assert.throws(() => createTestRuntime({}), /requires an apiKey or instance access/); }); test('Limrun attaches an existing instance under a consumed field and refuses a refused one', async () => { - const runtime = new LimrunRuntime({ instances: { ios: ATTACHED_IOS } }); + const runtime = createTestRuntime({ instances: { ios: ATTACHED_IOS } }); const allocateLease = runtime.leaseLifecycle.allocate; if (!allocateLease) throw new Error('Limrun runtime must provide lease allocation'); try { @@ -964,3 +885,32 @@ test('Limrun attaches an existing instance under a consumed field and refuses a await runtime.shutdown(); } }); + +test('Limrun runtimes keep their hosts in concurrent deferred Android callbacks', async () => { + const host = (owner: string) => ({ env: { SDK_OWNER: owner }, cwd: process.cwd() }); + const runtimes = ['first', 'second'].map((owner) => + createTestRuntime({ apiKey: 'lim_test_key' }, host(owner)), + ); + vi.mocked(runCmd).mockImplementation(async () => ({ + stdout: `mCurrentFocus=Window{1 u0 com.${commandHostEnvironment().env.SDK_OWNER}/.MainActivity}`, + stderr: '', + exitCode: 0, + })); + try { + const sessions = await Promise.all( + runtimes.map(async (runtime) => { + const device = await allocateLimrunDevice(runtime, androidLease()); + const session = runtime.getDeviceSession(device); + assert.ok(session?.platform === 'android'); + return session; + }), + ); + const results = await withCommandHost( + { host: host('foreign'), requestEnv: { SDK_OWNER: 'request' } }, + () => Promise.all(sessions.map((session) => session.getForegroundApp())), + ); + expect(results.map((app) => app?.appId)).toEqual(['com.first', 'com.second']); + } finally { + await Promise.all(runtimes.map((runtime) => runtime.shutdown())); + } +}); diff --git a/src/__tests__/platform-runtime-runtime-hints.test.ts b/src/__tests__/platform-runtime-runtime-hints.test.ts index 3a3277b7eb..b3be1c373c 100644 --- a/src/__tests__/platform-runtime-runtime-hints.test.ts +++ b/src/__tests__/platform-runtime-runtime-hints.test.ts @@ -4,7 +4,9 @@ import assert from 'node:assert/strict'; import { promises as fs } from 'node:fs'; import { AppError } from '@agent-device/kernel/errors'; import { + applyAppleRuntimeHintValues, applyRuntimeHintValues, + clearAppleRuntimeHintValues, clearRuntimeHintValues, } from '../platform-runtime-runtime-hints.ts'; import { resolveRuntimeTransportHints } from '@agent-device/host-kit/runtime-transport-hints'; @@ -401,6 +403,50 @@ test('applyRuntimeHintValues writes iOS simulator React Native defaults', async }); }); +test('the Apple hint path refuses an Android device instead of writing Android preferences', async () => { + await withMockedAdb(async ({ device, argsLogPath }) => { + await assert.rejects( + applyAppleRuntimeHintValues({ + device, + appId: 'com.example.demo', + values: { metroHost: '10.0.0.10', metroPort: '8081' }, + }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + assert.equal(error.details?.reason, 'apple_runtime_hint_target_required'); + return true; + }, + ); + // Refusal means no ADB call: an Apple-scoped grant cannot reach the device shell at all. + await assert.rejects( + fs.readFile(argsLogPath, 'utf8'), + (error: unknown) => (error as NodeJS.ErrnoException).code === 'ENOENT', + ); + }); +}); + +test('the Apple hint path writes the same simulator defaults as the dispatcher', async () => { + await withMockedXcrun(async ({ device, argsLogPath }) => { + await applyAppleRuntimeHintValues({ + device, + appId: 'com.example.demo', + values: { metroHost: '127.0.0.1', metroPort: '8081' }, + }); + await clearAppleRuntimeHintValues({ device, appId: 'com.example.demo' }); + + const loggedArgs = await fs.readFile(argsLogPath, 'utf8'); + assert.match( + loggedArgs, + /simctl spawn sim-1 defaults write com\.example\.demo RCT_jsLocation -string 127\.0\.0\.1:8081/, + ); + assert.match( + loggedArgs, + /simctl spawn sim-1 defaults delete com\.example\.demo RCT_jsLocation/, + ); + }); +}); + test('clearRuntimeHintValues deletes iOS simulator React Native defaults', async () => { await withMockedXcrun(async ({ device, argsLogPath }) => { await clearRuntimeHintValues({ diff --git a/src/__tests__/provider-device-runtimes.test.ts b/src/__tests__/provider-device-runtimes.test.ts index 0b15653879..04713372d4 100644 --- a/src/__tests__/provider-device-runtimes.test.ts +++ b/src/__tests__/provider-device-runtimes.test.ts @@ -3,16 +3,11 @@ import { test } from 'vitest'; import { createDaemonProviderRuntimeComposition } from '../provider-device-runtimes.ts'; import fs from 'node:fs'; import path from 'node:path'; -import { - pluginHome, - registrationSource, - selectPlugin, - selectV2Plugin, -} from '@agent-device/test-kit'; +import { pluginHome, selectV2Plugin, v2RegistrationSource } from '@agent-device/test-kit'; test('daemon composition registers installed provider runtimes and their lazy platform modules', async () => { const { home, env } = pluginHome(); - selectPlugin(home, 'example', 'example', registrationSource('example')); + selectV2Plugin(home, 'example', v2RegistrationSource('example')); const composition = await createDaemonProviderRuntimeComposition({ env: env, cwd: process.cwd(), @@ -26,9 +21,9 @@ test('daemon composition registers installed provider runtimes and their lazy pl await composition.shutdown(); }); -test('built-in providers register ahead of the store and an unconfigured Limrun still claims its id', async () => { +test('an unconfigured Limrun stays dormant while the store provider registers', async () => { const { home, env } = pluginHome(); - selectPlugin(home, 'example', 'example', registrationSource('example')); + selectV2Plugin(home, 'example', v2RegistrationSource('example')); const composition = await createDaemonProviderRuntimeComposition({ env: env, cwd: process.cwd(), @@ -36,22 +31,18 @@ test('built-in providers register ahead of the store and an unconfigured Limrun assert.deepEqual( composition.runtimes.map((runtime) => runtime.provider), - ['browserstack', 'aws-device-farm', 'example'], + ['example'], ); assert.deepEqual( composition.inventory.map(({ provider, source, state }) => [provider, source, state]), - [ - ['browserstack', 'builtin', 'active'], - ['aws-device-farm', 'builtin', 'active'], - ['example', 'store', 'active'], - ], + [['example', 'store', 'active']], ); await composition.shutdown(); }); test('daemon composition records Limrun as failed for a partial instance set and still loads every other provider', async () => { const { home, env } = pluginHome(); - selectPlugin(home, 'example', 'example', registrationSource('example')); + selectV2Plugin(home, 'example', v2RegistrationSource('example')); const composition = await createDaemonProviderRuntimeComposition({ env: { ...env, @@ -64,7 +55,7 @@ test('daemon composition records Limrun as failed for a partial instance set and assert.deepEqual( composition.runtimes.map((runtime) => runtime.provider), - ['browserstack', 'aws-device-farm', 'example'], + ['example'], ); const limrun = composition.inventory.find(({ provider }) => provider === 'limrun'); assert.equal(limrun?.state, 'failed'); @@ -74,9 +65,9 @@ test('daemon composition records Limrun as failed for a partial instance set and }); test('a plugin claiming a built-in provider ID is recorded as failed and the built-in keeps the ID', async () => { - for (const provider of ['limrun', 'browserstack', 'aws-device-farm']) { + for (const provider of ['limrun']) { const { home, env } = pluginHome(); - selectPlugin(home, 'example', provider, 'throw new Error("must not evaluate");'); + selectV2Plugin(home, 'example', v2RegistrationSource(provider)); const composition = await createDaemonProviderRuntimeComposition({ env: env, cwd: process.cwd(), @@ -85,10 +76,56 @@ test('a plugin claiming a built-in provider ID is recorded as failed and the bui assert.equal(plugin?.state, 'failed'); assert.equal(plugin?.error?.reason, 'duplicate_provider'); // An unconfigured Limrun claims its id without registering a runtime. - assert.equal( - composition.runtimes.filter((runtime) => runtime.provider === provider).length, - provider === 'limrun' ? 0 : 1, - ); + assert.equal(composition.runtimes.filter((runtime) => runtime.provider === provider).length, 0); + await composition.shutdown(); + } +}); + +test('BrowserStack registers as an ordinary store plugin, not a built-in', async () => { + const { home, env } = pluginHome(); + selectV2Plugin(home, '@agent-device/browserstack', v2RegistrationSource('browserstack')); + const composition = await createDaemonProviderRuntimeComposition({ + env: env, + cwd: process.cwd(), + }); + + assert.deepEqual( + composition.inventory + .filter(({ provider }) => provider === 'browserstack') + .map(({ provider, source, state, package: name }) => [provider, source, state, name]), + [['browserstack', 'store', 'active', '@agent-device/browserstack']], + ); + await composition.shutdown(); +}); + +test('AWS Device Farm registers as an ordinary store plugin, not a built-in', async () => { + const { home, env } = pluginHome(); + selectV2Plugin(home, '@agent-device/aws-device-farm', v2RegistrationSource('aws-device-farm')); + const composition = await createDaemonProviderRuntimeComposition({ + env: env, + cwd: process.cwd(), + }); + + assert.deepEqual( + composition.inventory + .filter(({ provider }) => provider === 'aws-device-farm') + .map(({ provider, source, state, package: name }) => [provider, source, state, name]), + [['aws-device-farm', 'store', 'active', '@agent-device/aws-device-farm']], + ); + await composition.shutdown(); +}); + +test('a plugin claiming a routing identity is refused before the registry settles claims', async () => { + for (const provider of ['cloud', 'proxy']) { + const { home, env } = pluginHome(); + selectV2Plugin(home, 'example', v2RegistrationSource(provider)); + const composition = await createDaemonProviderRuntimeComposition({ + env: env, + cwd: process.cwd(), + }); + const plugin = composition.inventory.find(({ package: name }) => name === 'example'); + assert.equal(plugin?.state, 'failed'); + assert.equal(plugin?.error?.reason, 'reserved_provider'); await composition.shutdown(); } }); diff --git a/src/__tests__/remote-connection-proxy-lease-id.test.ts b/src/__tests__/remote-connection-proxy-lease-id.test.ts index ac4386ad0b..f0a7c59d8e 100644 --- a/src/__tests__/remote-connection-proxy-lease-id.test.ts +++ b/src/__tests__/remote-connection-proxy-lease-id.test.ts @@ -1,4 +1,4 @@ -import { bindTestCommandHost, createTestHostEnvironment } from '@agent-device/test-kit'; +import { bindTestCommandHost, createTestHostEnvironment, pluginHome } from '@agent-device/test-kit'; import { test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; @@ -16,6 +16,7 @@ vi.mock('@agent-device/react-native', async (importOriginal) => ({ })); import { materializeRemoteConnectionForCommand } from '../cli/commands/connection-runtime.ts'; +import { selectAwsDeviceFarmPlugin } from './test-utils/aws-device-farm-plugin-inventory.ts'; import { readRemoteConnectionState } from '@agent-device/remote/remote-connection-state'; bindTestCommandHost(); @@ -110,6 +111,8 @@ test('proxy allocation sends a fresh lease id on every attempt and keeps the id }); test('a non-proxy remote connection leaves the lease id to the daemon', async () => { + const { home, env } = pluginHome(); + selectAwsDeviceFarmPlugin(home); const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( 'agent-device-cloud-lease-id-', ); @@ -128,7 +131,7 @@ test('a non-proxy remote connection leaves the lease id to the daemon', async () const requests: LeaseAllocateRequest[] = []; const materialized = await materializeRemoteConnectionForCommand({ - host: createTestHostEnvironment(), + host: createTestHostEnvironment({ env }), command: 'screenshot', flags: { json: true, diff --git a/src/__tests__/remote-connection.test.ts b/src/__tests__/remote-connection.test.ts index 9f9bda97b0..301e6f80e1 100644 --- a/src/__tests__/remote-connection.test.ts +++ b/src/__tests__/remote-connection.test.ts @@ -1,6 +1,6 @@ import { afterEach, test, vi } from 'vitest'; import assert from 'node:assert/strict'; -import { withCapturedStdoutAsync } from '@agent-device/test-kit'; +import { withCapturedStdoutAsync, pluginHome } from '@agent-device/test-kit'; import fs from 'node:fs'; import path from 'node:path'; import { @@ -32,6 +32,7 @@ import { REMOTE_LEASE_IDLE_TTL_MS } from '@agent-device/contracts/lease-scope'; import { hasDeferredMetroConfig } from '../cli/commands/connection-metro-runtime.ts'; import { stopMetroTunnel } from '@agent-device/react-native'; import { AppError } from '@agent-device/kernel/errors'; +import { selectAwsDeviceFarmPlugin } from './test-utils/aws-device-farm-plugin-inventory.ts'; import { hashRemoteConfigFile, readActiveConnectionState, @@ -298,7 +299,7 @@ test('connect proxy rejects remote-config and unknown provider combinations', as }, client: createTestClient(), }), - /Supported providers: cloud, proxy, browserstack, aws-device-farm/, + /Supported providers: cloud, proxy, limrun/, ); fs.rmSync(tempRoot, { recursive: true, force: true }); }); @@ -692,6 +693,9 @@ test.each(['install', 'uninstall'])('proxy %s allocates a lease first', async (c }); test('artifacts command reuses the stored cloud lease without allocating', async () => { + const { home } = pluginHome(); + selectAwsDeviceFarmPlugin(home); + vi.stubEnv('AGENT_DEVICE_HOME', home); const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( 'agent-device-connect-cloud-artifacts-', ); @@ -737,6 +741,11 @@ test('cloud webdriver connection allocates and heartbeats with extended lease TT const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( 'agent-device-connect-cloud-ttl-', ); + // The AWS Device Farm capabilities a plugin declares are what earn the extended TTL, so the + // store declares them here the way the installed package does. + const { home } = pluginHome(); + selectAwsDeviceFarmPlugin(home); + vi.stubEnv('AGENT_DEVICE_HOME', home); fs.writeFileSync(remoteConfigPath, JSON.stringify({})); seedConnectionState({ stateDir, @@ -1321,74 +1330,6 @@ test('deferred materialization allocates pending lease for devices', async () => fs.rmSync(tempRoot, { recursive: true, force: true }); }); -test('deferred provider materialization forwards provider profile fields to lease allocation', async () => { - const { tempRoot, stateDir } = connectionWorkspace('agent-device-provider-lease-flags-'); - const remoteConfigPath = path.join(tempRoot, 'browserstack.json'); - fs.writeFileSync( - remoteConfigPath, - JSON.stringify({ - tenant: 'browserstack', - runId: 'browserstack-run', - leaseProvider: 'browserstack', - leaseBackend: 'android-instance', - platform: 'android', - device: 'Google Pixel 8', - providerOsVersion: '14.0', - providerApp: '/tmp/WikipediaSample.apk', - providerProject: 'agent-device', - providerBuild: 'live-smoke', - }), - ); - seedConnectionState({ - stateDir, - state: { - session: 'adc-browserstack', - remoteConfigPath, - tenant: 'browserstack', - runId: 'browserstack-run', - leaseBackend: 'android-instance', - leaseProvider: 'browserstack', - platform: 'android', - }, - }); - const allocate = recordedLeaseAllocate({ - leaseId: 'lease-browserstack', - backend: 'android-instance', - }); - - const materialized = await materializeRemoteConnectionForCommand({ - command: 'open', - flags: { - json: true, - help: false, - version: false, - stateDir, - remoteConfig: remoteConfigPath, - tenant: 'browserstack', - runId: 'browserstack-run', - session: 'adc-browserstack', - leaseBackend: 'android-instance', - platform: 'android', - device: 'Google Pixel 8', - providerOsVersion: '14.0', - providerApp: '/tmp/WikipediaSample.apk', - providerProject: 'agent-device', - providerBuild: 'live-smoke', - }, - client: createTestClient({ allocate: allocate.stub }), - }); - - assert.equal(materialized.flags.leaseId, 'lease-browserstack'); - assert.equal(allocate.request?.platform, 'android'); - assert.equal(allocate.request?.device, 'Google Pixel 8'); - assert.equal(allocate.request?.providerApp, '/tmp/WikipediaSample.apk'); - assert.equal(allocate.request?.providerOsVersion, '14.0'); - assert.equal(allocate.request?.providerProject, 'agent-device'); - assert.equal(allocate.request?.providerBuild, 'live-smoke'); - - fs.rmSync(tempRoot, { recursive: true, force: true }); -}); - test('deferred materialization reallocates when the persisted lease is inactive', async () => { const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( 'agent-device-connect-stale-lease-', diff --git a/src/__tests__/replay-plugin-setup.ts b/src/__tests__/replay-plugin-setup.ts new file mode 100644 index 0000000000..b17fda0184 --- /dev/null +++ b/src/__tests__/replay-plugin-setup.ts @@ -0,0 +1,34 @@ +import { afterEach, beforeEach, vi } from 'vitest'; + +let registry: Awaited< + ReturnType +>; +beforeEach(async () => { + const [ + { bindReplayBackendResolver }, + { resolveProviderPlugins, startProviderRegistry }, + { storePluginCandidates }, + ] = await Promise.all([ + vi.importActual( + '@agent-device/replay-port/replay-backend-registry', + ), + vi.importActual( + '@agent-device/plugins/registry', + ), + vi.importActual('@agent-device/plugins/store'), + ]); + registry = await startProviderRegistry( + await resolveProviderPlugins(await storePluginCandidates(process.env)), + { env: process.env, cwd: process.cwd() }, + { + adaptWebDriver: async () => { + throw new Error('Replay test setup cannot start providers'); + }, + }, + 'replay-backends', + ); + await bindReplayBackendResolver(registry.resolveReplayBackend, registry.resolveReplayExecution); +}); +afterEach(async () => { + await registry?.close(); +}); diff --git a/src/__tests__/test-utils/aws-device-farm-plugin-inventory.ts b/src/__tests__/test-utils/aws-device-farm-plugin-inventory.ts new file mode 100644 index 0000000000..7b123878a9 --- /dev/null +++ b/src/__tests__/test-utils/aws-device-farm-plugin-inventory.ts @@ -0,0 +1,35 @@ +import type { PluginInventoryEntry } from '@agent-device/contracts/plugin-inventory'; +import type { PluginCandidate } from '@agent-device/plugins/registry'; +import { resolveProviderPlugins } from '@agent-device/plugins/registry'; +import { selectV2Plugin, v2RegistrationSource } from '@agent-device/test-kit'; +import awsDeviceFarm from '@agent-device/aws-device-farm'; +import manifest from '@agent-device/aws-device-farm/package.json' with { type: 'json' }; + +/** The AWS Device Farm package as an installed store plugin, without touching the on-disk store. */ +function awsDeviceFarmPluginCandidate(): PluginCandidate { + return { + source: 'store', + package: manifest.name as string, + load: async () => (await import('@agent-device/aws-device-farm')).default(), + }; +} + +/** The inventory one installed AWS Device Farm plugin produces, the way the daemon reads it. */ +export async function awsDeviceFarmPluginInventory(): Promise { + const resolved = await resolveProviderPlugins([awsDeviceFarmPluginCandidate()]); + return resolved.inventory(); +} + +/** + * Declares the plugin installed in a store home, with the capabilities of the real package and a + * stub connection, so capability readers that prime the store see what an installed plugin declares. + */ +export function selectAwsDeviceFarmPlugin(home: string): void { + selectV2Plugin( + home, + manifest.name, + v2RegistrationSource('aws-device-farm', { + extra: `connection: { capabilities: ${JSON.stringify(awsDeviceFarm().connection?.capabilities)}, resolve() {}, verify() {} },`, + }), + ); +} diff --git a/src/__tests__/test-utils/browserstack-plugin-inventory.ts b/src/__tests__/test-utils/browserstack-plugin-inventory.ts new file mode 100644 index 0000000000..3201005373 --- /dev/null +++ b/src/__tests__/test-utils/browserstack-plugin-inventory.ts @@ -0,0 +1,19 @@ +import type { PluginInventoryEntry } from '@agent-device/contracts/plugin-inventory'; +import type { PluginCandidate } from '@agent-device/plugins/registry'; +import { resolveProviderPlugins } from '@agent-device/plugins/registry'; +import manifest from '@agent-device/browserstack/package.json' with { type: 'json' }; + +/** The BrowserStack package as an installed store plugin, without touching the on-disk store. */ +function browserstackPluginCandidate(): PluginCandidate { + return { + source: 'store', + package: manifest.name as string, + load: async () => (await import('@agent-device/browserstack')).default(), + }; +} + +/** The inventory one installed BrowserStack plugin produces, the way the daemon reads it. */ +export async function browserstackPluginInventory(): Promise { + const resolved = await resolveProviderPlugins([browserstackPluginCandidate()]); + return resolved.inventory(); +} diff --git a/src/__tests__/test-utils/replay-script-source.fixtures.ts b/src/__tests__/test-utils/replay-script-source.fixtures.ts index 322419ca41..cbd10585fe 100644 --- a/src/__tests__/test-utils/replay-script-source.fixtures.ts +++ b/src/__tests__/test-utils/replay-script-source.fixtures.ts @@ -26,6 +26,7 @@ export async function withClientReplayScriptSources( if (req.command === 'replay') { if (req.flags?.replayScriptSource) return req; const replayScriptSource = await loadReplayScriptSourceBundle({ + hostEnv: process.env, inputPath: inputs[0], cwd, replayBackend, @@ -35,7 +36,13 @@ export async function withClientReplayScriptSources( if (req.flags?.replayScriptSources) return req; const replayScriptSources = await Promise.all( discoverReplaySourcePaths({ inputs, cwd, replayBackend }).map( - async (inputPath) => await loadReplayScriptSourceBundle({ inputPath, cwd, replayBackend }), + async (inputPath) => + await loadReplayScriptSourceBundle({ + hostEnv: process.env, + inputPath, + cwd, + replayBackend, + }), ), ); return withFlags({ replayScriptSources }); diff --git a/src/builtin-provider-ids.ts b/src/builtin-provider-ids.ts index b2e542a59e..6216c7010a 100644 --- a/src/builtin-provider-ids.ts +++ b/src/builtin-provider-ids.ts @@ -1,6 +1,5 @@ import type { ConnectionProviderCapabilities } from '@agent-device/contracts/remote'; -import { ROUTING_PROVIDER_IDENTITIES } from '@agent-device/plugins/manifest'; -import { CLOUD_WEBDRIVER_PROVIDER_DECLARATIONS } from '@agent-device/provider-webdriver/providers'; +import { ROUTING_PROVIDER_IDENTITIES } from '@agent-device/plugins/contract'; export const LIMRUN_ID = 'limrun'; @@ -17,10 +16,7 @@ const LIMRUN_CONNECTION: ConnectionProviderCapabilities = { }; /** Every provider id agent-device registers itself; a plugin cannot claim any of them. */ -export const BUILTIN_PROVIDER_IDS: readonly string[] = [ - ...CLOUD_WEBDRIVER_PROVIDER_DECLARATIONS.map(({ provider }) => provider), - LIMRUN_ID, -]; +export const BUILTIN_PROVIDER_IDS: readonly string[] = [LIMRUN_ID]; /** Provider ids `connect` accepts without a plugin: the routing identities and the built-ins. */ export const BUILTIN_CONNECT_PROVIDER_IDS: readonly string[] = [ @@ -32,8 +28,5 @@ export const BUILTIN_CONNECT_PROVIDER_IDS: readonly string[] = [ export function builtinConnectionCapabilities( provider: string | undefined, ): ConnectionProviderCapabilities | undefined { - if (provider === LIMRUN_ID) return LIMRUN_CONNECTION; - return CLOUD_WEBDRIVER_PROVIDER_DECLARATIONS.find( - (declaration) => declaration.provider === provider, - )?.connection; + return provider === LIMRUN_ID ? LIMRUN_CONNECTION : undefined; } diff --git a/src/builtin-provider-plugins.ts b/src/builtin-provider-plugins.ts index 52708c2b72..d64bd8c402 100644 --- a/src/builtin-provider-plugins.ts +++ b/src/builtin-provider-plugins.ts @@ -1,9 +1,5 @@ import type { AgentDevicePlugin } from '@agent-device/plugins/contract'; import type { PluginCandidate } from '@agent-device/plugins/registry'; -import { - CLOUD_WEBDRIVER_PROVIDER_DECLARATIONS, - type CloudWebDriverProviderDeclaration, -} from '@agent-device/provider-webdriver/providers'; import { LIMRUN_ID } from './builtin-provider-ids.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import path from 'node:path'; @@ -20,50 +16,7 @@ import { * registering until the environment holds it. */ export function builtinProviderCandidates(host: HostEnvironment): PluginCandidate[] { - return [ - ...CLOUD_WEBDRIVER_PROVIDER_DECLARATIONS.map((declaration): PluginCandidate => ({ - source: 'builtin', - provider: declaration.provider, - load: () => cloudWebDriverPlugin(declaration), - })), - limrunCandidate(host), - ]; -} - -function cloudWebDriverPlugin(declaration: CloudWebDriverProviderDeclaration): AgentDevicePlugin { - const loadProvider = async () => { - const [{ bundledCloudWebDriverProvider }, host] = await Promise.all([ - import('@agent-device/provider-webdriver'), - import('./provider-webdriver.ts'), - ]); - return { bundled: bundledCloudWebDriverProvider(declaration.provider)!, host }; - }; - return { - apiVersion: 2, - provider: declaration.provider, - credentials: { variables: declaration.credentialVariables ?? [] }, - connection: { - capabilities: declaration.connection, - resolve: async (context) => { - const { bundled, host } = await loadProvider(); - return await bundled - .create(host.createBundledCloudWebDriverHost(context.env)) - .connection.resolve(context); - }, - verify: async (context) => { - const { bundled, host } = await loadProvider(); - return await bundled - .create(host.createBundledCloudWebDriverHost(context.env)) - .connection.verify(context); - }, - }, - setup: async (pluginHost) => { - const { bundled, host } = await loadProvider(); - return { - webDriver: bundled.create(host.createBundledCloudWebDriverHost(pluginHost.env)).webDriver, - }; - }, - }; + return [limrunCandidate(host)]; } function limrunCandidate(host: HostEnvironment): PluginCandidate { diff --git a/src/cli.ts b/src/cli.ts index d5e11c386b..37a5b0b85a 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -51,8 +51,8 @@ import { } from '@agent-device/host-kit/diagnostics'; import { resolveCliOptions } from './cli/resolve-cli-options.ts'; import { maybeRunUpgradeNotifier } from './cli/update-check.ts'; +import { remoteSessionRequiredError } from '@agent-device/contracts/lease-scope'; import { - remoteSessionRequiredError, resolveRemoteConnectionDefaults, type RemoteConnectionRequestMetadata, } from '@agent-device/remote/remote-connection-state'; diff --git a/src/cli/commands/__tests__/connection-revyl.test.ts b/src/cli/commands/__tests__/connection-revyl.test.ts index ba9a563eaf..45330a3d7a 100644 --- a/src/cli/commands/__tests__/connection-revyl.test.ts +++ b/src/cli/commands/__tests__/connection-revyl.test.ts @@ -4,7 +4,12 @@ import http from 'node:http'; import type { AddressInfo } from 'node:net'; import path from 'node:path'; import { afterEach, beforeEach, test, vi } from 'vitest'; -import { mkdtempForTestSync, pluginHome, selectPlugin } from '@agent-device/test-kit'; +import { + mkdtempForTestSync, + pluginHome, + selectV2Plugin, + v2RegistrationSource, +} from '@agent-device/test-kit'; import type { CliFlags } from '@agent-device/contracts/command'; import { AppError } from '@agent-device/kernel/errors'; import { readActiveConnectionState } from '@agent-device/remote/remote-connection-state'; @@ -15,9 +20,9 @@ import manifest from '@agent-device/revyl/package.json' with { type: 'json' }; import { resolveConnectProviderProfile } from '../../connection/connect-provider-adapters.ts'; import { connectWithGeneratedProviderProfile } from '../../../__tests__/test-utils/connect-command.ts'; -// Mirrors src/__tests__/cloud-connect-testmu.test.ts: the plugin store is told the Revyl plugin is -// installed and its connection callbacks are loaded from the workspace source, so the assertions read -// the HTTP the plugin really sends rather than a mock of it. +// Mirrors src/__tests__/cloud-connect-testmu.test.ts: the store declares the Revyl plugin installed +// and its connection callbacks are loaded from the workspace source, so the assertions read the HTTP +// the plugin really sends rather than a mock of it. const mockedWithPluginConnection = vi.hoisted(() => vi.fn()); vi.mock('@agent-device/plugins/load', () => ({ @@ -81,20 +86,16 @@ afterEach(async () => { beforeEach(() => { const { home } = pluginHome(); - selectPlugin(home, manifest.name, 'revyl', 'export default () => {};'); - const { installation } = JSON.parse(fs.readFileSync(path.join(home, 'config.json'), 'utf8')) - .plugins[manifest.name]; - const manifestPath = path.join( + // The store declares the plugin installed with Revyl's capabilities; the mocked loader below + // supplies the workspace factory those assertions exercise. + selectV2Plugin( home, - 'plugins', - installation, - 'node_modules', manifest.name, - 'package.json', + v2RegistrationSource('revyl', { + extra: `connection: { capabilities: ${JSON.stringify(revyl().connection?.capabilities)}, resolve() {}, verify() {} },`, + credentials: '{ variables: ["REVYL_API_KEY"] }', + }), ); - const declared = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); - declared.agentDevicePlugin.connection = manifest.agentDevicePlugin.connection; - fs.writeFileSync(manifestPath, JSON.stringify(declared)); vi.stubEnv('AGENT_DEVICE_HOME', home); vi.stubEnv('REVYL_API_KEY', 'rk_test'); vi.stubEnv('REVYL_API_URL', ''); diff --git a/src/cli/commands/__tests__/daemon.test.ts b/src/cli/commands/__tests__/daemon.test.ts index 6e368a6496..5dc7082398 100644 --- a/src/cli/commands/__tests__/daemon.test.ts +++ b/src/cli/commands/__tests__/daemon.test.ts @@ -320,7 +320,7 @@ test('daemon status reads the daemon record without stopping or contacting the d version: '0.21.30', plugins: [ { - provider: 'browserstack', + provider: 'aws-device-farm', source: 'builtin', state: 'active', credentials: { variables: [], byBackend: {} }, @@ -354,7 +354,7 @@ test('daemon status reads the daemon record without stopping or contacting the d ); const render = mocks.writeCommandOutput.mock.calls[0]![2] as () => string; expect(render()).toContain('testmu [store] @agent-device/testmu@1.0.0 - failed: bad plugin'); - expect(render()).toContain('browserstack [builtin] builtin - active'); + expect(render()).toContain('aws-device-farm [builtin] builtin - active'); // A host-owned pid changes what a stop may do to it, so status says who owns it. expect(render()).toContain('pid 321, host-owned'); } finally { diff --git a/src/cli/commands/__tests__/plugins.test.ts b/src/cli/commands/__tests__/plugins.test.ts index b6b8ac5db7..001f74c593 100644 --- a/src/cli/commands/__tests__/plugins.test.ts +++ b/src/cli/commands/__tests__/plugins.test.ts @@ -1,10 +1,18 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; +import { runCmdSync } from '@agent-device/host-kit/command'; +import * as command from '@agent-device/host-kit/command'; import { afterEach, test, vi } from 'vitest'; import { runCli } from '../../../cli.ts'; +import * as pluginStore from '@agent-device/plugins/store'; import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; -import { pluginHome, selectPlugin, beginStdoutCapture } from '@agent-device/test-kit'; +import { + pluginHome, + selectV2Plugin, + v2RegistrationSource, + beginStdoutCapture, +} from '@agent-device/test-kit'; import { parseArgs, parseRawArgs, usageForCommand } from '../../parser/args.ts'; vi.mock('../../../provider-device-runtimes.ts', () => { @@ -15,17 +23,20 @@ afterEach(() => { vi.restoreAllMocks(); }); -test('plugins list and remove route through the CLI and emits JSON without daemon access or plugin evaluation', async () => { +test('plugins list and remove route through the CLI and emits JSON without daemon access or setup', async () => { const { home } = pluginHome(); vi.stubEnv('AGENT_DEVICE_HOME', home); vi.stubEnv('AGENT_DEVICE_STATE_DIR', path.join(home, 'state')); vi.stubEnv('AGENT_DEVICE_NO_UPDATE_NOTIFIER', '1'); - const marker = path.join(home, 'evaluated'); - selectPlugin( + const marker = path.join(home, 'setup'); + selectV2Plugin( home, 'example', - 'example', - `import fs from 'node:fs'; fs.writeFileSync(${JSON.stringify(marker)}, 'yes');`, + `import fs from 'node:fs'; + export default () => ({ + apiVersion: 2, provider: 'example', credentials: { variables: [] }, + setup: async () => { fs.writeFileSync(${JSON.stringify(marker)}, 'yes'); throw new Error('must not set up'); }, + });`, ); const sendToDaemon = vi.fn(async () => { throw new Error('unexpected daemon access'); @@ -40,7 +51,7 @@ test('plugins list and remove route through the CLI and emits JSON without daemo const result = JSON.parse(stdout); assert.equal(result.success, true); assert.deepEqual(result.data.plugins, [ - { name: 'example', version: '1.2.3', provider: 'example', compatible: true }, + { name: 'example', version: '2.0.0', provider: 'example', compatible: true }, ]); assert.equal(sendToDaemon.mock.calls.length, 0); await runCli(['plugins', 'remove', 'example', '--json'], { sendToDaemon }); @@ -58,6 +69,11 @@ test('plugin schema exposes operator help and preserves scoped npm package specs const help = await usageForCommand('plugins'); assert.ok(help); assert.match(help, /plugins list \[--state-dir \]\|add/); + assert.match(help, /add /); + assert.deepEqual(parseRawArgs(['plugins', 'add', './plugin.tgz', '--json']).positionals, [ + 'add', + './plugin.tgz', + ]); }); test('plugins list reports the running daemon inventory next to the store selections', async () => { @@ -87,7 +103,7 @@ test('plugins list reports the running daemon inventory next to the store select plugins: [failed], }), ); - selectPlugin(home, 'example', 'example', 'export default () => {};'); + selectV2Plugin(home, 'example', v2RegistrationSource('example')); const stdoutCapture = beginStdoutCapture(); try { await runCli(['plugins', 'list', '--json'], { @@ -161,7 +177,7 @@ test('plugins list names a plugin the running daemon did not register', async () ], }), ); - selectPlugin(home, 'example', 'example', 'export default () => {};'); + selectV2Plugin(home, 'example', v2RegistrationSource('example')); const text = await listPluginsAsText(home, stateDir); assert.match(text, /example@.* \(example\)/); assert.match(text, /The running daemon did not register example: bad plugin/); @@ -176,3 +192,220 @@ test('plugins list says when the daemon record cannot be used instead of hiding assert.match(text, /No provider plugins installed\./); assert.match(text, /daemon record for .* is invalid, so its providers are unknown/); }); + +test.each(['relative', 'absolute'])( + 'plugins add installs a %s archive without loading the factory', + async (form) => { + const { home } = pluginHome(); + vi.stubEnv('AGENT_DEVICE_HOME', home); + vi.stubEnv('AGENT_DEVICE_STATE_DIR', path.join(home, 'state')); + vi.stubEnv('AGENT_DEVICE_NO_UPDATE_NOTIFIER', '1'); + const source = path.join(home, 'source'); + fs.mkdirSync(source); + const marker = path.join(home, 'executed'); + fs.writeFileSync( + path.join(source, 'package.json'), + JSON.stringify({ + name: 'cli-artifact', + version: '1.0.0', + type: 'module', + exports: { './agent-device': './plugin.mjs' }, + scripts: { preinstall: 'node sentinel.cjs' }, + }), + ); + fs.writeFileSync( + path.join(source, 'sentinel.cjs'), + `require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'script')`, + ); + fs.writeFileSync( + path.join(source, 'plugin.mjs'), + `import fs from 'node:fs'; fs.writeFileSync(${JSON.stringify(marker)}, 'factory'); export default () => ({});`, + ); + const packedResult = runCmdSync( + 'npm', + ['pack', '--ignore-scripts', '--json', '--pack-destination', home], + { cwd: source }, + ); + assert.equal(packedResult.exitCode, 0, packedResult.stderr); + const packed = JSON.parse(packedResult.stdout); + const archive = path.join(home, packed[0].filename); + const capture = beginStdoutCapture(); + try { + const input = form === 'relative' ? `./${path.basename(archive)}` : archive; + await runCli( + ['plugins', 'add', input, '--json'], + { sendToDaemon: vi.fn() }, + { + cwd: home, + env: { + ...process.env, + AGENT_DEVICE_HOME: home, + AGENT_DEVICE_STATE_DIR: path.join(home, 'state'), + AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1', + }, + }, + ); + const { data } = JSON.parse(capture.read()); + assert.equal(data.artifact.name, 'cli-artifact'); + assert.equal(data.artifact.version, '1.0.0'); + assert.match(data.artifact.integrity, /^sha512-/); + assert.equal(data.artifact.compatibility, 'unchecked'); + assert.equal('plugins' in data, false); + assert.equal(data.restartRequired, true); + assert.equal(fs.existsSync(marker), false); + } finally { + capture.restore(); + } + }, +); + +test.each([ + [false, './fixture.tgz'], + [true, '../fixture.tgz'], + [true, path.resolve('/fixture.tgz')], +] as const)( + 'artifact receipt uses the executing CLI host (json=%s, input=%s)', + async (json, input) => { + const { home, env } = pluginHome(); + const cwd = path.join(home, 'workspace'); + const stateDir = path.join(home, 'state'); + fs.mkdirSync(cwd); + fs.mkdirSync(stateDir); + fs.writeFileSync(path.join(stateDir, 'daemon.json'), '{invalid'); + const host = { + cwd, + env: { + ...env, + AGENT_DEVICE_STATE_DIR: stateDir, + AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1', + }, + }; + const artifact = { + name: 'cli-artifact', + version: '1.0.0', + installation: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + integrity: `sha512-${Buffer.alloc(64).toString('base64')}`, + }; + const install = vi.spyOn(pluginStore, 'addPluginArtifact').mockResolvedValue(artifact); + const sendToDaemon = vi.fn(async () => { + throw new Error('unexpected daemon access'); + }); + const capture = beginStdoutCapture(); + try { + await runCli(['plugins', 'add', input, ...(json ? ['--json'] : [])], { sendToDaemon }, host); + assert.equal(install.mock.calls.length, 1); + assert.equal(install.mock.calls[0]?.[0], input); + const installedHost = install.mock.calls[0]![1]; + assert.equal(installedHost.cwd, cwd); + assert.deepEqual(Object.keys(installedHost.env).sort(), Object.keys(host.env).sort()); + for (const [key, value] of Object.entries(host.env)) + assert.equal(installedHost.env[key], value); + assert.equal(sendToDaemon.mock.calls.length, 0); + const output = capture.read(); + if (json) { + const { data } = JSON.parse(output); + assert.deepEqual(data.artifact, { ...artifact, compatibility: 'unchecked' }); + assert.equal('plugins' in data, false); + assert.equal(data.daemonRecord, 'invalid'); + } else { + assert.match(output, /compatibility unchecked/i); + assert.match(output, /plugins list/); + } + } finally { + capture.restore(); + } + }, +); + +test.each(['@example/provider@1.2.3', 'plugin.tgz'])( + 'plugins add routes npm selector %s to the registry manager', + async (selector) => { + const { home, env } = pluginHome(); + const host = { cwd: home, env: { ...env, AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1' } }; + const change = vi.spyOn(pluginStore, 'changePlugin').mockResolvedValue(); + const artifact = vi.spyOn(pluginStore, 'addPluginArtifact'); + const capture = beginStdoutCapture(); + try { + await runCli(['plugins', 'add', selector, '--json'], { sendToDaemon: vi.fn() }, host); + assert.equal(change.mock.calls.length, 1); + assert.equal(change.mock.calls[0]?.[0], 'add'); + assert.equal(change.mock.calls[0]?.[1], selector); + assert.equal(artifact.mock.calls.length, 0); + assert.deepEqual(JSON.parse(capture.read()).data.plugins, []); + } finally { + capture.restore(); + } + }, +); + +test.each([ + './missing.tgz', + '../missing.tgz', + './invalid.zip', + './directory', + './directory.tgz', + 'https://example.test/plugin.tgz', + 'file:./plugin.tgz', +])('plugins add rejects %s without a registry install', async (input) => { + const { home, env } = pluginHome(); + fs.mkdirSync(path.join(home, 'directory')); + fs.mkdirSync(path.join(home, 'directory.tgz')); + const host = { cwd: home, env: { ...env, AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1' } }; + const registry = vi.spyOn(pluginStore, 'changePlugin'); + const npm = vi.spyOn(command, 'runCmd'); + const exit = vi.spyOn(process, 'exit').mockImplementation(() => { + throw new Error('test exit'); + }); + const capture = beginStdoutCapture(); + try { + await assert.rejects( + runCli(['plugins', 'add', input, '--json'], { sendToDaemon: vi.fn() }, host), + /test exit/, + ); + assert.equal(JSON.parse(capture.read()).success, false); + assert.equal(npm.mock.calls.length, 0); + if (input.startsWith('./') || input.startsWith('../')) + assert.equal(registry.mock.calls.length, 0); + } finally { + capture.restore(); + exit.mockRestore(); + } +}); + +test('plugins add installs a scoped pinned registry selector through the store', async () => { + const { home, env } = pluginHome(); + const host = { cwd: home, env: { ...env, AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1' } }; + const npm = vi.spyOn(command, 'runCmd').mockImplementation(async (_program, _args, options) => { + const project = options!.cwd!; + const manifest = JSON.parse(fs.readFileSync(path.join(project, 'package.json'), 'utf8')); + assert.deepEqual(manifest.dependencies, { '@example/provider': '1.2.3' }); + const directory = path.join(project, 'node_modules', '@example/provider'); + fs.mkdirSync(directory, { recursive: true }); + fs.writeFileSync( + path.join(directory, 'package.json'), + JSON.stringify({ + name: '@example/provider', + version: '1.2.3', + type: 'module', + exports: { './agent-device': './plugin.mjs' }, + }), + ); + fs.writeFileSync(path.join(directory, 'plugin.mjs'), v2RegistrationSource('example')); + return { stdout: '', stderr: '', exitCode: 0 }; + }); + const capture = beginStdoutCapture(); + try { + await runCli( + ['plugins', 'add', '@example/provider@1.2.3', '--json'], + { sendToDaemon: vi.fn() }, + host, + ); + assert.equal(npm.mock.calls.length, 1); + const { data } = JSON.parse(capture.read()); + assert.equal(data.plugins[0].name, '@example/provider'); + assert.equal(data.plugins[0].version, '1.2.3'); + assert.equal(data.plugins[0].compatible, true); + } finally { + capture.restore(); + } +}); diff --git a/src/cli/commands/__tests__/replay-maestro-export.test.ts b/src/cli/commands/__tests__/replay-maestro-export.test.ts index fcb775472b..32057071d7 100644 --- a/src/cli/commands/__tests__/replay-maestro-export.test.ts +++ b/src/cli/commands/__tests__/replay-maestro-export.test.ts @@ -1,15 +1,8 @@ +import { installedReplayCliTestEnv } from '../../../__tests__/cli-test-env.ts'; import fs from 'node:fs'; import path from 'node:path'; import { parseAllDocuments } from 'yaml'; import { describe, expect, test } from 'vitest'; -import { AppError } from '@agent-device/kernel/errors'; -import { - exportReplayActionsToMaestro, - inspectMaestroFlow, - MAESTRO_SELECTOR_PROJECTION, -} from '@agent-device/maestro'; -import { parseReplayScriptDetailed, readReplayScriptMetadata } from '@agent-device/ad-script'; -import { projectSelectorExpression } from '@agent-device/selectors'; import { runCliCapture } from '../../../__tests__/cli-capture.ts'; import { mkdtempForTestSync } from '@agent-device/test-kit'; @@ -26,7 +19,8 @@ describe('exportReplayScriptToMaestro', () => { const open = withApp ? `com.example.app ${link} --relaunch` : link; fs.writeFileSync(sourcePath, `open ${open}\n`); - const result = await runCliCapture(['replay', 'export', sourcePath, '--json']); + const env = installedReplayCliTestEnv(); + const result = await runCliCapture(['replay', 'export', sourcePath, '--json'], { env }); expect(result.code).toBeNull(); expect(result.calls).toEqual([]); @@ -44,307 +38,16 @@ describe('exportReplayScriptToMaestro', () => { ] : [[{ openLink: link }]], ); - expect(() => inspectMaestroFlow(output.data.yaml, 'flow.yaml')).not.toThrow(); - const written = await runCliCapture(['replay', 'export', sourcePath, '--out', outPath]); + const written = await runCliCapture(['replay', 'export', sourcePath, '--out', outPath], { + env, + }); expect(written).toMatchObject({ code: null, calls: [], stderr: '', stdout: `${outPath}\n` }); expect(fs.readFileSync(outPath, 'utf8')).toBe(output.data.yaml); }); - - test('exports app launch, selectors, input, keyboard, assertions, and screenshots', () => { - const result = exportReplayScriptToMaestro(`env USER="Ada" -context platform=ios target=mobile -open com.example.app --relaunch -click id="email" -fill id="email" "ada@example.com" -keyboard dismiss -find text "Continue" exists -screenshot "./artifacts/checkout" -`); - - const docs = parseYamlDocs(result.yaml); - expect(() => inspectMaestroFlow(result.yaml, 'export.yaml')).not.toThrow(); - expect(docs).toEqual([ - { appId: 'com.example.app', env: { USER: 'Ada' } }, - [ - { launchApp: { appId: 'com.example.app', stopApp: true } }, - { tapOn: { id: 'email' } }, - { tapOn: { id: 'email' } }, - { inputText: 'ada@example.com' }, - 'hideKeyboard', - { assertVisible: 'Continue' }, - { takeScreenshot: './artifacts/checkout' }, - ], - ]); - expect(result.warnings).toEqual([ - { - line: 5, - action: 'fill id="email" ada@example.com', - message: - 'fill exports as tapOn + inputText; Maestro may append text instead of replacing existing field contents', - }, - ]); - }); - - test('exports each app target when a script switches apps and returns', () => { - const result = exportReplayScriptToMaestro(`open com.example.shop -open com.example.auth -open com.example.shop -`); - - expect(() => inspectMaestroFlow(result.yaml, 'apps.yaml')).not.toThrow(); - expect(parseYamlDocs(result.yaml)).toEqual([ - { appId: 'com.example.shop' }, - [ - { launchApp: { appId: 'com.example.shop' } }, - { launchApp: { appId: 'com.example.auth' } }, - { launchApp: { appId: 'com.example.shop' } }, - ], - ]); - expect(result.warnings).toEqual([]); - }); - - test('exports the empty-fill clear as eraseText, never a vacuous inputText', () => { - // `fill ""` is the clear-field primitive (#2063); Maestro's `inputText: ""` types - // nothing, so the recorded clear must become its clear verb. - const result = exportReplayScriptToMaestro(`context platform=ios target=mobile -open com.example.app -fill id="email" "" -`); - - const docs = parseYamlDocs(result.yaml); - expect(docs[1]).toEqual([ - { launchApp: { appId: 'com.example.app' } }, - { tapOn: { id: 'email' } }, - 'eraseText', - ]); - expect(result.warnings).toEqual([ - { - line: 3, - action: 'fill id="email"', - message: - 'fill "" exports as tapOn + eraseText; Maestro erases at most its 50-character default', - }, - ]); - }); - - test('exports coordinate gestures and sleep waits with warnings', () => { - const result = exportReplayScriptToMaestro(`open com.example.app -click 120 240 -swipe 200 700 200 200 --count 2 -wait 500 -`); - - expect(parseYamlDocs(result.yaml)).toEqual([ - { appId: 'com.example.app' }, - [ - { launchApp: { appId: 'com.example.app' } }, - { tapOn: { point: '120,240' } }, - { swipe: { start: '200,700', end: '200,200', duration: 100 } }, - { swipe: { start: '200,700', end: '200,200', duration: 100 } }, - { waitForAnimationToEnd: { timeout: 500 } }, - ], - ]); - expect(result.warnings).toEqual([ - { - line: 4, - action: 'wait 500', - message: - 'wait exports as waitForAnimationToEnd and may return before the full duration', - }, - ]); - }); - - test('exports wait stable as waitForAnimationToEnd and text or selector waits with their timeouts', () => { - const result = exportReplayScriptToMaestro(`open com.example.app -wait stable -wait stable 500 3000 -wait text "Ready" 2000 -wait 'id="done"' 4000 -wait id="save" enabled=true 25000 -wait text Sign in 2000 -`); - - expect(parseYamlDocs(result.yaml)).toEqual([ - { appId: 'com.example.app' }, - [ - { launchApp: { appId: 'com.example.app' } }, - 'waitForAnimationToEnd', - { waitForAnimationToEnd: { timeout: 3000 } }, - { extendedWaitUntil: { visible: 'Ready', timeout: 2000 } }, - { extendedWaitUntil: { visible: { id: 'done' }, timeout: 4000 } }, - { extendedWaitUntil: { visible: { id: 'save', enabled: true }, timeout: 25000 } }, - { extendedWaitUntil: { visible: 'Sign in', timeout: 2000 } }, - ], - ]); - const stableWarning = - 'wait stable exports as waitForAnimationToEnd, which uses its own screen-stability threshold instead of the quiet window'; - expect(result.warnings).toEqual([ - { line: 2, action: 'wait stable', message: stableWarning }, - { line: 3, action: 'wait stable 500 3000', message: stableWarning }, - ]); - }); - - test('rejects wait forms that have no on-screen text to wait for', () => { - const run = () => - exportReplayScriptToMaestro(`open com.example.app -wait @e3 -wait text -wait stable 500 junk -wait visible label="Save" 25000 -`); - expect(run).toThrowError(AppError); - expect(run).toThrowError('line 2 (wait @e3): wait @ref names a session-local ref'); - expect(run).toThrowError('line 3 (wait text): wait text requires the text to wait for'); - expect(run).toThrowError( - 'line 4 (wait stable 500 junk): wait stable takes at most a numeric quietMs and timeoutMs', - ); - // The whole selector reaches the projection, which refuses `visible`; it never exports as text. - expect(run).toThrowError( - 'line 5 (wait visible label="Save" 25000): wait selector is not Maestro-compatible', - ); - }); - - // #3197: `scroll --until` became part of a scroll action, so the export names - // the stop condition it cannot carry instead of exporting a bare page scroll. - test('warns when scroll --until exports as a bare Maestro scroll', () => { - const result = exportReplayScriptToMaestro(`open com.example.app -scroll down --until 'id="far-button"' -`); - - expect(parseYamlDocs(result.yaml)).toEqual([ - { appId: 'com.example.app' }, - [{ launchApp: { appId: 'com.example.app' } }, 'scroll'], - ]); - expect(result.warnings).toEqual([ - { - line: 2, - // The action label names positionals only, so the flag shows in the message. - action: 'scroll down', - message: 'scroll --until id="far-button" is not represented by Maestro scroll', - }, - ]); - }); - - test('warns when explicit long-press durations export to Maestro defaults', () => { - const result = exportReplayScriptToMaestro(`open com.example.app -longpress "label=\\"Last message\\"" 800 -click id="hold-button" --hold-ms 1200 -press text="Retry" --hold-ms 1500 -`); - - expect(parseYamlDocs(result.yaml)).toEqual([ - { appId: 'com.example.app' }, - [ - { launchApp: { appId: 'com.example.app' } }, - { longPressOn: { text: 'Last message' } }, - { longPressOn: { id: 'hold-button' } }, - { longPressOn: { text: 'Retry' } }, - ], - ]); - expect(result.warnings).toEqual([ - { - line: 2, - action: 'longpress label="Last message" 800', - message: - 'label= selectors export as Maestro text; Maestro text matching is broader than agent-device label-only matching', - }, - { - line: 2, - action: 'longpress label="Last message" 800', - message: - 'long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of 800ms', - }, - { - line: 3, - action: 'click id="hold-button"', - message: - 'long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of 1200ms', - }, - { - line: 4, - action: 'press text="Retry"', - message: - 'long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of 1500ms', - }, - ]); - }); - - test('warns when double-tap and hold exports ignore repeated tap options', () => { - const result = exportReplayScriptToMaestro(`open com.example.app -click id="retry" --double-tap --count 2 --interval-ms 200 -press text="Hold" --hold-ms 1000 --count 3 --interval-ms 150 -`); - - expect(parseYamlDocs(result.yaml)).toEqual([ - { appId: 'com.example.app' }, - [ - { launchApp: { appId: 'com.example.app' } }, - { doubleTapOn: { id: 'retry' } }, - { longPressOn: { text: 'Hold' } }, - ], - ]); - expect(result.warnings).toEqual([ - { - line: 2, - action: 'click id="retry"', - message: 'tap --count 2 is not represented by Maestro doubleTapOn', - }, - { - line: 2, - action: 'click id="retry"', - message: 'tap --interval-ms 200 is not represented by Maestro doubleTapOn', - }, - { - line: 3, - action: 'press text="Hold"', - message: - 'long-press duration exports as Maestro longPressOn; Maestro uses its default long-press duration instead of 1000ms', - }, - { - line: 3, - action: 'press text="Hold"', - message: 'tap --count 3 is not represented by Maestro longPressOn', - }, - { - line: 3, - action: 'press text="Hold"', - message: 'tap --interval-ms 150 is not represented by Maestro longPressOn', - }, - ]); - }); - - test('rejects native-only replay actions', () => { - expect(() => - exportReplayScriptToMaestro(`open com.example.app -snapshot -i -get text id="status" -`), - ).toThrowError(AppError); - try { - exportReplayScriptToMaestro(`open com.example.app -snapshot -i -get text id="status" -`); - } catch (error) { - expect(error).toBeInstanceOf(AppError); - expect((error as AppError).message).toContain('line 2 (snapshot)'); - expect((error as AppError).message).toContain('line 3 (get text id="status")'); - } - }); }); -function exportReplayScriptToMaestro(script: string) { - const parsed = parseReplayScriptDetailed(script); - return exportReplayActionsToMaestro(parsed.actions, { - actionLines: parsed.actionLines, - metadata: readReplayScriptMetadata(script), - resolveSelector: (expression) => - projectSelectorExpression(expression, MAESTRO_SELECTOR_PROJECTION), - }); -} - function parseYamlDocs(script: string): unknown[] { return parseAllDocuments(script).map((doc) => doc.toJSON()); } diff --git a/src/cli/commands/connection-aws-admission.test.ts b/src/cli/commands/connection-aws-admission.test.ts new file mode 100644 index 0000000000..89d3cb625a --- /dev/null +++ b/src/cli/commands/connection-aws-admission.test.ts @@ -0,0 +1,75 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { test } from 'vitest'; +import { runCliCapture } from '../../__tests__/cli-capture.ts'; +import { + hashRemoteConfigFile, + readRemoteConnectionState, + writeRemoteConnectionState, +} from '@agent-device/remote/remote-connection-state'; +import { pluginHome, selectV2Plugin } from '@agent-device/test-kit'; + +test.each(['missing', 'failed'] as const)( + 'AWS profile and stored connection refuse a %s plugin before lease actions', + async (kind) => { + const { home, env } = pluginHome(); + if (kind === 'failed') + selectV2Plugin( + home, + '@agent-device/aws-device-farm', + 'throw new Error("registration failed")', + ); + const stateDir = path.join(home, 'state'); + const remoteConfigPath = path.join(home, 'aws.json'); + fs.writeFileSync( + remoteConfigPath, + JSON.stringify({ + tenant: 'team', + runId: 'run-1', + leaseProvider: 'aws-device-farm', + leaseBackend: 'android-instance', + platform: 'android', + }), + ); + const opts = { cwd: home, env: { ...env, AGENT_DEVICE_SESSION: 'default' } }; + const expected = kind === 'missing' ? 'plugin-not-installed' : 'plugin-unavailable'; + const connect = await runCliCapture( + ['connect', '--remote-config', remoteConfigPath, '--state-dir', stateDir, '--json'], + opts, + ); + assert.equal(connect.code, 1, connect.stdout); + assert.equal(JSON.parse(connect.stdout).error?.code, 'UNSUPPORTED_OPERATION', connect.stdout); + assert.equal(JSON.parse(connect.stdout).error?.details?.reason, expected, connect.stdout); + assert.deepEqual(connect.calls, []); + assert.equal(readRemoteConnectionState({ stateDir, session: 'default' }), null); + const now = new Date().toISOString(); + writeRemoteConnectionState({ + stateDir, + state: { + version: 1, + session: 'default', + remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), + tenant: 'team', + runId: 'run-1', + leaseProvider: 'aws-device-farm', + leaseBackend: 'android-instance', + platform: 'android', + connectedAt: now, + updatedAt: now, + }, + }); + for (const argv of [ + ['connection', 'status', '--state-dir', stateDir, '--json'], + ['snapshot', '--state-dir', stateDir, '--json'], + ]) { + const result = await runCliCapture(argv, opts); + assert.equal(result.code, 1, result.stdout); + assert.equal(JSON.parse(result.stdout).error?.code, 'UNSUPPORTED_OPERATION', result.stdout); + assert.equal(JSON.parse(result.stdout).error?.details?.reason, expected, result.stdout); + assert.deepEqual(result.calls, []); + assert.doesNotMatch(result.stdout, /install-from-source|leaseId.*pending/); + } + }, +); diff --git a/src/cli/commands/connection-browserstack.test.ts b/src/cli/commands/connection-browserstack.test.ts new file mode 100644 index 0000000000..526ba52e77 --- /dev/null +++ b/src/cli/commands/connection-browserstack.test.ts @@ -0,0 +1,449 @@ +import { afterEach, beforeEach, test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { runCliCapture } from '../../__tests__/cli-capture.ts'; +import { + readActiveConnectionState, + readRemoteConnectionState, + type RemoteConnectionState, +} from '@agent-device/remote/remote-connection-state'; +import { AppError } from '@agent-device/kernel/errors'; +import { verifyBrowserStackConnection } from '@agent-device/browserstack/connection-verification'; +import browserstack from '@agent-device/browserstack'; +import { resolveProviderPlugins } from '@agent-device/plugins/registry'; +import { resolveConnectProviderProfile } from '../connection/connect-provider-adapters.ts'; +import { + mkdtempForTestSync, + pluginHome, + selectV2Plugin, + v2RegistrationSource, + bindTestCommandHost, +} from '@agent-device/test-kit'; +import manifest from '@agent-device/browserstack/package.json' with { type: 'json' }; +import type { PluginConnectionCallbacks } from '@agent-device/plugins/connection'; +import { connectWithGeneratedProviderProfile } from '../../__tests__/test-utils/connect-command.ts'; + +bindTestCommandHost(); + +const CREDENTIALS = { + BROWSERSTACK_USERNAME: 'browser-user', + BROWSERSTACK_ACCESS_KEY: 'browser-key', +}; + +vi.mock('@agent-device/browserstack/connection-verification', () => ({ + verifyBrowserStackConnection: vi.fn(), +})); +vi.mock('@agent-device/plugins/load', () => ({ + withPluginConnection: async ( + _provider: string, + _builtinProviders: readonly string[], + _env: NodeJS.ProcessEnv, + runConnection: (connection: PluginConnectionCallbacks) => Promise, + ) => { + const { connections } = await resolveProviderPlugins([ + { source: 'store', package: manifest.name, load: () => browserstack() }, + ]); + return await runConnection(connections.get('browserstack')!); + }, +})); + +afterEach(() => { + vi.clearAllMocks(); + vi.unstubAllEnvs(); +}); + +const mockedVerifyBrowserStackConnection = vi.mocked(verifyBrowserStackConnection); + +let pluginHomeDir = ''; + +beforeEach(() => { + const { home } = pluginHome(); + pluginHomeDir = home; + // The store declares the plugin installed with BrowserStack's capabilities; the mocked loader + // above supplies the workspace factory those assertions exercise. + selectV2Plugin( + home, + manifest.name, + v2RegistrationSource('browserstack', { + extra: `connection: { capabilities: ${JSON.stringify(browserstack().connection?.capabilities)}, resolve() {}, verify() {} },`, + credentials: '{ variables: ["BROWSERSTACK_USERNAME", "BROWSERSTACK_ACCESS_KEY"] }', + }), + ); + vi.stubEnv('AGENT_DEVICE_HOME', home); + mockedVerifyBrowserStackConnection.mockImplementation(async (options) => ({ + provider: 'browserstack', + service: 'BrowserStack', + verificationMessage: 'Credentials, device, and uploaded app verified.', + device: { + status: 'verified', + name: options.deviceName, + platform: options.platform, + osVersion: options.osVersion, + }, + app: { status: 'verified', reference: options.app }, + })); +}); + +test('connect browserstack generates local provider profile without credentials', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-browserstack-'); + const stateDir = path.join(tempRoot, '.state'); + vi.stubEnv('BROWSERSTACK_USERNAME', 'browser-user'); + vi.stubEnv('BROWSERSTACK_ACCESS_KEY', 'browser-key'); + + try { + await connectWithGeneratedProviderProfile({ + stateDir, + positionals: ['browserstack'], + flags: { + platform: 'android', + device: 'Google Pixel 8', + providerOsVersion: '14.0', + providerApp: 'bs://app-id', + providerProject: 'agent-device', + providerBuild: 'build-a', + }, + }); + + const state = readRequiredActiveState(stateDir); + assert.equal(state.tenant, 'browserstack'); + assert.equal(state.leaseProvider, 'browserstack'); + assert.equal(state.daemon?.baseUrl, undefined); + assert.match(state.remoteConfigPath, /generated\/browserstack-[a-f0-9]{16}\.json$/); + const generated = readGeneratedConfig(state.remoteConfigPath); + assert.equal(generated.providerApp, 'bs://app-id'); + assert.equal(generated.providerOsVersion, '14.0'); + assert.equal(generated.providerProject, 'agent-device'); + assert.equal(generated.providerBuild, 'build-a'); + assert.equal(JSON.stringify(generated).includes('browser-key'), false); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('connect browserstack canonicalizes the app scheme and refuses a malformed bs:// id', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-browserstack-ref-'); + const stateDir = path.join(tempRoot, '.state'); + vi.stubEnv('BROWSERSTACK_USERNAME', 'browser-user'); + vi.stubEnv('BROWSERSTACK_ACCESS_KEY', 'browser-key'); + const flags = { + platform: 'android' as const, + device: 'Google Pixel 8', + providerOsVersion: '14.0', + }; + + try { + await connectWithGeneratedProviderProfile({ + stateDir, + positionals: ['browserstack'], + flags: { ...flags, providerApp: 'Bs://app-id' }, + }); + assert.equal( + readGeneratedConfig(readRequiredActiveState(stateDir).remoteConfigPath).providerApp, + 'bs://app-id', + ); + // Verification must look up the reference the profile saved, not the spelling typed. + assert.equal(mockedVerifyBrowserStackConnection.mock.calls[0]?.[0].app, 'bs://app-id'); + + for (const app of ['bs://', 'bs://a b', 'BS://a/b']) { + await assert.rejects( + resolveConnectProviderProfile({ + provider: 'browserstack', + stateDir, + cwd: tempRoot, + env: CREDENTIALS, + flags: { json: false, help: false, version: false, ...flags, providerApp: app }, + }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + assert.equal(error.message, `BrowserStack --provider-app ${app} is not a bs:// app id.`); + assert.deepEqual(error.details, { + providerApp: app, + hint: 'Pass .', + }); + return true; + }, + ); + } + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('connect --remote-config verifies a direct provider profile before saving state', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-provider-config-'); + const stateDir = path.join(tempRoot, '.state'); + const remoteConfig = path.join(tempRoot, 'browserstack.remote.json'); + fs.writeFileSync( + remoteConfig, + JSON.stringify({ + tenant: 'browserstack', + runId: 'browserstack-config', + sessionIsolation: 'tenant', + leaseProvider: 'browserstack', + leaseBackend: 'android-instance', + platform: 'android', + target: 'mobile', + device: 'Google Pixel 8', + providerOsVersion: '14.0', + providerApp: 'bs://app-id', + }), + ); + vi.stubEnv('BROWSERSTACK_USERNAME', 'browser-user'); + vi.stubEnv('BROWSERSTACK_ACCESS_KEY', 'browser-key'); + + try { + await connectWithGeneratedProviderProfile({ + stateDir, + positionals: [], + flags: { remoteConfig }, + }); + + assert.equal(mockedVerifyBrowserStackConnection.mock.calls.length, 1); + assert.deepEqual(mockedVerifyBrowserStackConnection.mock.calls[0]?.[0], { + username: 'browser-user', + accessKey: 'browser-key', + platform: 'android', + deviceName: 'Google Pixel 8', + osVersion: '14.0', + app: 'bs://app-id', + }); + assert.equal(readRequiredActiveState(stateDir).remoteConfigPath, remoteConfig); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('connect browserstack persists a local app artifact as an absolute path', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-browserstack-app-'); + const stateDir = path.join(tempRoot, '.state'); + const appPath = path.join(tempRoot, 'sample.apk'); + fs.writeFileSync(appPath, 'fixture'); + vi.stubEnv('BROWSERSTACK_USERNAME', 'browser-user'); + vi.stubEnv('BROWSERSTACK_ACCESS_KEY', 'browser-key'); + + try { + // The host the command runs in decides what `./sample.apk` is relative to. + await connectWithGeneratedProviderProfile({ + stateDir, + host: { env: process.env, cwd: fs.realpathSync(tempRoot) }, + positionals: ['browserstack'], + flags: { + platform: 'android', + device: 'Google Pixel 8', + providerOsVersion: '14.0', + providerApp: './sample.apk', + }, + }); + + const state = readRequiredActiveState(stateDir); + assert.equal(readGeneratedConfig(state.remoteConfigPath).providerApp, fs.realpathSync(appPath)); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('connect browserstack refuses AWS Device Farm flags', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-browserstack-reject-'); + + try { + await assert.rejects( + resolveConnectProviderProfile({ + provider: 'browserstack', + stateDir: path.join(tempRoot, '.state'), + cwd: tempRoot, + env: CREDENTIALS, + flags: { + json: false, + help: false, + version: false, + platform: 'android', + device: 'Google Pixel 8', + providerOsVersion: '14.0', + providerApp: 'bs://app-id', + awsProjectArn: 'arn:aws:devicefarm:us-west-2:123:project:project-a', + }, + }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + assert.equal(error.details?.provider, 'browserstack'); + assert.deepEqual(error.details?.flags, ['--aws-project-arn']); + return true; + }, + ); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('connect browserstack refuses --provider-device-type before saving a profile', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-browserstack-device-type-'); + + try { + await assert.rejects( + resolveConnectProviderProfile({ + provider: 'browserstack', + stateDir: path.join(tempRoot, '.state'), + cwd: tempRoot, + env: CREDENTIALS, + flags: { + json: false, + help: false, + version: false, + platform: 'android', + device: 'Google Pixel 8', + providerOsVersion: '14.0', + providerApp: 'bs://app-id', + providerDeviceType: 'real', + }, + }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + assert.match(error.message, /^--provider-device-type is not supported by /); + assert.equal(error.details?.provider, 'browserstack'); + return true; + }, + ); + assert.equal(fs.existsSync(path.join(tempRoot, '.state')), false); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('connect browserstack JSON preserves the workflow notes from human output', async () => { + const result = await runCliCapture( + [ + 'connect', + 'browserstack', + '--session=ci', + '--platform', + 'android', + '--device', + 'Google Pixel 8', + '--provider-os-version', + '14.0', + '--provider-app', + 'bs://app-id', + '--json', + ], + { + env: { ...CREDENTIALS, AGENT_DEVICE_HOME: pluginHomeDir }, + stateDirPrefix: 'agent-device-connect-browserstack-json-', + }, + ); + + assert.equal(result.code, null); + const output = (JSON.parse(result.stdout) as { data: Record }).data; + assert.deepEqual(output.nextSteps, [ + `agent-device open --relaunch --session ${output.session}`, + ]); + assert.deepEqual(output.notes, [ + 'Use the installed package or bundle identifier in open, not the app artifact name.', + `After close, run agent-device artifacts --json --session ${output.session} for provider video and logs.`, + ]); +}); + +test('every command BrowserStack connect emits resolves back to the connection that emitted it', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-scoped-commands-'); + const stateDir = path.join(tempRoot, '.state'); + const browserstackArgs = [ + 'connect', + 'browserstack', + '--platform', + 'android', + '--device', + 'Google Pixel 8', + '--provider-os-version', + '14.0', + '--provider-app', + 'bs://app-id', + '--state-dir', + stateDir, + ]; + const captureOptions = { env: { ...CREDENTIALS, AGENT_DEVICE_HOME: pluginHomeDir } }; + + try { + const json = await runCliCapture( + [...browserstackArgs, '--session=bs-1', '--json'], + captureOptions, + ); + const human = await runCliCapture([...browserstackArgs, '--session=bs-2'], captureOptions); + + assert.equal(json.code, null); + assert.equal(human.code, null); + const output = (JSON.parse(json.stdout) as { data: Record }).data; + const session: string = output.session; + + // Every emitted command — nextSteps AND the prose notes — must name a + // session, so following one cannot adopt whichever connection happens to + // be host-global active in a concurrent run. + for (const line of [...output.nextSteps, ...output.notes]) { + assertCommandsAreSessionScoped(line, session); + } + assert.deepEqual([...readEmittedSessions([...output.nextSteps, ...output.notes])], [session]); + + // The human run is a second connect under its own session; its commands must name THAT one, + // not the JSON run's. + const humanSessions = [...readEmittedSessions([human.stdout])]; + assert.equal(humanSessions.length, 1, human.stdout); + const humanSession = humanSessions[0] ?? ''; + assert.notEqual(humanSession, session); + assertCommandsAreSessionScoped(human.stdout, humanSession); + + // The scope is not decoration: resolving each emitted --session lands on + // the connection state that connect wrote. + for (const emittedSession of [session, humanSession]) { + const state = readRemoteConnectionState({ stateDir, session: emittedSession }); + assert.equal(state?.session, emittedSession); + assert.equal(state?.leaseProvider, 'browserstack'); + assert.equal(state?.tenant, 'browserstack'); + } + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +/** + * A command-bearing string must carry one `--session ` per `agent-device` + * invocation it suggests. Counting rather than matching means an added command + * cannot silently ship unscoped alongside a scoped sibling. + */ +function assertCommandsAreSessionScoped(text: string, session: string): void { + const commands = text.match(/agent-device\s+[a-z]/g)?.length ?? 0; + const scopes = text.split(`--session ${session}`).length - 1; + assert.equal(scopes, commands, `unscoped suggested command in: ${text}`); +} + +function readEmittedSessions(texts: readonly string[]): Set { + const sessions = new Set(); + for (const text of texts) { + for (const match of text.matchAll(/--session\s+(\S+)/g)) { + const value = match[1]; + if (value) sessions.add(value); + } + } + return sessions; +} + +function readGeneratedConfig(configPath: string): { + providerApp?: string; + providerOsVersion?: string; + providerProject?: string; + providerBuild?: string; +} { + return JSON.parse(fs.readFileSync(configPath, 'utf8')) as { + providerApp?: string; + providerOsVersion?: string; + providerProject?: string; + providerBuild?: string; + }; +} + +function readRequiredActiveState(stateDir: string): RemoteConnectionState { + const state = readActiveConnectionState({ stateDir }); + assert.ok(state); + return state; +} diff --git a/src/cli/commands/connection-lease-policy.test.ts b/src/cli/commands/connection-lease-policy.test.ts index 825f1e41bf..1212b4860a 100644 --- a/src/cli/commands/connection-lease-policy.test.ts +++ b/src/cli/commands/connection-lease-policy.test.ts @@ -33,7 +33,7 @@ vi.mock('../connection/provider-policy.ts', () => ({ function ttlFor(leaseProvider: string): number | undefined { const state = { leaseProvider } as RemoteConnectionState; - return connectionLeasePolicyForState(state).ttlMs(state); + return connectionLeasePolicyForState(state, {}).ttlMs(state, {}); } test.each([ diff --git a/src/cli/commands/connection-lease-policy.ts b/src/cli/commands/connection-lease-policy.ts index 569cd8c4be..fca756c4fe 100644 --- a/src/cli/commands/connection-lease-policy.ts +++ b/src/cli/commands/connection-lease-policy.ts @@ -19,8 +19,11 @@ const leaseDeferredCommands = new Set([ 'session', 'shutdown', ]); -function remoteLeaseTtlMs(state: RemoteConnectionState): number | undefined { - const capabilities = connectionProviderCapabilities(state.leaseProvider); +function remoteLeaseTtlMs( + state: RemoteConnectionState, + env: NodeJS.ProcessEnv, +): number | undefined { + const capabilities = connectionProviderCapabilities(state.leaseProvider, env); return capabilities.leaseKind === 'proxy' || capabilities.usesCloudWebDriverLease || capabilities.holdsCloudDevice === true @@ -30,7 +33,7 @@ function remoteLeaseTtlMs(state: RemoteConnectionState): number | undefined { export type ConnectionLeasePolicy = { shouldAllocate(command: string): boolean; - ttlMs(state: RemoteConnectionState): number | undefined; + ttlMs(state: RemoteConnectionState, env: NodeJS.ProcessEnv): number | undefined; /** The id this client names a new lease with; without it the daemon mints one. */ newLeaseId?(): string; resolveLeaseState(options: { @@ -42,9 +45,12 @@ export type ConnectionLeasePolicy = { }): Promise; }; -export function connectionLeasePolicyForState(state: RemoteConnectionState): ConnectionLeasePolicy { +export function connectionLeasePolicyForState( + state: RemoteConnectionState, + env: NodeJS.ProcessEnv, +): ConnectionLeasePolicy { if (state.leaseBackend === 'macos-app') return MACOS_APP_CONNECTION_LEASE_POLICY; - const capabilities = connectionProviderCapabilities(state.leaseProvider); + const capabilities = connectionProviderCapabilities(state.leaseProvider, env); if (capabilities.leaseKind === 'proxy') { return PROXY_CONNECTION_LEASE_POLICY; } diff --git a/src/cli/commands/connection-lease-transaction.ts b/src/cli/commands/connection-lease-transaction.ts index 322524aea9..a303567481 100644 --- a/src/cli/commands/connection-lease-transaction.ts +++ b/src/cli/commands/connection-lease-transaction.ts @@ -114,15 +114,17 @@ export async function acquireConnectionLease(options: { nextFlags: CliFlags; positionals?: string[]; leaseLedger: LeaseLedger; + env: NodeJS.ProcessEnv; }): Promise<{ state: RemoteConnectionState; changed: boolean }> { const { command, client, state, nextFlags, leaseLedger } = options; const deferredAppSelection = connectionProviderCapabilities( state.leaseProvider, + options.env, ).supportsDeferredAppSelection; const initialApp = deferredAppSelection && command === PUBLIC_COMMANDS.open ? options.positionals?.[0] : undefined; if (deferredAppSelection) delete nextFlags.providerApp; - const leasePolicy = connectionLeasePolicyForState(state); + const leasePolicy = connectionLeasePolicyForState(state, options.env); let nextState = state; let changed = false; if (leasePolicy.shouldAllocate(command)) { @@ -135,6 +137,7 @@ export async function acquireConnectionLease(options: { initialApp, policy: leasePolicy, leaseLedger, + env: options.env, }); nextState = materialized.state; changed = materialized.changed; @@ -184,6 +187,7 @@ async function materializeLeaseForCommand(options: { initialApp?: string; policy: ConnectionLeasePolicy; leaseLedger: LeaseLedger; + env: NodeJS.ProcessEnv; }): Promise<{ state: RemoteConnectionState; changed: boolean }> { const { command, client, state, nextFlags, policy, leaseLedger } = options; const preliminaryLeaseBackend = state.leaseBackend ?? resolveRequestedLeaseBackend(nextFlags); @@ -218,6 +222,7 @@ async function materializeLeaseForCommand(options: { options.initialApp, resolvedLeaseState.allocateBySpec, leaseLedger, + options.env, ); if (resolvedLeaseState.allocateBySpec) { const bound = await bindLeaseNamedDevice({ @@ -237,6 +242,7 @@ async function materializeLeaseForCommand(options: { options.initialApp, undefined, leaseLedger, + options.env, ), }); nextState = bound.state; @@ -357,6 +363,7 @@ async function allocateOrReuseLease( initialApp: string | undefined, allocateBySpec: boolean | undefined, leaseLedger: LeaseLedger, + env: NodeJS.ProcessEnv, ): Promise<{ lease: Lease; acquired: boolean }> { const connection = buildRemoteConnectionRequestMetadata(state); if (state.leaseId && state.leaseBackend === leaseBackend) { @@ -365,7 +372,7 @@ async function allocateOrReuseLease( runId: state.runId, leaseBackend, ...connection, - ttlMs: policy.ttlMs(state), + ttlMs: policy.ttlMs(state, env), }); if (existing) return { lease: existing, acquired: false }; } @@ -386,7 +393,7 @@ async function allocateOrReuseLease( leaseBackend, ...connection, ...(allocateBySpec ? { deviceKey: undefined } : {}), - ttlMs: policy.ttlMs(state), + ttlMs: policy.ttlMs(state, env), ...providerFlags, platform: state.platform ?? flags.platform, target: state.target ?? flags.target, diff --git a/src/cli/commands/connection-plugin-admission.test.ts b/src/cli/commands/connection-plugin-admission.test.ts new file mode 100644 index 0000000000..47d00a1e63 --- /dev/null +++ b/src/cli/commands/connection-plugin-admission.test.ts @@ -0,0 +1,172 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { afterEach, test, vi } from 'vitest'; +import { runCli } from '../../cli.ts'; +import { runCliCapture } from '../../__tests__/cli-capture.ts'; +import { + hashRemoteConfigFile, + readRemoteConnectionState, + writeRemoteConnectionState, +} from '@agent-device/remote/remote-connection-state'; +import { + beginStdoutCapture, + pluginHome, + selectV2Plugin, + v2RegistrationSource, +} from '@agent-device/test-kit'; + +const provider = 'browserstack'; +const packageName = '@agent-device/browserstack'; +const capabilities = { + leaseKind: 'direct-device-provider', + requiresAppAttachment: false, + requiresRemoteDaemon: false, + supportsArtifacts: false, + supportsDeferredAppSelection: false, + supportsDirectPortReverse: false, + usesCloudWebDriverLease: true, +}; + +afterEach(() => vi.unstubAllEnvs()); + +function fixture(home: string, leaseProvider = provider) { + const stateDir = path.join(home, 'state'); + const remoteConfigPath = path.join(home, 'remote.json'); + fs.writeFileSync( + remoteConfigPath, + JSON.stringify({ + tenant: 'team', + runId: 'run-1', + leaseProvider, + leaseBackend: 'android-instance', + platform: 'android', + ...(leaseProvider === 'ordinary-remote' + ? { daemonBaseUrl: 'https://daemon.example.test' } + : {}), + }), + ); + return { stateDir, remoteConfigPath }; +} + +function seedState(f: ReturnType, leaseProvider = provider) { + const now = new Date().toISOString(); + writeRemoteConnectionState({ + stateDir: f.stateDir, + state: { + version: 1, + session: 'default', + remoteConfigPath: f.remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(f.remoteConfigPath), + tenant: 'team', + runId: 'run-1', + leaseProvider, + leaseBackend: 'android-instance', + platform: 'android', + connectedAt: now, + updatedAt: now, + }, + }); +} + +test.each(['missing', 'failed'] as const)( + 'routed %s vetted plugin fails before capability-based actions', + async (kind) => { + const { home, env } = pluginHome(); + if (kind === 'failed') + selectV2Plugin(home, packageName, 'throw new Error("registration failed")'); + const f = fixture(home); + const opts = { cwd: home, env: { ...env, AGENT_DEVICE_SESSION: 'default' } }; + const expected = kind === 'missing' ? 'plugin-not-installed' : 'plugin-unavailable'; + const connect = await runCliCapture( + ['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'], + opts, + ); + seedState(f); + const status = await runCliCapture( + ['connection', 'status', '--state-dir', f.stateDir, '--json'], + opts, + ); + const snapshot = await runCliCapture( + ['snapshot', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'], + opts, + ); + const disconnected = await runCliCapture( + ['disconnect', '--state-dir', f.stateDir, '--json'], + opts, + ); + assert.equal(disconnected.code, null); + assert.equal(readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' }), null); + for (const result of [connect, status, snapshot]) { + const parsed = JSON.parse(result.stdout); + assert.equal(result.code, 1, result.stdout); + assert.equal(parsed.error?.code, 'UNSUPPORTED_OPERATION', result.stdout); + assert.equal(parsed.error?.details?.reason, expected, result.stdout); + assert.deepEqual(result.calls, []); + assert.doesNotMatch(result.stdout, /install-from-source|leaseId.*pending/); + } + }, +); + +test('a generic remote profile remains connectable without a plugin', async () => { + const { home, env } = pluginHome(); + const f = fixture(home, 'ordinary-remote'); + const result = await runCliCapture( + ['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'], + { cwd: home, env: { ...env, AGENT_DEVICE_SESSION: 'default' } }, + ); + assert.equal(result.code, null); + assert.equal( + readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' })?.leaseProvider, + 'ordinary-remote', + ); +}); + +test('routed status uses capabilities from the supplied host store rather than the process store', async () => { + const { home } = pluginHome(); + const ambient = pluginHome(); + vi.stubEnv('AGENT_DEVICE_HOME', ambient.home); + selectV2Plugin( + home, + packageName, + v2RegistrationSource(provider, { + extra: `connection: { capabilities: ${JSON.stringify(capabilities)}, resolve() {}, verify() { return { provider: 'browserstack', service: 'BrowserStack', verificationMessage: 'verified' }; } },`, + }), + ); + const f = fixture(home); + const capture = beginStdoutCapture(); + const sendToDaemon = vi.fn(async () => { + throw new Error('unexpected daemon access'); + }); + try { + const suppliedHost = { + cwd: home, + env: { + AGENT_DEVICE_HOME: home, + AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1', + AGENT_DEVICE_SESSION: 'default', + }, + }; + await runCli( + ['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir], + { sendToDaemon }, + suppliedHost, + ); + assert.equal( + readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' })?.leaseProvider, + provider, + ); + const statusOutputStart = capture.read().length; + await runCli( + ['connection', 'status', '--state-dir', f.stateDir], + { sendToDaemon }, + suppliedHost, + ); + const statusOutput = capture.read().slice(statusOutputStart); + assert.match(statusOutput, /The first device command shown below will allocate one/); + assert.doesNotMatch(statusOutput, /install-from-source/); + assert.equal(sendToDaemon.mock.calls.length, 0); + } finally { + capture.restore(); + } +}); diff --git a/src/cli/commands/connection-plugin-guidance.test.ts b/src/cli/commands/connection-plugin-guidance.test.ts index 1aac8399f3..04a66d8b42 100644 --- a/src/cli/commands/connection-plugin-guidance.test.ts +++ b/src/cli/commands/connection-plugin-guidance.test.ts @@ -1,9 +1,26 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; -import { test } from 'vitest'; +import { afterEach, test, vi } from 'vitest'; import { pluginHome, selectV2Plugin, v2RegistrationSource } from '@agent-device/test-kit'; +import { readVersion } from '@agent-device/host-kit/version'; import { runCliCapture } from '../../__tests__/cli-capture.ts'; +import { usageForCommand } from '../parser/args.ts'; + +vi.mock('@agent-device/host-kit/version', async (importOriginal) => { + const original = await importOriginal(); + return { ...original, readVersion: vi.fn(original.readVersion) }; +}); + +afterEach(() => { + // Restores the real reader this checkout's version reports, so no case hands its channel to + // the next one. + vi.mocked(readVersion).mockReset(); +}); + +// The release `scripts/release-version.mjs` stamps on the 0.22 source branch. Its provider plugins +// publish at the same version, and their `latest` tag stays the staged placeholder. +const NIGHTLY_0_22 = '0.22.0-nightly-0-22.20261118.187'; test('connect names a missing provider plugin and returns installation guidance before dispatch', async () => { const { home, env } = pluginHome(); @@ -26,6 +43,30 @@ test('connect names a missing provider plugin and returns installation guidance assert.match(error.hint, /If a local daemon is already running/); }); +test('connect browserstack without its plugin names the package, even with credentials set', async () => { + vi.mocked(readVersion).mockReturnValue('0.22.0-dev'); + const { home, env } = pluginHome(); + const result = await runCliCapture( + ['connect', 'browserstack', '--platform', 'android', '--session', 'checkout', '--json'], + { + cwd: home, + env: { ...env, BROWSERSTACK_USERNAME: 'user', BROWSERSTACK_ACCESS_KEY: 'key' }, + stateDirPrefix: 'connect-missing-browserstack-', + }, + ); + assert.equal(result.code, 1); + assert.deepEqual(result.calls, []); + const { error } = JSON.parse(result.stdout); + assert.equal(error.code, 'UNSUPPORTED_OPERATION'); + assert.deepEqual(error.details, { + reason: 'plugin-not-installed', + provider: 'browserstack', + package: '@agent-device/browserstack', + installCommand: 'agent-device plugins add @agent-device/browserstack@nightly-0.22', + }); + assert.match(error.hint, /agent-device plugins add @agent-device\/browserstack/); +}); + test('connect prints installation guidance without JSON', async () => { const { home, env } = pluginHome(); const result = await runCliCapture(['connect', 'testmu', '--session', 'ci'], { @@ -90,6 +131,74 @@ test('connect does not call a selected plugin missing when it has no connection assert.equal(JSON.parse(result.stdout).error.details.reason, 'plugin-unavailable'); }); +// A channel plugin's `latest` tag is the staged placeholder, so an unversioned selector installs a +// package that exports no factory and the plugin manager refuses it as `incompatible_plugin`. The +// guidance has to name the release built with the running core. +test('a 0.22 nightly core prescribes the matching channel plugin release', async () => { + vi.mocked(readVersion).mockReturnValue(NIGHTLY_0_22); + const { home, env } = pluginHome(); + const result = await runCliCapture( + ['connect', 'browserstack', '--platform', 'android', '--session', 'checkout', '--json'], + { cwd: home, env, stateDirPrefix: 'connect-nightly-browserstack-' }, + ); + assert.equal(result.code, 1); + assert.deepEqual(result.calls, []); + const { error } = JSON.parse(result.stdout); + assert.deepEqual(error.details, { + reason: 'plugin-not-installed', + provider: 'browserstack', + package: '@agent-device/browserstack', + installCommand: `agent-device plugins add @agent-device/browserstack@${NIGHTLY_0_22}`, + }); + assert.match(error.hint, new RegExp(`plugins add @agent-device/browserstack@${NIGHTLY_0_22}`)); + assert.match(error.hint, /If a local daemon is already running/); + const help = await usageForCommand('remote'); + assert.ok(help?.includes(`${error.details.installCommand}\n`)); +}); + +test('a main-channel 0.22 nightly repairs a failed BrowserStack selection with the matching release', async () => { + const version = '0.22.0-nightly.20261118.186'; + vi.mocked(readVersion).mockReturnValue(version); + const { home, env } = pluginHome(); + selectV2Plugin(home, '@agent-device/browserstack', 'throw new Error("Plugin failed to load.");'); + const result = await runCliCapture( + ['connect', 'browserstack', '--platform', 'android', '--session', 'checkout', '--json'], + { cwd: home, env, stateDirPrefix: 'connect-nightly-broken-browserstack-' }, + ); + assert.equal(result.code, 1); + assert.deepEqual(result.calls, []); + const { error } = JSON.parse(result.stdout); + assert.equal(error.details.reason, 'plugin-unavailable'); + assert.ok(error.hint.includes(`plugins add @agent-device/browserstack@${version}`)); +}); + +test('a stable core prescribes the plain package for the same plugin', async () => { + vi.mocked(readVersion).mockReturnValue('0.22.0'); + const { home, env } = pluginHome(); + const result = await runCliCapture( + ['connect', 'browserstack', '--platform', 'android', '--session', 'checkout', '--json'], + { cwd: home, env, stateDirPrefix: 'connect-stable-browserstack-' }, + ); + assert.equal(result.code, 1); + const { error } = JSON.parse(result.stdout); + assert.equal(error.details.installCommand, 'agent-device plugins add @agent-device/browserstack'); + const help = await usageForCommand('remote'); + assert.ok(help?.includes(`${error.details.installCommand}\n`)); +}); + +test('a 0.22 nightly core still prescribes the plain package for a full-channel plugin', async () => { + vi.mocked(readVersion).mockReturnValue(NIGHTLY_0_22); + const { home, env } = pluginHome(); + const result = await runCliCapture( + ['connect', 'testmu', '--platform', 'android', '--session', 'checkout', '--json'], + { cwd: home, env, stateDirPrefix: 'connect-nightly-testmu-' }, + ); + assert.equal(result.code, 1); + assert.deepEqual(result.calls, []); + const { error } = JSON.parse(result.stdout); + assert.equal(error.details.installCommand, 'agent-device plugins add @agent-device/testmu'); +}); + test('connect reports an unreadable plugin selection instead of prescribing a new installation', async () => { const { home, env } = pluginHome(); fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify({ plugins: [] })); diff --git a/src/cli/commands/connection-presentation.test.ts b/src/cli/commands/connection-presentation.test.ts new file mode 100644 index 0000000000..ae8341bb5d --- /dev/null +++ b/src/cli/commands/connection-presentation.test.ts @@ -0,0 +1,34 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import type { RemoteConnectionState } from '@agent-device/remote/remote-connection-state'; +import { presentConnectReadiness } from './connection-presentation.ts'; + +test('connect guides a deferred device without an app to install a local file in its session', () => { + const state: RemoteConnectionState = { + version: 1, + session: 'checkout', + tenant: 'mobile', + runId: 'local', + platform: 'android', + remoteConfigPath: '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/workspace/remote.json', + remoteConfigHash: 'fixture', + connectedAt: '2026-11-18T00:00:00Z', + updatedAt: '2026-11-18T00:00:00Z', + }; + const readiness = presentConnectReadiness( + state, + { + provider: 'fixture-provider', + service: 'Fixture Provider', + verificationMessage: 'Credentials verified.', + device: { status: 'deferred', platform: 'android' }, + app: { status: 'missing' }, + }, + {}, + ); + + assert.deepEqual(readiness.nextSteps, [ + 'agent-device install --session checkout', + 'agent-device open --relaunch --session checkout', + ]); +}); diff --git a/src/cli/commands/connection-presentation.ts b/src/cli/commands/connection-presentation.ts index c46349794f..b93aa3cc81 100644 --- a/src/cli/commands/connection-presentation.ts +++ b/src/cli/commands/connection-presentation.ts @@ -31,15 +31,16 @@ export type PreviousLeaseReleaseNotice = { export function buildLeasePreparationNotice( state: RemoteConnectionState, - verification?: ConnectVerification, + verification: ConnectVerification | undefined, + env: NodeJS.ProcessEnv, ): LeasePreparationNotice | undefined { if (state.leaseId) return undefined; - const capabilities = connectionProviderCapabilities(state.leaseProvider); + const capabilities = connectionProviderCapabilities(state.leaseProvider, env); const leaseKind = capabilities.leaseKind; if (leaseKind === 'proxy') { return { status: 'deferred', - nextSteps: buildConnectWorkflow(state, verification).nextSteps, + nextSteps: buildConnectWorkflow(state, verification, env).nextSteps, message: 'No live device session has been created. Run devices to inspect inventory without allocating, then open when ready.', }; @@ -47,7 +48,7 @@ export function buildLeasePreparationNotice( if (capabilities.supportsDeferredAppSelection) { return { status: 'deferred', - nextSteps: buildConnectWorkflow(state, verification).nextSteps, + nextSteps: buildConnectWorkflow(state, verification, env).nextSteps, message: 'No live device session has been created. Run apps to inspect uploaded assets without allocating; open creates the instance.', }; @@ -55,7 +56,7 @@ export function buildLeasePreparationNotice( if (leaseKind === 'direct-device-provider') { return { status: 'deferred', - nextSteps: buildConnectWorkflow(state, verification).nextSteps, + nextSteps: buildConnectWorkflow(state, verification, env).nextSteps, message: 'No live device session has been created. The first device command shown below will allocate one.', }; @@ -81,13 +82,14 @@ export function buildLeasePreparationNotice( export function presentConnectReadiness( state: RemoteConnectionState, verification: ConnectVerification, + env: NodeJS.ProcessEnv, ): ConnectReadiness { return { ...verification, preparationMessage: - buildLeasePreparationNotice(state, verification)?.message ?? + buildLeasePreparationNotice(state, verification, env)?.message ?? 'No live device session has been created.', - ...buildConnectWorkflow(state, verification), + ...buildConnectWorkflow(state, verification, env), }; } @@ -96,10 +98,11 @@ export function renderConnectSuccess(options: { readiness?: ConnectReadiness; runtimePreparation?: RuntimePreparationNotice; previousLeaseNotice?: PreviousLeaseReleaseNotice; + env: NodeJS.ProcessEnv; }): string { - const { state, readiness, runtimePreparation, previousLeaseNotice } = options; + const { state, readiness, runtimePreparation, previousLeaseNotice, env } = options; if (!readiness) { - const leasePreparation = buildLeasePreparationNotice(state); + const leasePreparation = buildLeasePreparationNotice(state, undefined, env); return [ `Configured remote session "${state.session}" tenant "${state.tenant}" run "${state.runId}"${state.leaseId ? ` lease ${state.leaseId}` : ''}.`, leasePreparation?.message, @@ -118,7 +121,7 @@ export function renderConnectSuccess(options: { lines.push(`Project: ${readiness.project.name ?? readiness.project.reference} — verified`); } if (readiness.device) lines.push(renderDevice(readiness.device)); - if (readiness.app) lines.push(renderApp(state, readiness.app)); + if (readiness.app) lines.push(renderApp(state, readiness.app, env)); lines.push(readiness.preparationMessage); lines.push('Next:'); lines.push(...readiness.nextSteps.map((step) => ` ${step}`)); @@ -133,9 +136,10 @@ export function serializeConnectionState(options: { runtimePreparation?: RuntimePreparationNotice; readiness?: ConnectReadiness; previousLeaseNotice?: PreviousLeaseReleaseNotice; + env: NodeJS.ProcessEnv; }): Record { - const { state, runtimePreparation, readiness, previousLeaseNotice } = options; - const leasePreparation = buildLeasePreparationNotice(state, readiness); + const { state, runtimePreparation, readiness, previousLeaseNotice, env } = options; + const leasePreparation = buildLeasePreparationNotice(state, readiness, env); return { connected: true, session: state.session, @@ -212,9 +216,10 @@ function renderDevice(device: NonNullable): string { function renderApp( state: RemoteConnectionState, app: NonNullable, + env: NodeJS.ProcessEnv, ): string { if (app.status === 'missing') { - return `App: ${missingAppLabel(state)} — ${app.message ?? 'Install or attach an app before open.'}`; + return `App: ${missingAppLabel(state, env)} — ${app.message ?? 'Install or attach an app before open.'}`; } const label = app.name ?? app.reference ?? 'configured app'; const suffix = app.status === 'verified' ? 'verified' : (app.message ?? 'configured'); @@ -223,17 +228,19 @@ function renderApp( function buildConnectWorkflow( state: RemoteConnectionState, - verification?: ConnectVerification, + verification: ConnectVerification | undefined, + env: NodeJS.ProcessEnv, ): Pick { - const workflow = buildUnscopedConnectWorkflow(state, verification); + const workflow = buildUnscopedConnectWorkflow(state, verification, env); return { ...workflow, nextSteps: scopeNextSteps(state, workflow.nextSteps) }; } function buildUnscopedConnectWorkflow( state: RemoteConnectionState, - verification?: ConnectVerification, + verification: ConnectVerification | undefined, + env: NodeJS.ProcessEnv, ): Pick { - const capabilities = connectionProviderCapabilities(state.leaseProvider); + const capabilities = connectionProviderCapabilities(state.leaseProvider, env); const leaseKind = capabilities.leaseKind; if (leaseKind === 'proxy') { return { @@ -246,9 +253,16 @@ function buildUnscopedConnectWorkflow( if (!verification && leaseKind === 'direct-device-provider') { return { nextSteps: defaultDirectProviderLifecycle() }; } - if (connectionProviderCapabilities(verification?.provider).supportsDeferredAppSelection) { + if (connectionProviderCapabilities(verification?.provider, env).supportsDeferredAppSelection) { return { nextSteps: ['agent-device apps', 'agent-device open '], + ...(requiresInstall(verification) + ? { + notes: [ + `For a local app file, run ${scopeNextSteps(state, installThenOpenWorkflow(state)).join(' then ')}.`, + ], + } + : {}), }; } const appMissing = verification?.app?.status === 'missing'; @@ -256,7 +270,7 @@ function buildUnscopedConnectWorkflow( nextSteps: requiresInstall(verification) ? installThenOpenWorkflow(state) : [...missingAttachedAppRecovery(verification), ...openWorkflow(state).nextSteps], - ...(supportsProviderArtifacts(verification) + ...(supportsProviderArtifacts(verification, env) ? { notes: providerArtifactNotes(state, !appMissing) } : {}), }; @@ -266,8 +280,11 @@ function requiresInstall(verification?: ConnectVerification): boolean { return verification?.app?.status === 'missing' && verification.device?.status === 'deferred'; } -function supportsProviderArtifacts(verification?: ConnectVerification): boolean { - return connectionProviderCapabilities(verification?.provider).supportsArtifacts; +function supportsProviderArtifacts( + verification: ConnectVerification | undefined, + env: NodeJS.ProcessEnv, +): boolean { + return connectionProviderCapabilities(verification?.provider, env).supportsArtifacts; } function missingAttachedAppRecovery(verification?: ConnectVerification): string[] { @@ -303,10 +320,7 @@ function openWorkflow(state: RemoteConnectionState): Pick`, - `agent-device open ${appId} --relaunch`, - ]; + return [`agent-device install ${appId} `, `agent-device open ${appId} --relaunch`]; } function connectionVerificationStatus( @@ -345,8 +359,8 @@ function appIdPlaceholder(platform: RemoteConnectionState['platform']): string { return platform === 'ios' ? '' : ''; } -function missingAppLabel(state: RemoteConnectionState): string { - const capabilities = connectionProviderCapabilities(state.leaseProvider); +function missingAppLabel(state: RemoteConnectionState, env: NodeJS.ProcessEnv): string { + const capabilities = connectionProviderCapabilities(state.leaseProvider, env); if (capabilities.requiresAppAttachment) return 'not attached'; if (capabilities.supportsDeferredAppSelection) { return 'not installed yet'; diff --git a/src/cli/commands/connection-runtime-direct-host.test.ts b/src/cli/commands/connection-runtime-direct-host.test.ts new file mode 100644 index 0000000000..01c6609ffd --- /dev/null +++ b/src/cli/commands/connection-runtime-direct-host.test.ts @@ -0,0 +1,87 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { afterEach, test, vi } from 'vitest'; +import { createAgentDeviceClient } from '@agent-device/client'; +import { REMOTE_LEASE_IDLE_TTL_MS } from '@agent-device/contracts/lease-scope'; +import { pluginHome, selectV2Plugin, v2RegistrationSource } from '@agent-device/test-kit'; +import { materializeRemoteConnectionForCommand } from './connection-runtime.ts'; + +const capabilities = { + leaseKind: 'direct-device-provider', + requiresAppAttachment: false, + requiresRemoteDaemon: false, + supportsArtifacts: true, + supportsDeferredAppSelection: false, + supportsDirectPortReverse: false, + usesCloudWebDriverLease: true, +}; + +afterEach(() => vi.unstubAllEnvs()); + +test('direct materialization uses supplied host store without an ambient command host', async () => { + const { home } = pluginHome(); + const ambient = pluginHome(); + vi.stubEnv('AGENT_DEVICE_HOME', ambient.home); + selectV2Plugin( + home, + 'example-v2', + v2RegistrationSource('example-v2', { + extra: `connection: { capabilities: ${JSON.stringify(capabilities)}, resolve() {}, verify() {} },`, + }), + ); + const remoteConfigPath = path.join(home, 'remote.json'); + fs.writeFileSync( + remoteConfigPath, + JSON.stringify({ + tenant: 'team', + runId: 'run-1', + leaseProvider: 'example-v2', + leaseBackend: 'android-instance', + platform: 'android', + }), + ); + const host = { cwd: home, env: { AGENT_DEVICE_HOME: home } }; + const requests: Array<{ command: string; meta?: { leaseTtlMs?: number } }> = []; + const client = createAgentDeviceClient( + {}, + { + host, + transport: async (request) => { + requests.push(request); + if (request.command === 'lease_allocate') + return { + ok: true, + data: { + lease: { + leaseId: 'lease-1', + tenantId: 'team', + runId: 'run-1', + backend: 'android-instance', + created: true, + }, + }, + }; + throw new Error(`unexpected daemon request: ${request.command}`); + }, + }, + ); + const result = await materializeRemoteConnectionForCommand({ + host, + command: 'snapshot', + client, + flags: { + json: true, + help: false, + version: false, + stateDir: path.join(home, 'state'), + remoteConfig: remoteConfigPath, + session: 'plugin-direct', + platform: 'android', + }, + }); + assert.equal(result.flags.leaseId, 'lease-1'); + assert.equal(requests.length, 1); + assert.equal(requests[0]?.command, 'lease_allocate'); + assert.equal(requests[0]?.meta?.leaseTtlMs, REMOTE_LEASE_IDLE_TTL_MS); +}); diff --git a/src/cli/commands/connection-runtime-provider.test.ts b/src/cli/commands/connection-runtime-provider.test.ts new file mode 100644 index 0000000000..3f75b9bedf --- /dev/null +++ b/src/cli/commands/connection-runtime-provider.test.ts @@ -0,0 +1,92 @@ +import { afterEach, test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import browserstack from '@agent-device/browserstack'; +import { pluginHome, selectV2Plugin, v2RegistrationSource } from '@agent-device/test-kit'; +import { + connectionWorkspace, + createTestClient, + recordedLeaseAllocate, + seedConnectionState, +} from '../../__tests__/remote-connection.fixtures.ts'; +import { materializeRemoteConnectionForCommand } from '../../__tests__/test-utils/host-bound-commands.ts'; + +afterEach(() => vi.unstubAllEnvs()); + +test('deferred provider materialization forwards provider profile fields to lease allocation', async () => { + const { home } = pluginHome(); + vi.stubEnv('AGENT_DEVICE_HOME', home); + selectV2Plugin( + home, + '@agent-device/browserstack', + v2RegistrationSource('browserstack', { + extra: `connection: { capabilities: ${JSON.stringify(browserstack().connection?.capabilities)}, resolve() {}, verify() {} },`, + }), + ); + const { tempRoot, stateDir } = connectionWorkspace('agent-device-provider-lease-flags-'); + const remoteConfigPath = path.join(tempRoot, 'browserstack.json'); + fs.writeFileSync( + remoteConfigPath, + JSON.stringify({ + tenant: 'browserstack', + runId: 'browserstack-run', + leaseProvider: 'browserstack', + leaseBackend: 'android-instance', + platform: 'android', + device: 'Google Pixel 8', + providerOsVersion: '14.0', + providerApp: '/tmp/WikipediaSample.apk', + providerProject: 'agent-device', + providerBuild: 'live-smoke', + }), + ); + seedConnectionState({ + stateDir, + state: { + session: 'adc-browserstack', + remoteConfigPath, + tenant: 'browserstack', + runId: 'browserstack-run', + leaseBackend: 'android-instance', + leaseProvider: 'browserstack', + platform: 'android', + }, + }); + const allocate = recordedLeaseAllocate({ + leaseId: 'lease-browserstack', + backend: 'android-instance', + }); + + const materialized = await materializeRemoteConnectionForCommand({ + command: 'open', + flags: { + json: true, + help: false, + version: false, + stateDir, + remoteConfig: remoteConfigPath, + tenant: 'browserstack', + runId: 'browserstack-run', + session: 'adc-browserstack', + leaseBackend: 'android-instance', + platform: 'android', + device: 'Google Pixel 8', + providerOsVersion: '14.0', + providerApp: '/tmp/WikipediaSample.apk', + providerProject: 'agent-device', + providerBuild: 'live-smoke', + }, + client: createTestClient({ allocate: allocate.stub }), + }); + + assert.equal(materialized.flags.leaseId, 'lease-browserstack'); + assert.equal(allocate.request?.platform, 'android'); + assert.equal(allocate.request?.device, 'Google Pixel 8'); + assert.equal(allocate.request?.providerApp, '/tmp/WikipediaSample.apk'); + assert.equal(allocate.request?.providerOsVersion, '14.0'); + assert.equal(allocate.request?.providerProject, 'agent-device'); + assert.equal(allocate.request?.providerBuild, 'live-smoke'); + + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); diff --git a/src/cli/commands/connection-runtime.ts b/src/cli/commands/connection-runtime.ts index 0c687dc05c..4285f74e2c 100644 --- a/src/cli/commands/connection-runtime.ts +++ b/src/cli/commands/connection-runtime.ts @@ -85,13 +85,14 @@ export async function materializeRemoteConnectionForCommand(options: { ); } - await primeProviderConnection(providerOf(existingState, remoteConfig.profile)); + await primeProviderConnection(providerOf(existingState, remoteConfig.profile), host.env); const state = existingState ?? createRemoteConnectionStateFromFlags( mergedFlags, remoteConfig.resolvedPath, remoteConfig.profile, + host.env, ); const nextFlags = { ...mergedFlags, session: state.session }; let nextRuntime = selectCompatibleRuntime(state.runtime, nextFlags.platform) ?? options.runtime; @@ -109,6 +110,7 @@ export async function materializeRemoteConnectionForCommand(options: { nextFlags, positionals: options.positionals, leaseLedger, + env: host.env, }); nextState = acquired.state; changed = changed || acquired.changed; @@ -194,7 +196,8 @@ function createRemoteConnectionStateFromFlags( remoteConfigPath: string, profile: Partial< Pick - > = {}, + >, + env: NodeJS.ProcessEnv, ): RemoteConnectionState { const session = flags.session ?? 'default'; const scope = sessionLeaseScope( @@ -218,7 +221,7 @@ function createRemoteConnectionStateFromFlags( } if ( !flags.daemonBaseUrl && - connectionProviderCapabilities(profile.leaseProvider).requiresRemoteDaemon + connectionProviderCapabilities(profile.leaseProvider, env).requiresRemoteDaemon ) { throw new AppError( 'INVALID_ARGS', diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 9ebcafac2a..a17cc42c66 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -81,7 +81,7 @@ export const connectCommand: ClientCommandHandler = async ({ resolved, host, ); - const scope = readRequiredConnectScope(connectFlags, connectionMetadata); + const scope = readRequiredConnectScope(connectFlags, connectionMetadata, host.env); const context = resolveConnectContext({ stateDir, flags: connectFlags, @@ -96,7 +96,7 @@ export const connectCommand: ClientCommandHandler = async ({ connection: connectionMetadata, daemon: context.daemon, }); - const verification = await verifyResolvedConnectProvider(resolved, host.env); + const verification = await verifyResolvedConnectProvider(resolved, host); const state = buildConnectedState({ flags: connectFlags, scope, @@ -113,12 +113,25 @@ export const connectCommand: ClientCommandHandler = async ({ host, ); const runtimePreparation = buildRuntimePreparationNotice(connectFlags, state, host); - const readiness = presentConnectReadiness(state, verification); + const readiness = presentConnectReadiness(state, verification, host.env); await writeCommandOutput( connectFlags, - serializeConnectionState({ state, runtimePreparation, readiness, previousLeaseNotice }), - () => renderConnectSuccess({ state, runtimePreparation, readiness, previousLeaseNotice }), + serializeConnectionState({ + state, + runtimePreparation, + readiness, + previousLeaseNotice, + env: host.env, + }), + () => + renderConnectSuccess({ + state, + runtimePreparation, + readiness, + previousLeaseNotice, + env: host.env, + }), ); return true; }; @@ -134,6 +147,7 @@ function assertConnectProviderUsage(provider: ConnectProvider | undefined, flags function readRequiredConnectScope( flags: CliFlags, connectionMetadata: RemoteConnectionRequestMetadata | undefined, + env: NodeJS.ProcessEnv, ): { tenant: string; runId: string } { if (!flags.tenant) { throw new AppError( @@ -149,7 +163,7 @@ function readRequiredConnectScope( } if ( !flags.daemonBaseUrl && - connectionProviderCapabilities(connectionMetadata?.leaseProvider).requiresRemoteDaemon + connectionProviderCapabilities(connectionMetadata?.leaseProvider, env).requiresRemoteDaemon ) { throw new AppError( 'INVALID_ARGS', @@ -395,20 +409,23 @@ export const connectionCommand: ClientCommandHandler = async ({ positionals, fla await writeNoRemoteConnectionOutput(flags, session); return true; } - await primeProviderConnection(state.leaseProvider); - const leasePreparation = buildLeasePreparationNotice(state); + await primeProviderConnection(state.leaseProvider, host.env); + const leasePreparation = buildLeasePreparationNotice(state, undefined, host.env); const runtimePreparation = buildRuntimePreparationNoticeFromState(state, host); - await writeCommandOutput(flags, serializeConnectionState({ state, runtimePreparation }), () => - [ - `Configured remote session "${state.session}".`, - `tenant=${state.tenant} runId=${state.runId} leaseId=${state.leaseId ?? 'pending'} backend=${state.leaseBackend ?? 'pending'}`, - `remoteConfig=${state.remoteConfigPath}`, - state.runtime ? 'metro=prepared' : 'metro=not-prepared', - leasePreparation?.message, - runtimePreparation?.message, - ] - .filter((line): line is string => Boolean(line)) - .join('\n'), + await writeCommandOutput( + flags, + serializeConnectionState({ state, runtimePreparation, env: host.env }), + () => + [ + `Configured remote session "${state.session}".`, + `tenant=${state.tenant} runId=${state.runId} leaseId=${state.leaseId ?? 'pending'} backend=${state.leaseBackend ?? 'pending'}`, + `remoteConfig=${state.remoteConfigPath}`, + state.runtime ? 'metro=prepared' : 'metro=not-prepared', + leasePreparation?.message, + runtimePreparation?.message, + ] + .filter((line): line is string => Boolean(line)) + .join('\n'), ); return true; }; diff --git a/src/cli/commands/daemon.ts b/src/cli/commands/daemon.ts index 5ffc31c066..3dbbf37c67 100644 --- a/src/cli/commands/daemon.ts +++ b/src/cli/commands/daemon.ts @@ -135,7 +135,7 @@ function renderDaemonStatus( plugin.state === 'active' ? 'active' : `failed: ${plugin.error?.message ?? 'unknown'}`; - return ` ${plugin.provider ?? '(unknown provider)'} [${plugin.source}] ${origin} - ${outcome}`; + return ` ${plugin.provider ?? (plugin.backend ? `replay backend ${plugin.backend}` : '(unknown plugin)')} [${plugin.source}] ${origin} - ${outcome}`; }), ]), ].join('\n'); diff --git a/src/cli/commands/plugins.ts b/src/cli/commands/plugins.ts index 284a0f840f..e3ee13d323 100644 --- a/src/cli/commands/plugins.ts +++ b/src/cli/commands/plugins.ts @@ -1,3 +1,4 @@ +import path from 'node:path'; import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { readPluginInventory } from '@agent-device/contracts/plugin-inventory'; import { @@ -5,12 +6,12 @@ import { readDaemonStatus, } from '@agent-device/daemon-contracts/daemon-registration'; import { AppError } from '@agent-device/kernel/errors'; -import { changePlugin, listPlugins } from '@agent-device/plugins/store'; +import { addPluginArtifact, changePlugin, listPlugins } from '@agent-device/plugins/store'; import { BUILTIN_PROVIDER_IDS } from '../../builtin-provider-ids.ts'; import { writeCommandOutput } from './shared.ts'; import type { ClientCommandHandler } from './router-types.ts'; -export const pluginsCommand: ClientCommandHandler = async ({ positionals, flags }) => { +export const pluginsCommand: ClientCommandHandler = async ({ host, positionals, flags }) => { const [action = 'list', name, extra] = positionals; if ( extra || @@ -19,23 +20,22 @@ export const pluginsCommand: ClientCommandHandler = async ({ positionals, flags ) { throw new AppError( 'INVALID_ARGS', - 'Use plugins list, add , update , or remove ', + 'Use plugins list, add , update , or remove ', ); } - if (action !== 'list' && name) { - await changePlugin( - action as 'add' | 'update' | 'remove', - name, - process.env, - BUILTIN_PROVIDER_IDS, - ); + const artifact = + action === 'add' && name && (path.isAbsolute(name) || /^\.{1,2}[\\/]/.test(name)) + ? await addPluginArtifact(name, host) + : undefined; + if (action !== 'list' && !artifact && name) { + await changePlugin(action as 'add' | 'update' | 'remove', name, host.env); } - const plugins = await listPlugins(process.env, BUILTIN_PROVIDER_IDS); - const daemon = readDaemonStatus(resolveDaemonPaths(flags.stateDir)); + const plugins = artifact ? [] : await listPlugins(host.env, BUILTIN_PROVIDER_IDS); + const daemon = readDaemonStatus(resolveDaemonPaths(flags.stateDir, host)); const daemonPlugins = readPluginInventory(daemon.plugins); const failedInDaemon = daemonPlugins.filter(({ state }) => state === 'failed'); const data = { - plugins, + ...(artifact ? { artifact: { ...artifact, compatibility: 'unchecked' } } : { plugins }), ...(daemon.state === 'running' ? { daemon: { pid: daemon.pid, stateDir: daemon.stateDir, plugins: daemonPlugins } } : {}), @@ -44,17 +44,21 @@ export const pluginsCommand: ClientCommandHandler = async ({ positionals, flags }; await writeCommandOutput(flags, data, () => [ - ...plugins.map((plugin) => - plugin.compatible - ? `${plugin.name}@${plugin.version} (${plugin.provider})` - : plugin.name === undefined - ? `Plugin config unavailable: ${plugin.error?.message}` - : `${plugin.name}: unavailable; run plugins update ${plugin.name} or plugins remove ${plugin.name}`, - ), + ...(artifact + ? [ + `${artifact.name}@${artifact.version}: installed; compatibility unchecked. Run agent-device plugins list.`, + ] + : plugins.map((plugin) => + plugin.compatible + ? `${plugin.name}@${plugin.version} (${plugin.provider ?? plugin.backend})` + : plugin.name === undefined + ? `Plugin config unavailable: ${plugin.error?.message}` + : `${plugin.name}: unavailable; run plugins update ${plugin.name} or plugins remove ${plugin.name}`, + )), ...(action !== 'list' ? ['Restart the local daemon after closing active sessions to use the changed plugin set.'] : []), - ...(plugins.length === 0 ? ['No provider plugins installed.'] : []), + ...(!artifact && plugins.length === 0 ? ['No provider plugins installed.'] : []), ...(isUnusableRecord(daemon) ? [ `The daemon record for ${daemon.stateDir} is ${daemon.state}, so its providers are unknown.`, diff --git a/src/cli/commands/replay.ts b/src/cli/commands/replay.ts index 96d8caf968..d4dcfa10a2 100644 --- a/src/cli/commands/replay.ts +++ b/src/cli/commands/replay.ts @@ -3,7 +3,6 @@ import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; import { parseReplayScriptDetailed, readReplayScriptMetadata } from '@agent-device/ad-script'; import { resolveUserPath } from '@agent-device/host-kit/file'; -import type { ReplayBackend } from '@agent-device/contracts/replay-backend'; import { writeCommandOutput } from './shared.ts'; import type { ClientCommandHandler } from './router-types.ts'; @@ -44,13 +43,14 @@ async function handleReplayExportCommand({ // `replay export` exports to Maestro, so the conversion goes through that backend's registry // entry rather than naming the engine package from the CLI (#3377). This handler is loaded // lazily by the router, and the engine sits one further thunk behind the backend. - const backend: ReplayBackend = await ( + const result = await ( await import('@agent-device/replay-port/replay-backend-registry') - ).getReplayBackend('maestro'); - const result = backend.exportReplayScript(parsed.actions, { - actionLines: parsed.actionLines, - metadata: readReplayScriptMetadata(script), - }); + ).withReplayBackend('maestro', host, (backend) => + backend.exportReplayScript(parsed.actions, { + actionLines: parsed.actionLines, + metadata: readReplayScriptMetadata(script), + }), + ); const outputPath = typeof flags.out === 'string' ? resolveUserPath(flags.out, { cwd: host.cwd }) : undefined; if (outputPath) { @@ -64,7 +64,7 @@ async function handleReplayExportCommand({ await writeCommandOutput( flags, { - format: backend.id, + format: 'maestro', sourcePath, ...(outputPath ? { path: outputPath } : { yaml: result.yaml }), warnings: result.warnings, diff --git a/src/cli/connection/connect-provider-adapters-aws-device-farm.test.ts b/src/cli/connection/connect-provider-adapters-aws-device-farm.test.ts new file mode 100644 index 0000000000..9347e75a66 --- /dev/null +++ b/src/cli/connection/connect-provider-adapters-aws-device-farm.test.ts @@ -0,0 +1,290 @@ +import { afterEach, beforeEach, test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { runCliCapture } from '../../__tests__/cli-capture.ts'; +import { + readActiveConnectionState, + type RemoteConnectionState, +} from '@agent-device/remote/remote-connection-state'; +import { AppError } from '@agent-device/kernel/errors'; +import { verifyAwsDeviceFarmConnection } from '@agent-device/aws-device-farm/connection-verification'; +import awsDeviceFarm from '@agent-device/aws-device-farm'; +import { resolveProviderPlugins } from '@agent-device/plugins/registry'; +import { + resolveConnectProviderProfile, + verifyResolvedConnectProvider, +} from './connect-provider-adapters.ts'; +import { + mkdtempForTestSync, + pluginHome, + selectV2Plugin, + v2RegistrationSource, + bindTestCommandHost, +} from '@agent-device/test-kit'; +import manifest from '@agent-device/aws-device-farm/package.json' with { type: 'json' }; +import type { PluginConnectionCallbacks } from '@agent-device/plugins/connection'; +import { connectWithGeneratedProviderProfile } from '../../__tests__/test-utils/connect-command.ts'; + +bindTestCommandHost(); + +vi.mock('@agent-device/aws-device-farm/connection-verification', () => ({ + verifyAwsDeviceFarmConnection: vi.fn(), +})); +vi.mock('@agent-device/plugins/load', () => ({ + withPluginConnection: async ( + _provider: string, + _builtinProviders: readonly string[], + _env: NodeJS.ProcessEnv, + runConnection: (connection: PluginConnectionCallbacks) => Promise, + ) => { + const { connections } = await resolveProviderPlugins([ + { source: 'store', package: manifest.name, load: () => awsDeviceFarm() }, + ]); + return await runConnection(connections.get('aws-device-farm')!); + }, +})); + +afterEach(() => { + vi.clearAllMocks(); + vi.unstubAllEnvs(); +}); + +const mockedVerifyAwsDeviceFarmConnection = vi.mocked(verifyAwsDeviceFarmConnection); + +test('connection verification carries the caller host to the provider command', async () => { + const cwd = fs.realpathSync(mkdtempForTestSync('connect-aws-host-')); + let observed: unknown; + mockedVerifyAwsDeviceFarmConnection.mockImplementationOnce(async (_options, run) => { + const result = await run(process.execPath, [ + '-e', + 'process.stdout.write(JSON.stringify([process.cwd(), process.env.CONNECT_HOST_VALUE]))', + ]); + observed = JSON.parse(result.stdout); + return { + provider: 'aws-device-farm', + service: 'AWS Device Farm', + verificationMessage: 'ok', + project: { reference: 'project' }, + device: { status: 'verified' }, + app: { status: 'missing' }, + }; + }); + await verifyResolvedConnectProvider( + { + provider: 'aws-device-farm', + remoteConfigPath: '/unused', + flags: { + json: false, + help: false, + version: false, + platform: 'ios', + awsProjectArn: 'project', + awsDeviceArn: 'device', + }, + }, + { cwd, env: { CONNECT_HOST_VALUE: 'supplied' } }, + ); + assert.deepEqual(observed, [cwd, 'supplied']); +}); + +let pluginHomeDir = ''; + +beforeEach(() => { + const { home } = pluginHome(); + pluginHomeDir = home; + // The store declares the plugin installed with AWS Device Farm's capabilities; the mocked loader + // above supplies the workspace factory those assertions exercise. + selectV2Plugin( + home, + manifest.name, + v2RegistrationSource('aws-device-farm', { + extra: `connection: { capabilities: ${JSON.stringify(awsDeviceFarm().connection?.capabilities)}, resolve() {}, verify() {} },`, + }), + ); + vi.stubEnv('AGENT_DEVICE_HOME', home); + mockedVerifyAwsDeviceFarmConnection.mockImplementation(async (options) => ({ + provider: 'aws-device-farm', + service: 'AWS Device Farm', + verificationMessage: 'Credentials, project, and device verified.', + project: { name: 'Agent Device', reference: options.projectArn }, + device: { + status: 'verified', + name: 'iPhone 15', + reference: options.deviceArn, + platform: options.platform, + osVersion: '17', + }, + app: { + status: 'missing', + message: + 'No app upload is attached; AWS Device Farm does not support install after allocation.', + }, + })); +}); + +test('connect aws-device-farm generates local provider profile from flags', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-aws-'); + const stateDir = path.join(tempRoot, '.state'); + + try { + await connectWithGeneratedProviderProfile({ + stateDir, + positionals: ['aws-device-farm'], + flags: { + platform: 'ios', + device: 'Apple iPhone 15', + awsProjectArn: 'arn:aws:devicefarm:us-west-2:123:project:project-a', + awsDeviceArn: 'arn:aws:devicefarm:us-west-2::device:device-a', + awsAppArn: 'arn:aws:devicefarm:us-west-2:123:upload:app-a', + awsInteractionMode: 'INTERACTIVE', + }, + }); + + const state = readRequiredActiveState(stateDir); + assert.equal(state.tenant, 'aws-device-farm'); + assert.equal(state.leaseProvider, 'aws-device-farm'); + assert.equal(state.daemon?.baseUrl, undefined); + assert.match(state.remoteConfigPath, /generated\/aws-device-farm-[a-f0-9]{16}\.json$/); + const generated = readGeneratedConfig(state.remoteConfigPath); + assert.equal(generated.awsProjectArn, 'arn:aws:devicefarm:us-west-2:123:project:project-a'); + assert.equal(generated.awsDeviceArn, 'arn:aws:devicefarm:us-west-2::device:device-a'); + assert.equal(generated.awsAppArn, 'arn:aws:devicefarm:us-west-2:123:upload:app-a'); + assert.equal(generated.awsRegion, 'us-west-2'); + assert.equal(generated.awsInteractionMode, 'INTERACTIVE'); + // The plugin verifies through the host command, and the profile carries the region its ARN names. + assert.equal(mockedVerifyAwsDeviceFarmConnection.mock.calls[0]?.[0].region, 'us-west-2'); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('connect aws-device-farm JSON exposes verification, device, app, live-session, and next-step state', async () => { + const result = await runCliCapture( + [ + 'connect', + 'aws-device-farm', + '--session=ci', + '--platform', + 'ios', + '--aws-project-arn', + 'project-arn', + '--aws-device-arn', + 'device-arn', + '--json', + ], + { + env: { AGENT_DEVICE_HOME: pluginHomeDir }, + stateDirPrefix: 'agent-device-connect-aws-output-', + }, + ); + + assert.equal(result.code, null); + const output = (JSON.parse(result.stdout) as { data: Record }).data; + assert.equal(output.verification.status, 'verified'); + assert.equal(output.device.name, 'iPhone 15'); + assert.equal(output.app.status, 'missing'); + assert.equal(output.liveSession.status, 'not-created'); + assert.deepEqual(output.nextSteps, [ + `agent-device connect aws-device-farm --platform ios --aws-project-arn project-arn --aws-device-arn device-arn --aws-app-arn --force --session ${output.session}`, + `agent-device open --relaunch --session ${output.session}`, + ]); + assert.deepEqual(output.leasePreparation.nextSteps, output.nextSteps); + assert.deepEqual(output.notes, [ + `After close, run agent-device artifacts --json --session ${output.session} for provider video and logs.`, + ]); +}); + +test('connect aws-device-farm rejects device-feature flags it does not read', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-aws-reject-'); + + try { + await assert.rejects( + resolveConnectProviderProfile({ + provider: 'aws-device-farm', + stateDir: path.join(tempRoot, '.state'), + cwd: tempRoot, + env: {}, + flags: { + json: false, + help: false, + version: false, + platform: 'android', + device: 'Google Pixel 8', + providerDeviceOrientation: 'portrait', + providerTimezone: 'New_York', + }, + }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + // Names every offending flag, and fires before the provider's own required-arg checks so + // the caller is told what is unsupported rather than what else is missing. + assert.equal(error.details?.provider, 'aws-device-farm'); + assert.deepEqual(error.details?.flags, [ + '--provider-device-orientation', + '--provider-timezone', + ]); + return true; + }, + ); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('connect aws-device-farm refuses --provider-device-type before saving a profile', async () => { + const tempRoot = mkdtempForTestSync('agent-device-connect-aws-device-type-'); + + try { + await assert.rejects( + resolveConnectProviderProfile({ + provider: 'aws-device-farm', + stateDir: path.join(tempRoot, '.state'), + cwd: tempRoot, + env: {}, + flags: { + json: false, + help: false, + version: false, + platform: 'android', + awsProjectArn: 'arn:aws:devicefarm:us-west-2:123:project/p', + awsDeviceArn: 'arn:aws:devicefarm:us-west-2::device/d', + providerDeviceType: 'real', + }, + }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + assert.match(error.message, /^--provider-device-type is not supported by /); + assert.equal(error.details?.provider, 'aws-device-farm'); + return true; + }, + ); + assert.equal(fs.existsSync(path.join(tempRoot, '.state')), false); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +function readGeneratedConfig(configPath: string): { + awsProjectArn?: string; + awsDeviceArn?: string; + awsAppArn?: string; + awsRegion?: string; + awsInteractionMode?: string; +} { + return JSON.parse(fs.readFileSync(configPath, 'utf8')) as { + awsProjectArn?: string; + awsDeviceArn?: string; + awsAppArn?: string; + awsRegion?: string; + awsInteractionMode?: string; + }; +} + +function readRequiredActiveState(stateDir: string): RemoteConnectionState { + const state = readActiveConnectionState({ stateDir }); + assert.ok(state); + return state; +} diff --git a/src/cli/connection/connect-provider-adapters.ts b/src/cli/connection/connect-provider-adapters.ts index 8ca1de5d20..2928340f66 100644 --- a/src/cli/connection/connect-provider-adapters.ts +++ b/src/cli/connection/connect-provider-adapters.ts @@ -6,7 +6,7 @@ import { readVersion } from '@agent-device/host-kit/version'; import { leaseBackendForPlatform } from '@agent-device/kernel/contracts'; import { AppError } from '@agent-device/kernel/errors'; import { resolveRemoteConfigProfile } from '@agent-device/remote/remote-config'; -import { type EnvMap } from '@agent-device/kernel/source-value'; +import { type EnvMap, type HostEnvironment } from '@agent-device/kernel/source-value'; import { resolveCloudConnectProfile } from './cloud-profile.ts'; import { resolveLimrunConnectProfile } from './limrun-profile.ts'; @@ -19,7 +19,6 @@ import { type ConnectProvider, } from './provider-policy.ts'; import { BUILTIN_PROVIDER_IDS } from '../../builtin-provider-ids.ts'; -import { bundledCloudWebDriverConnection } from '../../provider-webdriver.ts'; import { withPluginConnection } from '@agent-device/plugins/load'; import type { PluginConnectionCallbacks } from '@agent-device/plugins/connection'; import { readMetroProfileFields } from './profile-fields.ts'; @@ -86,16 +85,13 @@ function builtinConnectAdapter(provider: string): ConnectProviderAdapter | undef : undefined; } -/** Runs a provider's connection callbacks: a bundled provider in-process, otherwise its installed plugin. */ +/** Runs a provider's connection callbacks from its installed plugin. */ async function withProviderConnection( provider: string, env: EnvMap, run: (connection: PluginConnectionCallbacks) => Promise, ): Promise { - const bundled = bundledCloudWebDriverConnection(provider, env); - return bundled - ? await run(bundled) - : await withPluginConnection(provider, BUILTIN_PROVIDER_IDS, env, run); + return await withPluginConnection(provider, BUILTIN_PROVIDER_IDS, env, run); } export async function resolveConnectProviderProfile(options: { @@ -186,7 +182,7 @@ async function resolveProviderConnectionProfile( export async function verifyResolvedConnectProvider( resolved: ResolvedConnectProfile, - env: EnvMap, + host: HostEnvironment, ): Promise { if (!resolved.provider) { return { @@ -198,7 +194,8 @@ export async function verifyResolvedConnectProvider( } const context = { flags: resolved.flags, - env, + env: host.env, + cwd: host.cwd, }; const adapter = builtinConnectAdapter(resolved.provider); return adapter diff --git a/src/cli/connection/provider-policy.test.ts b/src/cli/connection/provider-policy.test.ts index b708979f2d..9fb147e326 100644 --- a/src/cli/connection/provider-policy.test.ts +++ b/src/cli/connection/provider-policy.test.ts @@ -1,23 +1,20 @@ import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; import { expect, test } from 'vitest'; -import { pluginConnectionNames, primePluginConnections } from '@agent-device/plugins/connection'; +import { + pluginConnectionNames, + pluginLoadFailures, + primePluginConnections, +} from '@agent-device/plugins/connection'; import { connectionProviderCapabilities, connectProviderNamesForError, isConnectProviderName, primeProviderConnection, } from './provider-policy.ts'; -import { - pluginHome, - selectPlugin, - selectV2Plugin, - v2RegistrationSource, -} from '@agent-device/test-kit'; +import { pluginHome, selectV2Plugin, v2RegistrationSource } from '@agent-device/test-kit'; test('provider policy projects provider identity into semantic capabilities', () => { - assert.deepEqual(connectionProviderCapabilities('limrun'), { + assert.deepEqual(connectionProviderCapabilities('limrun', {}), { leaseKind: 'direct-device-provider', requiresAppAttachment: false, requiresRemoteDaemon: false, @@ -28,39 +25,56 @@ test('provider policy projects provider identity into semantic capabilities', () holdsCloudDevice: true, forgetsEndedConnectionLease: true, }); - const browserStack = connectionProviderCapabilities('browserstack'); - assert.equal(browserStack.supportsArtifacts, true); - assert.equal(browserStack.usesCloudWebDriverLease, true); - assert.equal(connectionProviderCapabilities('aws-device-farm').requiresAppAttachment, true); - assert.equal(connectionProviderCapabilities('proxy').leaseKind, 'proxy'); + // BrowserStack is a plugin: without an installed one nothing declares its capabilities. + assert.equal( + connectionProviderCapabilities('browserstack', pluginHome().env).leaseKind, + 'remote-provider', + ); + assert.equal(connectionProviderCapabilities('aws-device-farm', {}).leaseKind, 'remote-provider'); + assert.equal(connectionProviderCapabilities('proxy', {}).leaseKind, 'proxy'); }); -test('plugin capabilities come from the same environment as the provider name check', () => { +test('an installed AWS Device Farm plugin declares its capabilities once the store is primed', async () => { const { home, env } = pluginHome(); - selectPlugin(home, 'example', 'example', 'export default () => {};'); - const { installation } = JSON.parse(fs.readFileSync(path.join(home, 'config.json'), 'utf8')) - .plugins.example; - const manifestPath = path.join( + selectV2Plugin( home, - 'plugins', - installation, - 'node_modules/example/package.json', + '@agent-device/aws-device-farm', + v2RegistrationSource('aws-device-farm', { + extra: `connection: { capabilities: { leaseKind: 'direct-device-provider', requiresAppAttachment: true, requiresRemoteDaemon: false, supportsArtifacts: true, supportsDeferredAppSelection: false, supportsDirectPortReverse: false, usesCloudWebDriverLease: true }, resolve() {}, verify() {} },`, + }), ); - const declared = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); - const connection = { - leaseKind: 'direct-device-provider', - requiresAppAttachment: true, - requiresRemoteDaemon: false, - supportsArtifacts: true, - supportsDeferredAppSelection: false, - supportsDirectPortReverse: false, - usesCloudWebDriverLease: true, - } as const; - declared.agentDevicePlugin.connection = connection; - fs.writeFileSync(manifestPath, JSON.stringify(declared)); - assert.equal(isConnectProviderName('example', env), true); - assert.deepEqual(connectionProviderCapabilities('example', env), connection); + assert.equal(connectionProviderCapabilities('aws-device-farm', env).requiresAppAttachment, false); + await primeProviderConnection('aws-device-farm', env); + assert.equal(connectionProviderCapabilities('aws-device-farm', env).requiresAppAttachment, true); +}); + +test('a manifest connection on a store package supplies no capabilities', async () => { + const { home, env } = pluginHome(); + selectV2Plugin(home, 'example', v2RegistrationSource('example'), { + manifest: { + agentDevicePlugin: { + apiVersion: 1, + provider: 'example', + entry: './plugin.mjs', + connection: { + leaseKind: 'direct-device-provider', + requiresAppAttachment: true, + requiresRemoteDaemon: false, + supportsArtifacts: true, + supportsDeferredAppSelection: false, + supportsDirectPortReverse: false, + usesCloudWebDriverLease: true, + }, + }, + }, + }); + + assert.equal(isConnectProviderName('example', env), false); + await primeProviderConnection('example', env); + // The factory declares no connection, so the manifest never fills the gap. + assert.equal(isConnectProviderName('example', env), false); + assert.deepEqual(pluginConnectionNames(env), []); }); test('a v2 plugin declares its capabilities in code, so they are read once the store is primed', async () => { @@ -97,25 +111,13 @@ test('a store plugin that fails to load is named where an unknown connect provid ); }); -test('once the store is primed a duplicate v1 manifest no longer supplies capabilities', async () => { +test('a plugin that fails to load supplies no connection name even after priming', async () => { const { home, env } = pluginHome(); - selectPlugin(home, 'dup', 'browserstack', 'export default () => {};'); - const { installation } = JSON.parse(fs.readFileSync(path.join(home, 'config.json'), 'utf8')) - .plugins.dup; - const manifestPath = path.join(home, 'plugins', installation, 'node_modules/dup/package.json'); - const declared = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); - declared.agentDevicePlugin.connection = { - leaseKind: 'direct-device-provider', - requiresAppAttachment: true, - requiresRemoteDaemon: false, - supportsArtifacts: true, - supportsDeferredAppSelection: false, - supportsDirectPortReverse: false, - usesCloudWebDriverLease: true, - }; - fs.writeFileSync(manifestPath, JSON.stringify(declared)); - - expect(pluginConnectionNames(env)).toEqual(['browserstack']); - await primePluginConnections(env, ['browserstack']); + selectV2Plugin(home, 'dup', v2RegistrationSource('aws-device-farm')); + await primePluginConnections(env, ['aws-device-farm']); + // The built-in claimed the id first, so the store package registers nothing. expect(pluginConnectionNames(env)).toEqual([]); + expect(pluginLoadFailures(env).map(({ package: name, error }) => [name, error.reason])).toEqual([ + ['dup', 'duplicate_provider'], + ]); }); diff --git a/src/cli/connection/provider-policy.ts b/src/cli/connection/provider-policy.ts index 8327ae2866..1d38a4e408 100644 --- a/src/cli/connection/provider-policy.ts +++ b/src/cli/connection/provider-policy.ts @@ -7,7 +7,11 @@ import { primePluginConnections, } from '@agent-device/plugins/connection'; import { AppError } from '@agent-device/kernel/errors'; -import { getProviderPluginDeclaration } from '../../commands/provider-plugin-catalog.ts'; +import { + getProviderPluginDeclaration, + providerPluginInstallCommand, + providerPluginRepairCommand, +} from '../../commands/provider-plugin-catalog.ts'; import { BUILTIN_CONNECT_PROVIDER_IDS, BUILTIN_PROVIDER_IDS, @@ -41,6 +45,9 @@ export async function primeProviderConnection( ): Promise { if (provider === undefined || BUILTIN_CONNECT_PROVIDER_IDS.includes(provider)) return; await primePluginConnections(env, BUILTIN_PROVIDER_IDS); + if (pluginConnectionCapabilities(provider, env) !== undefined) return; + const unavailable = unavailableConnectPluginError(provider, env); + if (unavailable) throw unavailable; } export function isConnectProviderName( @@ -84,10 +91,10 @@ export function unavailableConnectPluginError( provider, package: declaration.package, ...(failures.length > 0 ? { failedPlugins: failures } : {}), - hint: `Run agent-device plugins list --json to inspect the plugin, fix its configuration or run agent-device plugins update ${declaration.package}, then retry your original command.`, + hint: `Run agent-device plugins list --json to inspect the plugin, fix its configuration or run ${providerPluginRepairCommand(declaration)}, then retry your original command.`, }); } - const installCommand = `agent-device plugins add ${declaration.package}`; + const installCommand = providerPluginInstallCommand(declaration); return new AppError( 'UNSUPPORTED_OPERATION', `${declaration.label} requires the ${declaration.package} plugin.`, @@ -104,11 +111,13 @@ export function unavailableConnectPluginError( /** Bundled and installed providers declare their capabilities; the rest is the daemon's own routing. */ export function connectionProviderCapabilities( provider: string | undefined, - env: NodeJS.ProcessEnv = process.env, + env: NodeJS.ProcessEnv, ): ConnectionProviderCapabilities { if (provider === 'proxy') return remoteDaemonConnection('proxy'); const declared = builtinConnectionCapabilities(provider) ?? - (provider === 'cloud' ? undefined : pluginConnectionCapabilities(provider, env)); + (provider === undefined || provider === 'cloud' + ? undefined + : pluginConnectionCapabilities(provider, env)); return declared ?? remoteDaemonConnection('remote-provider'); } diff --git a/src/cli/parser/__tests__/args-maestro-support-matrix.test.ts b/src/cli/parser/__tests__/args-maestro-support-matrix.test.ts index c84c5b0ec2..7f32e6fef1 100644 --- a/src/cli/parser/__tests__/args-maestro-support-matrix.test.ts +++ b/src/cli/parser/__tests__/args-maestro-support-matrix.test.ts @@ -5,7 +5,7 @@ import { getFlagDefinitions } from '@agent-device/command-registry/flag-registry import { MAESTRO_COMPAT_LIMITATIONS, MAESTRO_COMPAT_SUPPORTED_CAPABILITIES, -} from '@agent-device/maestro'; +} from '@agent-device/replay-port/replay-backend-declarations'; const MAESTRO_COMPATIBILITY_ADR_URL = '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/callstack/agent-device/blob/main/docs/adr/0015-direct-maestro-engine.md'; @@ -20,6 +20,9 @@ test('Maestro flag routes to the versioned compatibility help topic', () => { test('Maestro help covers the supported subset and operational boundaries', async () => { const help = await usageForCommand('maestro'); expect(help).not.toBeNull(); + expect(help).toContain('agent-device plugins add @agent-device/maestro'); + expect(help).toContain('agent-device plugins add @agent-device/replay'); + expect(help).toContain('on the daemon host for native .ad replay and all test suites'); for (const statement of [ ...MAESTRO_COMPAT_SUPPORTED_CAPABILITIES, ...MAESTRO_COMPAT_LIMITATIONS, diff --git a/src/cli/replay-test/reporters/default.ts b/src/cli/replay-test/reporters/default.ts index d2b0d00fe3..b0550013b8 100644 --- a/src/cli/replay-test/reporters/default.ts +++ b/src/cli/replay-test/reporters/default.ts @@ -6,7 +6,7 @@ import { } from '../progress.ts'; import { formatDurationSeconds } from '../duration-format.ts'; import { colorize, supportsColor } from '@agent-device/command-output'; -import { formatReplayDivergenceReport } from '@agent-device/ad-replay/divergence'; +import { formatReplayDivergenceReport } from '@agent-device/contracts/replay-divergence-data'; import type { ReplayTestReporter, ReplayTestReporterContext, diff --git a/src/cli/update-check.ts b/src/cli/update-check.ts index 916d2f84f4..3afc23b420 100644 --- a/src/cli/update-check.ts +++ b/src/cli/update-check.ts @@ -169,7 +169,6 @@ function cachedDistTag(cache: UpdateCheckCache): string { return cache.distTag ?? 'latest'; } -/** A nightly build follows the `nightly` dist-tag; every other build follows `latest`. */ function distTagFor(version: string): 'latest' | 'nightly' { return version.includes('-nightly.') ? 'nightly' : 'latest'; } diff --git a/src/commands/provider-plugin-catalog.test.ts b/src/commands/provider-plugin-catalog.test.ts new file mode 100644 index 0000000000..30e5b36279 --- /dev/null +++ b/src/commands/provider-plugin-catalog.test.ts @@ -0,0 +1,68 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { + getProviderPluginDeclaration, + providerPluginHelp, + providerPluginInstallCommand, +} from './provider-plugin-catalog.ts'; + +const NIGHTLY_0_22 = '0.22.0-nightly-0-22.20261118.187'; +const MAIN_NIGHTLY_0_22 = '0.22.0-nightly.20261118.186'; + +function declaration(provider: string) { + const found = getProviderPluginDeclaration(provider); + assert.ok(found, `Expected ${provider} in the provider plugin catalog`); + return found; +} + +test.each([NIGHTLY_0_22, MAIN_NIGHTLY_0_22])( + '0.22 nightly core %s names the plugin release built with it', + (coreVersion) => { + for (const provider of ['browserstack', 'aws-device-farm']) { + assert.equal( + providerPluginInstallCommand(declaration(provider), coreVersion), + `agent-device plugins add @agent-device/${provider}@${coreVersion}`, + ); + } + }, +); + +test('a 0.22 source checkout names the nightly tag', () => { + assert.equal( + providerPluginInstallCommand(declaration('browserstack'), '0.22.0-dev'), + 'agent-device plugins add @agent-device/browserstack@nightly-0.22', + ); +}); + +test('a core outside the 0.22 nightlies keeps the plain package selector', () => { + for (const coreVersion of ['0.21.40-nightly.20261118.186', '0.22.0', '0.0.0']) { + assert.equal( + providerPluginInstallCommand(declaration('aws-device-farm'), coreVersion), + 'agent-device plugins add @agent-device/aws-device-farm', + `core ${coreVersion} must not name a release it cannot match`, + ); + } +}); + +test('a plugin that ships every release ignores the channel of the core', () => { + for (const provider of ['testmu', 'revyl', 'webos', 'tizen']) { + assert.equal( + providerPluginInstallCommand(declaration(provider), NIGHTLY_0_22), + `agent-device plugins add @agent-device/${provider}`, + ); + assert.equal( + providerPluginInstallCommand(declaration(provider), '0.21.39'), + `agent-device plugins add @agent-device/${provider}`, + ); + } +}); + +test('help gives nightly and stable users the same plugin selectors as recovery', () => { + const nightly = providerPluginHelp(NIGHTLY_0_22); + const stable = providerPluginHelp('0.22.0'); + for (const provider of ['browserstack', 'aws-device-farm']) { + assert.ok(nightly.includes(`connect ${provider}; @agent-device/${provider}@${NIGHTLY_0_22})`)); + assert.ok(stable.includes(`connect ${provider}; @agent-device/${provider})`)); + } + assert.match(nightly, /TestMu AI \(connect testmu; @agent-device\/testmu\)/); +}); diff --git a/src/commands/provider-plugin-catalog.ts b/src/commands/provider-plugin-catalog.ts index 03e8a282e5..ccd566c29c 100644 --- a/src/commands/provider-plugin-catalog.ts +++ b/src/commands/provider-plugin-catalog.ts @@ -1,10 +1,31 @@ +import { readVersion } from '@agent-device/host-kit/version'; + type ProviderPluginDeclaration = Readonly<{ provider: string; package: string; label: string; + // A 0.22.x-dev version carries no source branch. Use the 0.22 branch's nightly tag + // as the shared default for development builds, including main checkouts. + nightlyTag?: 'nightly-0.22'; }>; +export const AWS_DEVICE_FARM: ProviderPluginDeclaration = { + provider: 'aws-device-farm', + package: '@agent-device/aws-device-farm', + label: 'AWS Device Farm', + nightlyTag: 'nightly-0.22', +}; + +export const BROWSERSTACK: ProviderPluginDeclaration = { + provider: 'browserstack', + package: '@agent-device/browserstack', + label: 'BrowserStack', + nightlyTag: 'nightly-0.22', +}; + const PROVIDER_PLUGIN_CATALOG: readonly ProviderPluginDeclaration[] = [ + AWS_DEVICE_FARM, + BROWSERSTACK, { provider: 'revyl', package: '@agent-device/revyl', label: 'Revyl' }, { provider: 'testmu', package: '@agent-device/testmu', label: 'TestMu AI' }, { provider: 'webos', package: '@agent-device/webos', label: 'LG webOS' }, @@ -17,10 +38,43 @@ export function getProviderPluginDeclaration( return PROVIDER_PLUGIN_CATALOG.find((plugin) => plugin.provider === provider); } -// One line for the whole catalog keeps help remote's first screen fixed as plugins are added. -export function providerPluginHelp(): string { +// The release workflow stamps the core and its public plugins with the same nightly version. +const NIGHTLY_0_22_VERSION = /^0\.22\.\d+-nightly(?:-0-22)?\.\d{8}\.[1-9]\d*$/; +const DEVELOPMENT_0_22_VERSION = /^0\.22\.\d+-dev$/; + +function providerPluginSelector( + declaration: ProviderPluginDeclaration, + coreVersion: string, +): string { + if (declaration.nightlyTag === undefined) return declaration.package; + const version = coreVersion.trim(); + if (NIGHTLY_0_22_VERSION.test(version)) return `${declaration.package}@${version}`; + if (DEVELOPMENT_0_22_VERSION.test(version)) { + return `${declaration.package}@${declaration.nightlyTag}`; + } + return declaration.package; +} + +export function providerPluginInstallCommand( + declaration: ProviderPluginDeclaration, + coreVersion: string = readVersion(), +): string { + return `agent-device plugins add ${providerPluginSelector(declaration, coreVersion)}`; +} + +export function providerPluginRepairCommand( + declaration: ProviderPluginDeclaration, + coreVersion: string = readVersion(), +): string { + const selector = providerPluginSelector(declaration, coreVersion); + const action = selector === declaration.package ? 'update' : 'add'; + return `agent-device plugins ${action} ${selector}`; +} + +export function providerPluginHelp(coreVersion: string = readVersion()): string { const plugins = PROVIDER_PLUGIN_CATALOG.map( - (plugin) => `${plugin.label} (connect ${plugin.provider}; ${plugin.package})`, + (plugin) => + `${plugin.label} (connect ${plugin.provider}; ${providerPluginSelector(plugin, coreVersion)})`, ).join(', '); return ` Plugins, installed separately: ${plugins}. Run agent-device plugins add , then retry agent-device connect with your original arguments.`; } diff --git a/src/commands/schema/cli-help-overview.ts b/src/commands/schema/cli-help-overview.ts index 51fa29cf6c..cddf5817c3 100644 --- a/src/commands/schema/cli-help-overview.ts +++ b/src/commands/schema/cli-help-overview.ts @@ -49,7 +49,7 @@ Rules: More commands (exact shapes: agent-device help ): open install devices apps boot close app and device lifecycle screenshot record logs network perf trace evidence and diagnostics - replay test batch session scripted flows + replay test batch session scripted flows (replay/test plugins, install separately) alert keyboard clipboard settings gesture system and input Guides (agent-device help ): diff --git a/src/commands/schema/cli-help-topics.test.ts b/src/commands/schema/cli-help-topics.test.ts index c4575dbe96..1b4b253cf2 100644 --- a/src/commands/schema/cli-help-topics.test.ts +++ b/src/commands/schema/cli-help-topics.test.ts @@ -411,8 +411,14 @@ test('usageForCommand resolves remote help topic', async () => { assert.match(help, /agent-device connect cloud discovers the agent-device cloud profile/); assert.match(help, /Direct proxy: agent-device connect proxy/); assert.match(help, /stores the shared proxy profile and client identity/); - assert.match(help, /BrowserStack: agent-device connect browserstack/); - assert.match(help, /AWS Device Farm: agent-device connect aws-device-farm/); + assert.match( + help, + /BrowserStack \(plugin, install separately\): agent-device connect browserstack/, + ); + assert.match( + help, + /AWS Device Farm \(plugin, install separately\): install the @agent-device\/aws-device-farm plugin/, + ); assert.match(help, /Limrun: agent-device connect limrun/); assert.match(help, /It does not create an App Automate session/); assert.match(help, /It does not create a remote access session/); diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 58715fb794..2a2a33e163 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -1,6 +1,10 @@ +import { getReplayPluginInstallation } from '@agent-device/ad-script'; import { gestureHelpTopic } from './cli-help-gestures.ts'; import { listCliCommandNames } from '@agent-device/command-registry/catalog'; -import { getReplayBackendDeclaration } from '@agent-device/replay-port/replay-backend-declarations'; +import { + getReplayBackendDeclaration, + replayPluginInstallHelp, +} from '@agent-device/replay-port/replay-backend-declarations'; import { normalizeCliCommandAlias } from '@agent-device/command-registry/cli-command-aliases'; import { helpBody } from '@agent-device/command-registry/command-text'; import { getCliCommandSchema, getCommandSchema } from '@agent-device/command-surface'; @@ -23,7 +27,12 @@ import { renderCliHelpOverview } from './cli-help-overview.ts'; import { foldableHelpTopic } from './cli-help-foldable.ts'; import { reactNativeHelpTopic } from './cli-help-react-native.ts'; import { TV_PLUGIN_FLOWS } from './cli-help-tv.ts'; -import { providerPluginHelp } from '../provider-plugin-catalog.ts'; +import { + AWS_DEVICE_FARM, + BROWSERSTACK, + providerPluginHelp, + providerPluginInstallCommand, +} from '../provider-plugin-catalog.ts'; const CONFIGURATION_LINES = [ 'Default config files: ~/.agent-device/config.json (or /config.json), ./agent-device.json (project-safe defaults only).', @@ -70,7 +79,10 @@ const HELP_TOPICS = { body: 'agent-device help commands', }, ...manualQaHelpTopics, - maestro: getReplayBackendDeclaration('maestro').help, + maestro: getReplayBackendDeclaration( + getReplayPluginInstallation('maestro'), + getReplayPluginInstallation('ad'), + ).help, workflow: { summary: 'Normal agent-device bootstrap, exploration, and validation loop', body: `agent-device help workflow @@ -415,8 +427,8 @@ Runner and daemon lifecycle (applies to simulators too): Each AGENT_DEVICE_STATE_DIR runs its own daemon. It self-exits after an idle window (default 5 minutes, matching the runner idle-stop default) once it has no open sessions, no in-flight requests, and no active recording; set AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS to override, or 0 to disable idle reap. A client starting a local daemon waits while the daemon process stays alive and keeps publishing startup progress, so an overloaded host makes startup slower, not failed. It stops at a ceiling (default 120 s; set AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS to a positive integer number of milliseconds to override) and names the outcome in error details.reason: startup-exited (the process ended before registering), startup-stalled (alive, no startup progress for a fixed 60 s window the ceiling variable does not change), or startup-ceiling (a startup was still live when the ceiling passed — this client's daemon or another client's; the client stops its own launch and never signals another client's live daemon. Only a progressing own launch outlasts the 60 s stall window, so a ceiling set below 60 s also ends a silent own launch this way). details.phases carries the startup phase timings it observed and details.startupTimeoutMs the effective ceiling. Branch on details.reason, never on the message. The variable is read only when a client must start a daemon: a value that is not a positive integer fails with INVALID_ARGS before the daemon spawns, and a client that only attaches to or reuses a running daemon never reads it. On iOS simulators, open prepares app accessibility before launching an app or URL. If a running app has an empty accessibility tree after an earlier XCTest session, use open --relaunch, then snapshot -i. A preparation failure is logged and does not block launch. - A command that needs the shared local daemon starts it for its state dir when none runs (device status and device release --stale never contact one). When the running daemon comes from another version or build, the command replaces it only if the daemon reports no work: no in-flight request, session, repair session, or live lease (a streaming resumable upload and a host human-control hold that names no lease are not counted); otherwise it fails with details.reason daemon-busy and leaves the daemon alone. A daemon that agreed to leave is waited for up to 60 s and never signaled while it drains; one still running then fails with details.reason daemon-drain-timeout unless it answers nothing and is provably a daemon process, which is force-retired. A daemon from a release that predates this check is never replaced and fails with daemon-incompatible. End a busy or older daemon deliberately with agent-device daemon stop --state-dir . Node clients pick daemonLifecycle 'attach' (never starts or replaces a daemon; fails with daemon-not-running or daemon-incompatible) or 'managed' (the default until 0.22), and ensureDaemon() starts or replaces one explicitly. - daemon stop --state-dir stops a detached daemon with process signals after verifying its identity. For a live embedded runtime, stop refuses with details.reason daemon-owner-embedded and a hint naming the host PID. Close that runtime in its host process with the handle returned by startAgentDevice(). Stop refuses live unrecognized ownership with daemon-owner-unrecognized and sends no request or signal. Stop retires an embedded or unrecognized registration when its recorded host lifetime has provably exited. Without --clean, an unreadable daemon.json fails with daemon-record-unreadable. daemon status shows host-owned or owner-not-recognized. Managed clients reuse a matching embedded runtime. Takeover, drain, and timeout recovery refuse a live embedded or unrecognized owner without a signal; a provably exited owner is retired so the state directory stays usable. Detached stop and cleanup use the lifetime and ownership from one registration read. --clean requires proven detached ownership; embedded, unrecognized and unreadable records fail with daemon-clean-not-detached because that cleanup walks the owner's whole process tree. + A command that needs the shared local daemon starts it for its state dir when none runs (device status and device release --stale never contact one). When the running daemon comes from another version or build, the command replaces it only if the daemon reports no work: no in-flight request, session, repair session, or live lease (a streaming resumable upload and a host human-control hold that names no lease are not counted); otherwise it fails with details.reason daemon-busy and leaves the daemon alone. A daemon that agreed to leave is waited for up to 60 s and never signaled while it drains; one still running then fails with details.reason daemon-drain-timeout unless it answers nothing and is provably a daemon process, which is force-retired. A daemon from a release that predates this check is never replaced and fails with daemon-incompatible. End a busy or older daemon deliberately with agent-device daemon stop --state-dir . Node clients always attach: they never start, replace or retire a daemon, and fail with daemon-not-running or daemon-incompatible. ensureDaemon() starts or replaces one explicitly, and startAgentDevice() owns one in the client's own process. + daemon stop --state-dir stops a detached daemon with process signals after verifying its identity. For a live embedded runtime, stop refuses with details.reason daemon-owner-embedded and a hint naming the host PID. Close that runtime in its host process with the handle returned by startAgentDevice(). Stop refuses live unrecognized ownership with daemon-owner-unrecognized and sends no request or signal. Stop retires an embedded or unrecognized registration when its recorded host lifetime has provably exited. Without --clean, an unreadable daemon.json fails with daemon-record-unreadable. daemon status shows host-owned or owner-not-recognized. Clients attach to a matching embedded runtime. Explicit ensuring refuses to replace a live embedded or unrecognized owner; a provably exited owner can be retired so the state directory stays usable. Detached stop and cleanup use the lifetime and ownership from one registration read. --clean requires proven detached ownership; embedded, unrecognized and unreadable records fail with daemon-clean-not-detached because that cleanup walks the owner's whole process tree. On a machine shared by several agents, set AGENT_DEVICE_SESSION_IDLE_TIMEOUT_MS to also expire an individual session that has taken a host-global device claim and then received no commands for that long; the claim is released and the next command on that session answers SESSION_NOT_FOUND with details.reason SESSION_IDLE_EXPIRED naming the window and the device. Off by default, because on a shared host "idle" and "thinking" are indistinguishable: only set it where an abandoned claim blocking every other agent is the worse failure. Sessions holding a remote lease or any active capture (recording, logs, audio, performance, or trace) are never expired this way. A stale iOS runner lease — its owner process dead, or its AGENT_DEVICE_STATE_DIR deleted — is reclaimed automatically instead of failing with "is already owned by another agent-device daemon". A live owner's runner is also reclaimed when the requesting daemon holds the host-global device claim for that device: claims are exclusive, so holding one proves the runner's owner released the device and merely kept the runner warm. The error remains only for owners outside claim arbitration (a pre-claims build, or daemons pointed at different claim stores). @@ -455,7 +467,7 @@ Rules: foldable: foldableHelpTopic, remote: { summary: 'Direct proxy, cloud profiles, and remote config', - body: `agent-device help remote + body: (coreVersion: string) => `agent-device help remote Remote connection providers use the same lifecycle: connect -> install/open -> commands -> close -> disconnect @@ -464,14 +476,14 @@ Providers: Cloud: agent-device connect or agent-device connect cloud discovers the agent-device cloud profile. Remote config: agent-device connect --remote-config ./remote-config.json uses a local profile. Direct proxy: agent-device connect proxy --daemon-base-url stores the shared proxy profile and client identity. - BrowserStack: agent-device connect browserstack verifies credentials, the exact device, and a bs:// app reference, then stores a local provider profile. It does not create an App Automate session. - AWS Device Farm: agent-device connect aws-device-farm verifies credentials and the exact project, device, and optional app upload, then stores a local provider profile. It does not create a remote access session. + BrowserStack (plugin, install separately): agent-device connect browserstack verifies credentials, the exact device, and a bs:// app reference, then stores a local provider profile. It does not create an App Automate session. + AWS Device Farm (plugin, install separately): install the @agent-device/aws-device-farm plugin, then agent-device connect aws-device-farm verifies credentials and the exact project, device, and optional app upload, then stores a local provider profile. It does not create a remote access session. TestMu AI (plugin, install separately): agent-device connect testmu verifies credentials and the exact virtual device (emulator or simulator) or, with --provider-device-type real, real device and OS version, then stores a local provider profile. --provider-app takes an lt:// app reference, an https URL, or a local path: connect looks an lt:// id up among your uploads for that device pool, while URL and local sources are uploaded and validated when open creates the session. It does not create a hub session. Limrun: agent-device connect limrun verifies access to the selected iOS or Android instance service, then stores a local provider profile. It does not create an instance. Revyl (plugin, install separately): agent-device connect revyl verifies credentials against the Revyl backend, then stores a local provider profile with the platform, optional --device model and --provider-os-version, and a required --provider-app https URL: Revyl downloads and installs that build when it starts the device. It does not rent a device. Plugin installation: the lines below name the plugin each provider needs, and plugin help is available before installation. plugins list --json reports your installed plugins. A missing plugin returns reason plugin-not-installed with its installation command; a selected plugin that cannot supply the provider returns plugin-unavailable instead. After changing plugins, close sessions and stop an existing local daemon with the same --state-dir before the next device command. -${providerPluginHelp()} +${providerPluginHelp(coreVersion)} After direct-provider connect: Read the printed Device, App, Next, and workflow-note lines. They are also available as verification/device/app/liveSession/nextSteps/notes in --json output. @@ -539,6 +551,7 @@ TestMu AI real-device flow: ${TV_PLUGIN_FLOWS} BrowserStack hosted-device flow: + ${providerPluginInstallCommand(BROWSERSTACK, coreVersion)} export BROWSERSTACK_USERNAME=... BROWSERSTACK_ACCESS_KEY=... AGENT_DEVICE_SESSION=checkout-android agent-device connect browserstack --platform android --device "Google Pixel 8" --provider-os-version 14.0 --provider-app bs://app-id agent-device open com.example.app @@ -548,6 +561,7 @@ BrowserStack hosted-device flow: agent-device disconnect AWS Device Farm hosted-device flow: + ${providerPluginInstallCommand(AWS_DEVICE_FARM, coreVersion)} export AWS_REGION=us-west-2 AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... AWS_SESSION_TOKEN=... AGENT_DEVICE_SESSION=checkout-android agent-device connect aws-device-farm --platform android --aws-project-arn --aws-device-arn --aws-app-arn agent-device open com.example.app @@ -598,6 +612,7 @@ Rules: Prefer connect --remote-config over --daemon-base-url, --tenant, --run-id, and --lease-id when using a local profile. Use agent-device proxy for direct tunnel access to a Mac you control. Expose the proxy through cloudflared/ngrok, configure --public-origin with the public tunnel origin, then run agent-device connect proxy with the tunnel URL and printed token before normal commands. Use Limrun, BrowserStack, AWS Device Farm, TestMu AI, and Revyl through local provider profiles; they do not accept a remote agent-device daemon URL. + Node SDK integrations in 0.22 pass an explicit { env, cwd } host to Android host ADB helpers, archive inspection, and Metro preparation. resolveRemoteConfigProfile requires env; createLocalArtifactAdapter requires cwd. CLI and MCP entry points capture their process host. Device cloud credentials must be available before the command starts. Limrun uses LIMRUN_API_KEY, or the LIM_*_INSTANCE_* variables for an existing instance. BrowserStack uses BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY. TestMu AI uses LT_USERNAME and LT_ACCESS_KEY. Revyl uses REVYL_API_KEY, with REVYL_API_URL to point at another Revyl backend. AWS Device Farm uses the AWS CLI credential chain, including CI-provided AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/AWS_SESSION_TOKEN, AWS profiles, or web identity role variables. A local daemon keeps the Limrun, BrowserStack, TestMu AI, and Revyl credentials it started with. When the shell holds different ones, the first command that allocates a lease refuses with reason provider-credentials-changed; run agent-device daemon stop with the same --state-dir, then rerun the command. A shell that sets none of them uses the daemon's. A daemon with an HTTP auth hook serves remote callers and does not compare. A lease for a provider the daemon has no runtime for refuses with UNSUPPORTED_OPERATION, reason provider-not-registered, and lists the registered providers, plus the plugins that failed to register as failedPlugins; no lease is recorded. Restart the daemon with the provider configured. Provider-less leases, proxy, and cloud need no provider runtime. @@ -709,7 +724,10 @@ Rules: Keep browser plans session-scoped: open a URL, inspect refs, act on refs/selectors, verify with wait/get/is/snapshot, capture screenshot only when visual evidence is needed, then close. Each --session name is its own browser (cookies and storage) and its own device (agent-browser-chrome:session:p_, or t__ under tenant isolation so tenants never share a browser): web sessions with different names run in parallel, and the same name in the same tenant conflicts while different tenants may reuse a name. Without --session under local workspace scoping, each workspace uses its own browser and device (agent-browser-chrome:session:w_); different workspaces can run in parallel, while the same workspace conflicts across daemons sharing a claims directory. A request without a workspace scope (no cwd) uses the default session's browser and device (p_default, or t__default under tenant isolation). A name matches case-insensitively and must be 1 to 30 characters of letters, digits, "_" and "-" (1 to 17 under tenant isolation); anything else, including surrounding whitespace or an empty --session "", is refused with web_session_name_invalid.`, }, ...qaReportHelpTopics, -} as const satisfies Record; +} as const satisfies Record< + string, + { summary: string; body: string | ((coreVersion: string) => string) } +>; function formatCommandListArg(commandName: string, schema: CommandSchema, arg: string): string { const optional = arg.endsWith('?'); @@ -874,6 +892,16 @@ export function buildCommandUsageText(commandName: string): string | null { schema.flagDescriptionOverrides, ); const sections: string[] = []; + if (commandName === 'replay' || commandName === 'test') { + sections.push(replayPluginInstallHelp(getReplayPluginInstallation('ad'))); + sections.push( + getReplayBackendDeclaration( + getReplayPluginInstallation('ad'), + getReplayPluginInstallation('ad'), + ).help.body, + ); + sections.push(replayPluginInstallHelp(getReplayPluginInstallation('maestro'))); + } if (commandName === 'connect') { sections.push(`Optional provider plugins:\n${providerPluginHelp()}`); } @@ -913,11 +941,13 @@ export function helpTopicIds(): string[] { function buildHelpTopicUsageText(topicName: string): string | null { const topic = HELP_TOPICS[topicName as keyof typeof HELP_TOPICS]; if (!topic) return null; - const body = topicName === 'commands' ? renderFullCommandReferenceText() : topic.body; + const coreVersion = readVersion(); + const topicBody = typeof topic.body === 'function' ? topic.body(coreVersion) : topic.body; + const body = topicName === 'commands' ? renderFullCommandReferenceText() : topicBody; const related = RELATED_HELP_LINES.filter((entry) => entry.topic !== topicName) .map((entry) => ` ${entry.line}\n`) .join(''); - return `${withVersionHeader(topicName, body)} + return `${withVersionHeader(topicName, body, coreVersion)} Related: ${related}`; @@ -933,8 +963,8 @@ const RELATED_HELP_LINES = [ // installed version here (instead of hand-editing every topic string) gives the skill router a // single, reliable header to read the CLI version from without a separate --version call: a // missing/old header on `help workflow` means an old CLI that predates this format. -function withVersionHeader(topicId: string, body: string): string { +function withVersionHeader(topicId: string, body: string, coreVersion: string): string { const legacyHeader = `agent-device help ${topicId}`; if (!body.startsWith(legacyHeader)) return body; - return `agent-device ${readVersion()} — ${topicId}${body.slice(legacyHeader.length)}`; + return `agent-device ${coreVersion} — ${topicId}${body.slice(legacyHeader.length)}`; } diff --git a/src/core/interactors/limrun-ios-application-tools.ts b/src/core/interactors/limrun-ios-application-tools.ts index 1646047ebd..1135aecfad 100644 --- a/src/core/interactors/limrun-ios-application-tools.ts +++ b/src/core/interactors/limrun-ios-application-tools.ts @@ -1,4 +1,7 @@ -import type { AppleApplicationTools } from '@agent-device/contracts/application-lifecycle-runtime'; +import type { + AppleApplicationTools, + AppleApplicationToolsForProvider, +} from '@agent-device/contracts/application-lifecycle-runtime'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; @@ -24,7 +27,7 @@ export function createLimrunAppleApplicationTools( device: DeviceInfo, runner: RunnerLifecycle, hostTools: Pick< - AppleApplicationTools, + AppleApplicationToolsForProvider, 'resolveOpenTarget' | 'applyRuntimeHints' | 'clearRuntimeHints' >, ): AppleApplicationTools { diff --git a/src/core/interactors/limrun-ios-runner.fixtures.ts b/src/core/interactors/limrun-ios-runner.fixtures.ts index 6fc4eba525..6c6152754e 100644 --- a/src/core/interactors/limrun-ios-runner.fixtures.ts +++ b/src/core/interactors/limrun-ios-runner.fixtures.ts @@ -7,6 +7,7 @@ import path from 'node:path'; import { gunzipSync } from 'node:zlib'; import { afterEach, vi, type Mock } from 'vitest'; import { mkdtempForTest } from '@agent-device/test-kit'; +import type { AppleApplicationTools } from '@agent-device/contracts/application-lifecycle-runtime'; import type { LimrunRuntimeDependencies } from '@agent-device/provider-limrun'; import { createLimrunIosRunner } from './limrun-ios-runner.ts'; const cleanups: Array<() => Promise> = []; @@ -15,6 +16,18 @@ afterEach(async () => { cleanups.length = 0; }); +async function readRequestBody(request: IncomingMessage): Promise { + const chunks: Buffer[] = []; + try { + for await (const chunk of request) chunks.push(Buffer.from(chunk)); + } catch (error) { + if (request.destroyed && (error as NodeJS.ErrnoException).code === 'ECONNRESET') + return undefined; + throw error; + } + return Buffer.concat(chunks); +} + type Session = Parameters[0]; type Manifest = { files: Array<{ path: string; mode: number }>; @@ -42,6 +55,7 @@ type RunnerFixture = { export async function fixture( options: { + wrapApplicationTools?: (tools: AppleApplicationTools) => AppleApplicationTools; launchStatus?: number; holdLaunchErrorBody?: boolean; syncStatus?: number; @@ -195,9 +209,8 @@ export async function fixture( response.writeHead(401).end(); return; } - const chunks: Buffer[] = []; - for await (const chunk of request) chunks.push(Buffer.from(chunk)); - let body = Buffer.concat(chunks); + let body = await readRequestBody(request); + if (body === undefined) return; if (request.headers['content-encoding'] === 'gzip') body = gunzipSync(body); if (storage.serve(request, response, body)) return; if (request.url === '/v1/ios_test/api/sync') { @@ -295,8 +308,12 @@ export async function fixture( : { AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS: String(options.idleMs) }), }, }; - const runner: Awaited> = - await createLimrunIosRunner(session, host, createAppleApplicationTools(host.env)); + const tools = createAppleApplicationTools(host.env); + const runner = await createLimrunIosRunner( + session, + host, + options.wrapApplicationTools?.(tools) ?? tools, + ); cleanups.push(() => runner.dispose()); return { runner, diff --git a/src/core/interactors/limrun-ios-runner.test.ts b/src/core/interactors/limrun-ios-runner.test.ts index 62c85c4519..ab21ca4de2 100644 --- a/src/core/interactors/limrun-ios-runner.test.ts +++ b/src/core/interactors/limrun-ios-runner.test.ts @@ -1,5 +1,6 @@ import { promises as fs } from 'node:fs'; import path from 'node:path'; +import { request as httpRequest } from 'node:http'; import { registerRequestAbort, markRequestCanceled, @@ -48,6 +49,20 @@ test('stages a token-authenticated runner once and presents forwarded XCTest sna ).rejects.toThrow(); }); +test('runner construction reads only lease-facing Apple operations', async () => { + const f = await fixture({ + wrapApplicationTools: (tools) => ({ + ...tools, + get stopRunnerSession(): never { + throw new Error('Runner construction read daemon-owned teardown'); + }, + }), + }); + await expect( + f.runner.createInteractor().snapshot({ appBundleId: 'com.apple.Preferences' }), + ).resolves.toMatchObject({ backend: 'xctest' }); +}); + test('reports an occupied XCTest slot instead of falling back to AX', async () => { const f = await fixture({ launchStatus: 409 }); await expect( @@ -802,3 +817,18 @@ test('a new cache waiter retries after the canceled preparation finishes cleanup cleanup.mockRestore(); } }); + +test('an interrupted upload does not prevent the fixture from serving a later request', async () => { + const f = await fixture(); + const request = httpRequest(`${f.apiUrl}/sync`, { + method: 'POST', + headers: { authorization: 'Bearer instance-token', 'content-length': '100' }, + }); + request.on('error', () => {}); + request.write('partial'); + await vi.waitFor(() => expect(f.requests).toContain('/v1/ios_test/api/sync')); + request.destroy(); + await new Promise((resolve) => request.once('close', resolve)); + await f.runner.applicationTools.prewarmRunnerCache(f.device, {}, new AbortController().signal); + expect(f.uploads).toHaveLength(1); +}); diff --git a/src/core/interactors/limrun-ios-runner.ts b/src/core/interactors/limrun-ios-runner.ts index dfe311db88..9d3e5cf81f 100644 --- a/src/core/interactors/limrun-ios-runner.ts +++ b/src/core/interactors/limrun-ios-runner.ts @@ -2,7 +2,10 @@ import { limrunRunnerError, withLimrunRunnerErrors } from './limrun-ios-runner-e import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; import { Deadline, type DeadlineClock, retryWithPolicy } from '@agent-device/host-kit/retry'; import { createLimrunAppleToolProvider } from './limrun-ios-tools.ts'; -import type { AppleApplicationTools } from '@agent-device/contracts/application-lifecycle-runtime'; +import { + availableAppleApplicationToolsForProvider, + type AppleApplicationToolsForProvider, +} from '@agent-device/contracts/application-lifecycle-runtime'; import { withMethodScope } from '@agent-device/kernel/scoped-provider'; import { createLimrunAppleApplicationTools } from './limrun-ios-application-tools.ts'; import { randomInt } from 'node:crypto'; @@ -23,11 +26,15 @@ import { type LimrunIosRunner = Awaited>; type Session = Parameters[0]; -/** Owns the lease’s XCTest runs; closing an attached lease never terminates its simulator. */ +/** + * Owns the lease’s XCTest runs; closing an attached lease never terminates its simulator. + * The runner projects open-target resolution and runtime hints from `appleApplications`. Its + * lease-scoped tools own shutdown of this lease's runner. + */ export async function createLimrunIosRunner( session: Session, host: HostEnvironment, - appleApplications: AppleApplicationTools, + appleApplications: AppleApplicationToolsForProvider, ): Promise { const { createAppleRunnerRuntime, @@ -43,8 +50,9 @@ export async function createLimrunIosRunner( withAppleToolProvider(createLimrunAppleToolProvider(session, lifetime.signal, signal), () => withLimrunRunnerErrors(task), ); - const hostTools = withMethodScope({ ...appleApplications }, (task) => - hasScopedAppleToolProvider() ? task() : withTools(task), + const hostTools = withMethodScope( + { ...availableAppleApplicationToolsForProvider(appleApplications) }, + (task) => (hasScopedAppleToolProvider() ? task() : withTools(task)), ); const port = randomInt(20000, 50000); const apiUrl = session.apiUrl.replace(/\/$/, ''); diff --git a/src/daemon-composition-credentials.test.ts b/src/daemon-composition-credentials.test.ts index 5609f0f392..f8156f903a 100644 --- a/src/daemon-composition-credentials.test.ts +++ b/src/daemon-composition-credentials.test.ts @@ -6,6 +6,7 @@ import { mkdtempForTestSync, createTestHostEnvironment } from '@agent-device/tes import { createDaemonRuntimeDeps } from './daemon-composition.ts'; import { providerCredentialFingerprint } from '@agent-device/plugins/credential-fingerprint'; import { builtinPluginInventory } from './__tests__/test-utils/builtin-plugin-inventory.ts'; +import { browserstackPluginInventory } from './__tests__/test-utils/browserstack-plugin-inventory.ts'; vi.mock('./platform-runtime.ts', () => ({ androidObservation: {}, @@ -43,15 +44,20 @@ vi.mock('./provider-device-runtimes.ts', async () => ({ ], platformModules: [], shutdown: async () => [], - inventory: await ( - await import('./__tests__/test-utils/builtin-plugin-inventory.ts') - ).builtinPluginInventory(), + inventory: [ + ...(await ( + await import('./__tests__/test-utils/builtin-plugin-inventory.ts') + ).builtinPluginInventory()), + ...(await ( + await import('./__tests__/test-utils/browserstack-plugin-inventory.ts') + ).browserstackPluginInventory()), + ], }), })); test('daemon startup compares lease credentials with its own startup environment', async () => { const stateDir = mkdtempForTestSync('agent-device-daemon-credential-composition-'); - const inventory = await builtinPluginInventory(); + const inventory = [...(await builtinPluginInventory()), ...(await browserstackPluginInventory())]; const daemonEnv = { BROWSERSTACK_USERNAME: 'user', BROWSERSTACK_ACCESS_KEY: 'key-1' }; const runtime = await startDaemonRuntime({ host: createTestHostEnvironment({ @@ -84,6 +90,7 @@ test('daemon startup compares lease credentials with its own startup environment method: 'agent_device.lease.allocate', params: { token, + session: 'agent-a', tenantId: 'tenant', runId: 'run', leaseProvider: 'browserstack', diff --git a/src/daemon-composition-replay-selection.test.ts b/src/daemon-composition-replay-selection.test.ts new file mode 100644 index 0000000000..e721d9d526 --- /dev/null +++ b/src/daemon-composition-replay-selection.test.ts @@ -0,0 +1,139 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; +import { storePluginCandidates } from '@agent-device/plugins/store'; +import { + getReplayBackend, + getReplayExecution, +} from '@agent-device/replay-port/replay-backend-registry'; +import { + createTestHostEnvironment, + mkdtempForTestSync, + pluginHome, + selectV2Plugin, +} from '@agent-device/test-kit'; +import { composeDaemonRuntimeDeps } from './daemon-composition.ts'; + +function pluginSource(backend: 'ad' | 'maestro') { + const capability = + backend === 'ad' + ? `execution: { create: () => ({ + inspectAdReplay() {}, runAdReplay() {}, runReplayTestSuite() {} + }) }` + : `replayBackend: { create: () => ({ + id: 'maestro', collectSourceFiles() {}, inspectSource() {}, + runReplay() {}, exportReplayScript() {} + }) }`; + return `export default () => ({ + apiVersion: 2, kind: 'replay-backend', backend: '${backend}', + setup: () => ({ ${capability} }) + });`; +} + +async function composedRuntime(env: NodeJS.ProcessEnv, embedded = false) { + const state = createRuntimeStateHandle(); + const baseDir = mkdtempForTestSync('replay-selection-runtime-'); + const candidates = embedded ? await storePluginCandidates(env) : undefined; + try { + const deps = await state.run(() => + composeDaemonRuntimeDeps( + { + host: createTestHostEnvironment({ env }), + baseDir, + sessionsDir: path.join(baseDir, 'sessions'), + assertShutdownAllowed: undefined, + resolveSessionDir: (id) => path.join(baseDir, 'sessions', id), + resolveSessionArtifacts: () => { + throw new Error('Replay resolution must not create a session'); + }, + openWebSessionNames: () => [], + }, + candidates, + ), + ); + return { + resolve: (backend: 'ad' | 'maestro') => + state.run(() => (backend === 'ad' ? getReplayExecution() : getReplayBackend(backend))), + close: async () => { + await deps.shutdownProviderRuntimes(); + state.dispose(); + }, + }; + } catch (error) { + state.dispose(); + throw error; + } +} + +test.each([ + ['ad', 'replace'], + ['ad', 'remove'], + ['maestro', 'replace'], + ['maestro', 'remove'], +] as const)( + 'daemon refuses a retained custom %s implementation after %s', + async (backend, change) => { + const { home, env } = pluginHome(); + const name = `@example/${backend}`; + const source = pluginSource(backend); + selectV2Plugin(home, name, source); + const runtime = await composedRuntime(env); + try { + const first = await runtime.resolve(backend); + selectV2Plugin(home, '@example/unrelated', pluginSource(backend)); + expect(await runtime.resolve(backend)).toBe(first); + if (change === 'replace') { + selectV2Plugin(home, name, source); + } else { + const configPath = path.join(home, 'config.json'); + const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); + delete config.plugins[name]; + fs.writeFileSync(configPath, JSON.stringify(config)); + } + await expect(runtime.resolve(backend)).rejects.toMatchObject({ + details: { reason: 'daemon-plugin-set-stale', package: name }, + }); + } finally { + await runtime.close(); + } + }, +); + +test.each(['ad', 'maestro'] as const)( + 'embedded %s implementations remain independent of store changes', + async (backend) => { + const { home, env } = pluginHome(); + selectV2Plugin(home, `@example/${backend}`, pluginSource(backend)); + const runtime = await composedRuntime(env, true); + try { + const first = await runtime.resolve(backend); + fs.writeFileSync(path.join(home, 'config.json'), '{broken'); + expect(await runtime.resolve(backend)).toBe(first); + } finally { + await runtime.close(); + } + }, +); + +test.each([ + ['ad', '@agent-device/replay'], + ['maestro', '@agent-device/maestro'], +] as const)( + 'a newly installed %s catalog package requires daemon restart', + async (backend, name) => { + const { home, env } = pluginHome(); + const runtime = await composedRuntime(env); + try { + await expect(runtime.resolve(backend)).rejects.toMatchObject({ + details: { reason: 'plugin-not-installed', package: name }, + }); + selectV2Plugin(home, name, pluginSource(backend)); + await expect(runtime.resolve(backend)).rejects.toMatchObject({ + details: { reason: 'daemon-plugin-set-stale', package: name }, + }); + } finally { + await runtime.close(); + } + }, +); diff --git a/src/daemon-composition.test.ts b/src/daemon-composition.test.ts index 90115b19bb..9f66551bf0 100644 --- a/src/daemon-composition.test.ts +++ b/src/daemon-composition.test.ts @@ -47,6 +47,9 @@ vi.mock('./provider-device-runtimes.ts', () => ({ platformModules: [], shutdown: ports.shutdownProviders, inventory: [], + resolveReplayBackend: async () => { + throw new Error('no replay backend'); + }, }), })); diff --git a/src/daemon-composition.ts b/src/daemon-composition.ts index 798d90f016..2e9d935c70 100644 --- a/src/daemon-composition.ts +++ b/src/daemon-composition.ts @@ -90,7 +90,12 @@ export const createDaemonRuntimeDeps: ComposeDaemonRuntimeDeps = async ( export async function composeDaemonRuntimeDeps( input: Parameters[0], providerCandidates?: readonly PluginCandidate[], -): Promise { +): Promise< + DaemonRuntimeDeps & { + resolveReplayBackend: import('@agent-device/contracts/replay-backend').ReplayBackendResolver; + resolveReplayExecution: import('@agent-device/contracts/replay-execution').ReplayExecutionResolver; + } +> { const { host, baseDir, @@ -114,6 +119,12 @@ export async function composeDaemonRuntimeDeps( // The registry has set up every plugin. Until this function returns, nothing else owns its // cleanup, so any later failure closes it here; success transfers ownership to the daemon. try { + const { bindReplayBackendResolver } = + await import('@agent-device/replay-port/replay-backend-registry'); + await bindReplayBackendResolver( + providerComposition.resolveReplayBackend, + providerComposition.resolveReplayExecution, + ); const providerDeviceRuntimes = [...providerComposition.runtimes]; const deviceRuntimeGateway = createPlatformRuntimeGateway({ host, @@ -162,6 +173,8 @@ export async function composeDaemonRuntimeDeps( ownerLifecycle: createPlatformDaemonLifecycleOwners(host), shutdownProviderRuntimes: providerComposition.shutdown, pluginInventory: providerComposition.inventory, + resolveReplayBackend: providerComposition.resolveReplayBackend, + resolveReplayExecution: providerComposition.resolveReplayExecution, leaseLifecycleProvider: providerRuntimeProviders.leaseLifecycleProvider, providerRuntimeIds: providerRuntimeProviders.providerRuntimeIds, recoverExpiredLease: providerRuntimeProviders.recoverExpiredLease, diff --git a/src/daemon-entrypoint.test.ts b/src/daemon-entrypoint.test.ts index cd8962ce34..3c7594461b 100644 --- a/src/daemon-entrypoint.test.ts +++ b/src/daemon-entrypoint.test.ts @@ -2,7 +2,6 @@ import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import crypto from 'node:crypto'; import fs from 'node:fs'; -import http from 'node:http'; import path from 'node:path'; import { test } from 'vitest'; import { KNOWN_APP_ERROR_CODES } from '@agent-device/kernel/errors'; @@ -22,8 +21,6 @@ import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; import { screenRecordingDurableResource } from '@agent-device/capture-kit/screen-recording-session-resource'; import { - closeLoopbackServer, - listenOnLoopback, mkdtempForTestSync, waitForHttpOk, createTestHostEnvironment, @@ -156,16 +153,6 @@ test('daemon runtime publishes dual transport metadata', async () => { test('daemon rejects unowned cloud artifacts over RPC', async () => { const stateDir = mkdtempForTestSync('agent-device-daemon-provider-'); - const providerRequests: string[] = []; - const providerServer = http.createServer((_req, res) => { - res.setHeader('content-type', 'application/json'); - res.end( - JSON.stringify({ - automation_session: { video_url: 'https://browserstack.example/video.mp4' }, - }), - ); - }); - const providerPort = await listenOnLoopback(providerServer); let runtime: DaemonRuntimeController | null = null; try { @@ -176,9 +163,6 @@ test('daemon rejects unowned cloud artifacts over RPC', async () => { ...process.env, AGENT_DEVICE_STATE_DIR: stateDir, AGENT_DEVICE_DAEMON_SERVER_MODE: 'http', - BROWSERSTACK_USERNAME: 'user', - BROWSERSTACK_ACCESS_KEY: 'key', - BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `http://127.0.0.1:${providerPort}/sessions`, }, }), stderr: { write: () => {} }, @@ -198,7 +182,7 @@ test('daemon rejects unowned cloud artifacts over RPC', async () => { session: 'default', command: 'artifacts', positionals: [], - flags: { provider: 'browserstack', providerSessionId: 'wd-1' }, + flags: { provider: 'aws-device-farm', providerSessionId: 'wd-1' }, }, }), }); @@ -210,10 +194,8 @@ test('daemon rejects unowned cloud artifacts over RPC', async () => { assert.equal(body.error?.code, -32000); assert.equal(body.error?.data?.code, 'UNAUTHORIZED'); assert.deepEqual(body.error?.data?.details, { reason: 'PROVIDER_SESSION_NOT_OWNED' }); - assert.deepEqual(providerRequests, []); } finally { await runtime?.close(); - await closeLoopbackServer(providerServer); fs.rmSync(stateDir, { recursive: true, force: true }); } }); diff --git a/src/daemon-runtime-limrun-public-http.test.ts b/src/daemon-runtime-limrun-public-http.test.ts index d18886091f..b0f75306f7 100644 --- a/src/daemon-runtime-limrun-public-http.test.ts +++ b/src/daemon-runtime-limrun-public-http.test.ts @@ -142,6 +142,7 @@ test('public HTTP rejects Limrun uploaded-app listing and allocation before prov id: 'limrun-public-allocation', method: 'agent_device.lease.allocate', params: { + session: 'agent-a', tenantId: 'tenant-a', runId: 'run-a', backend: 'android-instance', diff --git a/src/host-replay.test.ts b/src/host-replay.test.ts new file mode 100644 index 0000000000..e2159d48b9 --- /dev/null +++ b/src/host-replay.test.ts @@ -0,0 +1,286 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test, vi } from 'vitest'; +import { prepareDaemonCommandRequest } from '@agent-device/command-surface'; +import { createAgentDeviceClient } from '@agent-device/client'; +import type { ReplayEnginePlugin } from '@agent-device/plugins/replay-backend'; +import { resolveProviderPlugins } from '@agent-device/plugins/registry'; +import { storePluginCandidates } from '@agent-device/plugins/store'; +import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; +import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { startAgentDevice } from './host.ts'; + +async function trackSourceRegistries() { + const pluginRegistry = await import('@agent-device/plugins/registry'); + const original = pluginRegistry.startProviderRegistry; + const closed = vi.fn(); + const started = vi.spyOn(pluginRegistry, 'startProviderRegistry'); + started.mockImplementation(async (...args) => { + const registry = await original(...args); + return { + ...registry, + close: async () => { + closed(); + return await registry.close(); + }, + }; + }); + return { started, closed }; +} + +test('a multi-flow Maestro suite collects real includes in one disposable client scope', async () => { + const root = mkdtempForTestSync('maestro-suite-sources-'); + const child = path.join(root, 'child.yaml'); + const entries = ['first.yaml', 'second.yaml'].map((name) => path.join(root, name)); + const flow = 'appId: demo.app\n---\n- runFlow: child.yaml\n'; + const included = 'appId: demo.app\n---\n- back\n'; + for (const entry of entries) fs.writeFileSync(entry, flow); + fs.writeFileSync(child, included); + const scope = await trackSourceRegistries(); + try { + const result = await prepareDaemonCommandRequest( + 'test', + { paths: entries, backend: 'maestro' }, + { env: process.env, cwd: root }, + ); + expect(result.options.replayScriptSources).toEqual( + entries.map((entry) => ({ entry, files: { [entry]: flow, [child]: included } })), + ); + expect(scope.started).toHaveBeenCalledTimes(1); + expect(scope.closed).toHaveBeenCalledTimes(1); + } finally { + scope.started.mockRestore(); + } +}); + +test('a failed Maestro source bundle closes its client registry', async () => { + const root = mkdtempForTestSync('maestro-suite-large-source-'); + const entry = path.join(root, 'large.yaml'); + fs.writeFileSync(entry, `# ${'x'.repeat(2 * 1024 * 1024)}\n`); + const scope = await trackSourceRegistries(); + try { + await expect( + prepareDaemonCommandRequest( + 'test', + { paths: [entry], backend: 'maestro' }, + { env: process.env, cwd: root }, + ), + ).rejects.toMatchObject({ code: 'INVALID_ARGS', details: { limitBytes: 2 * 1024 * 1024 } }); + expect(scope.started).toHaveBeenCalledTimes(1); + expect(scope.closed).toHaveBeenCalledTimes(1); + } finally { + scope.started.mockRestore(); + } +}); + +test.each([undefined, 'maestro'])( + 'native-only source collection with backend %s never starts a plugin registry', + async (backend) => { + const root = mkdtempForTestSync('native-suite-sources-'); + const entry = path.join(root, 'suite.ad'); + const script = 'open demo.app\nclose\n'; + fs.writeFileSync(entry, script); + const scope = await trackSourceRegistries(); + try { + const result = await prepareDaemonCommandRequest( + 'test', + { paths: [entry], backend }, + { env: { AGENT_DEVICE_HOME: path.join(root, 'empty-home') }, cwd: root }, + ); + expect(result.options.replayScriptSources).toEqual([{ entry, files: { [entry]: script } }]); + expect(scope.started).not.toHaveBeenCalled(); + expect(scope.closed).not.toHaveBeenCalled(); + } finally { + scope.started.mockRestore(); + } + }, +); + +function fixture() { + const root = mkdtempForTestSync('embedded-replay-'); + const entry = path.join(root, 'flow.yaml'); + fs.writeFileSync(entry, 'appId: com.example.app\n---\n- runFlow: child.yaml\n'); + fs.writeFileSync( + path.join(root, 'child.yaml'), + 'appId: com.example.app\n---\n- evalScript: ${output.value = "ok"}\n', + ); + const host = createTestHostEnvironment({ + env: { + AGENT_DEVICE_HOME: path.join(root, 'home'), + AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0', + }, + }); + return { root, entry, host, stateDir: path.join(root, 'state') }; +} + +async function nativePlugin() { + const resolved = await resolveProviderPlugins(await storePluginCandidates(process.env)); + const plugin = resolved.slots.find((slot) => slot.backend === 'ad')?.replayPlugin; + if (!plugin) throw new Error('Native replay test installation is missing'); + return plugin; +} + +async function trackedPlugin() { + const resolved = await resolveProviderPlugins(await storePluginCandidates(process.env)); + const maestro = resolved.slots.find((slot) => slot.backend === 'maestro')?.replayPlugin; + if (!maestro) throw new Error('Maestro test installation is missing'); + const calls = { setup: 0, create: 0, collect: 0, run: 0, dispose: 0 }; + const plugin: ReplayEnginePlugin = { + ...maestro, + setup: async (host) => { + calls.setup += 1; + const setup = await maestro.setup(host); + if (!setup.replayBackend) throw new Error('Expected a format backend'); + const replayBackend = setup.replayBackend; + return { + replayBackend: { + create: async (host) => { + calls.create += 1; + const backend = await replayBackend.create(host); + return { + ...backend, + collectSourceFiles: (params) => { + calls.collect += 1; + return backend.collectSourceFiles(params); + }, + runReplay: async (command) => { + calls.run += 1; + return await backend.runReplay(command); + }, + }; + }, + }, + dispose: async () => { + calls.dispose += 1; + await setup.dispose?.(); + }, + }; + }, + }; + return { plugin, calls }; +} + +test.each(['replay', 'test', 'batch-test'] as const)( + 'the embedded client prepares %s includes with one runtime registry and an empty store', + async (command) => { + const state = createRuntimeStateHandle(); + try { + await state.run(async () => { + const f = fixture(); + const { plugin, calls } = await trackedPlugin(); + const host = await startAgentDevice({ ...f, plugins: [plugin, await nativePlugin()] }); + const input = { path: f.entry, platform: 'ios' as const, backend: 'maestro' }; + const testInput = { paths: [f.entry], platform: 'ios' as const, backend: 'maestro' }; + try { + expect(JSON.parse(JSON.stringify(host.clientConfig))).toEqual(host.clientConfig); + if (command === 'replay') { + await expect(host.client.replay.run(input)).resolves.toMatchObject({ replayed: 1 }); + } else if (command === 'test') { + await expect(host.client.replay.test(testInput)).resolves.toMatchObject({ + passed: 1, + failed: 0, + }); + } else { + await expect( + host.client.batch.run({ steps: [{ command: 'test', input: testInput }] }), + ).resolves.toMatchObject({ + executed: 1, + results: [{ command: 'test', ok: true, data: { passed: 1, failed: 0 } }], + }); + } + expect(calls).toEqual({ setup: 1, create: 1, collect: 1, run: 1, dispose: 0 }); + } finally { + await host.close(); + } + expect(calls.dispose).toBe(1); + }); + } finally { + state.dispose(); + } + }, +); + +test('isolated embedded clients ignore a conflicting store and never borrow another runtime backend', async () => { + const f = fixture(); + const installation = crypto.randomUUID(); + const store = path.join( + f.host.env.AGENT_DEVICE_HOME!, + 'plugins', + installation, + 'node_modules', + '@agent-device/maestro', + ); + fs.mkdirSync(store, { recursive: true }); + fs.writeFileSync( + path.join(store, 'package.json'), + JSON.stringify({ + name: '@agent-device/maestro', + version: '0.0.0', + type: 'module', + exports: { './agent-device': './plugin.mjs' }, + }), + ); + fs.writeFileSync( + path.join(store, 'plugin.mjs'), + 'throw new Error("conflicting store must not be loaded by embedded client");', + ); + fs.writeFileSync( + path.join(f.host.env.AGENT_DEVICE_HOME!, 'config.json'), + JSON.stringify({ plugins: { '@agent-device/maestro': { installation } } }), + ); + const firstPlugin = await trackedPlugin(); + const secondPlugin = await trackedPlugin(); + const first = await startAgentDevice({ ...f, plugins: [firstPlugin.plugin] }); + let second: Awaited> | undefined; + try { + second = await startAgentDevice({ + ...f, + stateDir: path.join(f.root, 'second'), + plugins: [secondPlugin.plugin], + }); + await Promise.all( + [first, second].map(async ({ client }) => { + await expect( + client.replay.run({ path: f.entry, backend: 'maestro', platform: 'ios' }), + ).resolves.toMatchObject({ replayed: 1 }); + }), + ); + for (const { calls } of [firstPlugin, secondPlugin]) { + expect(calls).toEqual({ setup: 1, create: 1, collect: 1, run: 1, dispose: 0 }); + } + // An outside attacher retains its own caller-side installation requirement. + const outside = createAgentDeviceClient(first.clientConfig, { host: f.host }); + await expect(outside.replay.run({ path: f.entry, backend: 'maestro' })).rejects.toMatchObject({ + details: { reason: 'plugin_load_failed' }, + }); + await first.close(); + await expect( + second.client.replay.run({ path: f.entry, backend: 'maestro', platform: 'ios' }), + ).resolves.toMatchObject({ replayed: 1 }); + expect(firstPlugin.calls.dispose).toBe(1); + expect(secondPlugin.calls.dispose).toBe(0); + } finally { + await first.close(); + await second?.close(); + } + expect(secondPlugin.calls.dispose).toBe(1); +}); + +test('an embedded client without Maestro preserves the typed optional-plugin error', async () => { + const f = fixture(); + const host = await startAgentDevice(f); + try { + await expect( + host.client.replay.run({ path: f.entry, backend: 'maestro' }), + ).rejects.toMatchObject({ + details: { + reason: 'plugin-not-installed', + package: '@agent-device/maestro', + installCommand: 'agent-device plugins add @agent-device/maestro', + }, + }); + } finally { + await host.close(); + } +}); diff --git a/src/host.ts b/src/host.ts index 4519dee056..ce44a3e1b2 100644 --- a/src/host.ts +++ b/src/host.ts @@ -40,13 +40,18 @@ export async function startAgentDevice(options: StartAgentDeviceOptions): Promis ]); const codeIdentity = await resolveLocalDaemonCodeIdentity(); const output = { write: () => {} }; + const clientDeps: NonNullable[1]> = { host }; const runtime = await startDaemonRuntime({ host: runtimeHost, stdout: output, stderr: output, ownership: 'embedded', codeIdentity, - composeDeps: async (input) => await composeDaemonRuntimeDeps(input, candidates), + composeDeps: async (input) => { + const deps = await composeDaemonRuntimeDeps(input, candidates); + clientDeps.resolveReplayBackend = deps.resolveReplayBackend; + return deps; + }, }); try { const identity = runtime.identity; @@ -70,7 +75,7 @@ export async function startAgentDevice(options: StartAgentDeviceOptions): Promis }), }); return Object.freeze({ - client: createAgentDeviceClient(clientConfig, { host }), + client: createAgentDeviceClient(clientConfig, clientDeps), clientConfig, close: () => runtime.close(), }); diff --git a/src/mcp/__tests__/command-tools-parity.test.ts b/src/mcp/__tests__/command-tools-parity.test.ts index 9bf9ec89df..742cc6d748 100644 --- a/src/mcp/__tests__/command-tools-parity.test.ts +++ b/src/mcp/__tests__/command-tools-parity.test.ts @@ -19,6 +19,20 @@ afterEach(() => { let temporaryDirectory: string | undefined; +test('MCP replay discovery identifies optional plugins and installation scopes', () => { + const tools = listCommandTools({ outputSchemas: true }); + for (const name of ['replay', 'test']) { + const tool = tools.find((candidate) => candidate.name === name); + assert.ok(tool); + assert.match(tool.description, /plugin, install separately/); + assert.match(tool.description, /Native \.ad replay and test suites/); + assert.match(tool.description, /Install on the daemon host/); + assert.match(tool.description, /Install on the client for source collection/); + assert.ok(tool.inputSchema.properties); + assert.ok(tool.outputSchema); + } +}); + test('MCP collection results use object envelopes without changing object results or text', async () => { const results = { devices: [ @@ -216,6 +230,7 @@ test('MCP applies config-backed command defaults; explicit operator input is ref JSON.stringify({ iosXctestrunFile: configuredXctestrun, appsFilter: 'all' }), ); vi.stubEnv('HOME', home); + vi.stubEnv('AGENT_DEVICE_HOME', path.join(home, '.agent-device')); const calls: Array[0]> = []; const transport: AgentDeviceDaemonTransport = async (request) => { diff --git a/src/mcp/__tests__/command-tools-replay-plugin.test.ts b/src/mcp/__tests__/command-tools-replay-plugin.test.ts new file mode 100644 index 0000000000..0fcd8633a1 --- /dev/null +++ b/src/mcp/__tests__/command-tools-replay-plugin.test.ts @@ -0,0 +1,47 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { startAgentDevice } from '../../host.ts'; +import { createCommandToolExecutor } from '../command-tools.ts'; + +test.each([undefined, 'declared'] as const)( + 'MCP preserves optional replay recovery through the real client/router in %s mode', + async (structuredContent) => { + const root = mkdtempForTestSync('mcp-replay-plugin-'); + const script = path.join(root, 'flow.ad'); + fs.writeFileSync(script, 'open com.example.app\nclose\n'); + const runtime = await startAgentDevice({ + stateDir: path.join(root, 'state'), + plugins: [], + host: createTestHostEnvironment({ env: { AGENT_DEVICE_HOME: path.join(root, 'home') } }), + }); + try { + const executor = createCommandToolExecutor({ + createClient: () => runtime.client, + structuredContent, + }); + for (const [command, input] of [ + ['replay', { path: script }], + ['test', { paths: [script] }], + ] as const) { + const result = await executor.execute(command, input); + expect(result.isError).toBe(true); + expect(result.content[0]?.text).toContain('agent-device plugins add @agent-device/replay'); + expect(result.content[0]?.text).toContain('original command with all its arguments'); + if (structuredContent) + expect(result.structuredContent).toMatchObject({ + code: 'INVALID_ARGS', + details: { + reason: 'plugin-not-installed', + package: '@agent-device/replay', + installCommand: 'agent-device plugins add @agent-device/replay', + }, + }); + else expect(result.structuredContent).toBeUndefined(); + } + } finally { + await runtime.close(); + } + }, +); diff --git a/src/platform-runtime-android-adb-host.ts b/src/platform-runtime-android-adb-host.ts index 55e32ba9f7..d1fd13562c 100644 --- a/src/platform-runtime-android-adb-host.ts +++ b/src/platform-runtime-android-adb-host.ts @@ -97,6 +97,7 @@ bindAndroidAdbHost({ const lowered = lowerAndroidAdbInvocation(invocation, options, commandHostEnvironment().env); return await runCmd('adb', lowered.args, { ...lowered.options, + cwd: commandHostEnvironment().cwd, // adb's fork-server is a grandchild: without its own process group a deadline can only // signal `adb` itself, and the server keeps the stdio pipes open behind it. detached: process.platform !== 'win32', @@ -107,6 +108,7 @@ bindAndroidAdbHost({ const lowered = lowerAndroidAdbInvocation(invocation, options, commandHostEnvironment().env); const background = runCmdBackground('adb', lowered.args, { ...lowered.options, + cwd: commandHostEnvironment().cwd, allowFailure: true, captureOutput: false, }); diff --git a/src/platform-runtime-apple-application-tools.test.ts b/src/platform-runtime-apple-application-tools.test.ts index 414732110c..34140c73b4 100644 --- a/src/platform-runtime-apple-application-tools.test.ts +++ b/src/platform-runtime-apple-application-tools.test.ts @@ -97,6 +97,38 @@ test('preparing the runner spends the requested budget on stale-bundle cleanup, ); }); +test('the Apple tools refuse an Android hint target instead of dispatching it to ADB', async () => { + // The Apple owner's hint members take the Apple-only path. At the base these members forwarded + // to the neutral dispatcher, which sent an Android device to ADB, so an Apple-scoped grant could + // write Android app preferences. Refusal here happens before any executor is reached. + const androidDevice: DeviceInfo = { + platform: 'android', + id: 'emulator-5554', + name: 'Pixel', + kind: 'emulator', + booted: true, + }; + const tools = createAppleApplicationTools({}); + await expect( + tools.applyRuntimeHints(androidDevice, { + appId: 'com.example.app', + values: { metroHost: '10.0.0.10', metroPort: '8081' }, + }), + ).rejects.toMatchObject({ + code: 'INVALID_ARGS', + details: { reason: 'apple_runtime_hint_target_required', deviceId: 'emulator-5554' }, + }); + await expect( + tools.clearRuntimeHints(androidDevice, { + appId: 'com.example.app', + values: { metroHost: '10.0.0.10', metroPort: '8081' }, + }), + ).rejects.toMatchObject({ + code: 'INVALID_ARGS', + details: { reason: 'apple_runtime_hint_target_required' }, + }); +}); + test('a macOS frontmost-app open resolves the identity of the frontmost application', async () => { mockResolveFrontmostMacOsApp.mockResolvedValueOnce({ bundleId: 'com.apple.TextEdit', diff --git a/src/platform-runtime-apple-application-tools.ts b/src/platform-runtime-apple-application-tools.ts index af895d1a22..b99a05e6c0 100644 --- a/src/platform-runtime-apple-application-tools.ts +++ b/src/platform-runtime-apple-application-tools.ts @@ -104,13 +104,15 @@ export function createAppleApplicationTools(env: Readonly): AppleApplica startupTimeoutMs: input.timeoutMs, }); }, + // The Apple owner's own hint calls take the Apple-only path, so a non-Apple target reaching here + // is refused at the owner instead of being dispatched to ADB by the neutral dispatcher. applyRuntimeHints: async (device, input) => { - const { applyRuntimeHintValues } = await loadRuntimeHints(); - await applyRuntimeHintValues({ device, ...input }); + const { applyAppleRuntimeHintValues } = await loadRuntimeHints(); + await applyAppleRuntimeHintValues({ device, ...input }); }, clearRuntimeHints: async (device, input) => { - const { clearRuntimeHintValues } = await loadRuntimeHints(); - await clearRuntimeHintValues({ device, ...input }); + const { clearAppleRuntimeHintValues } = await loadRuntimeHints(); + await clearAppleRuntimeHintValues({ device, ...input }); }, dismissCloseAlerts: async (device, input) => await dismissMacOsCloseAlerts(device, input, env), detachRunnerSessionsForShutdown: async () => { diff --git a/src/platform-runtime-runtime-hints.ts b/src/platform-runtime-runtime-hints.ts index f571153c7e..37f8fd713b 100644 --- a/src/platform-runtime-runtime-hints.ts +++ b/src/platform-runtime-runtime-hints.ts @@ -1,4 +1,4 @@ -import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device'; +import { isApplePlatform, isIosFamily, type DeviceInfo } from '@agent-device/kernel/device'; import { deviceShellArgv } from '@agent-device/kernel/device-shell'; import { AppError, asAppError } from '@agent-device/kernel/errors'; import { escapeXmlTextAndAttribute } from '@agent-device/xml'; @@ -40,11 +40,7 @@ export async function applyRuntimeHintValues(params: { }): Promise { const { device, appId, values } = params; if (!appId) return; - const transport = resolveRuntimeTransportHints({ - metroHost: values.metroHost, - metroPort: values.metroPort ? Number(values.metroPort) : undefined, - bundleUrl: values.bundleUrl, - }); + const transport = resolveTransport(values); if (!transport) return; if (device.platform === 'android') { @@ -74,6 +70,57 @@ export async function clearRuntimeHintValues(params: { } } +/** + * The Apple hint path, for the Apple owner's own calls. It reads only Apple targets: an Android + * device is refused rather than dispatched to ADB, so an Apple-scoped grant cannot write Android + * app preferences. The dispatching entry point above never reaches a non-Apple device here. + */ +export async function applyAppleRuntimeHintValues(params: { + device: DeviceInfo; + appId?: string; + values: RuntimeHintValues; +}): Promise { + const { device, appId, values } = params; + if (!appId) return; + requireAppleRuntimeHintTarget(device); + const transport = resolveTransport(values); + if (!transport) return; + if (isIosFamily(device) && device.kind === 'simulator') { + await applyIosSimulatorRuntimeHints(device, appId, transport); + } +} + +/** Removes what {@link applyAppleRuntimeHintValues} wrote; refuses a non-Apple target the same way. */ +export async function clearAppleRuntimeHintValues(params: { + device: DeviceInfo; + appId?: string; +}): Promise { + const { device, appId } = params; + if (!appId) return; + requireAppleRuntimeHintTarget(device); + if (isIosFamily(device) && device.kind === 'simulator') { + await clearIosSimulatorRuntimeHints(device, appId); + } +} + +/** Hints are an Apple-owned operation only where the caller holds an Apple device. */ +function requireAppleRuntimeHintTarget(device: DeviceInfo): void { + if (isApplePlatform(device.platform)) return; + throw new AppError( + 'INVALID_ARGS', + `Apple runtime hints require an Apple device; '${device.id}' is a ${device.platform} device.`, + { reason: 'apple_runtime_hint_target_required', deviceId: device.id }, + ); +} + +function resolveTransport(values: RuntimeHintValues): ResolvedRuntimeTransport | undefined { + return resolveRuntimeTransportHints({ + metroHost: values.metroHost, + metroPort: values.metroPort ? Number(values.metroPort) : undefined, + bundleUrl: values.bundleUrl, + }); +} + function androidDevPrefsPaths(packageName: string): string[] { return [`shared_prefs/${packageName}_preferences.xml`, ANDROID_LEGACY_DEV_PREFS_PATH]; } diff --git a/src/provider-credential-fingerprint.test.ts b/src/provider-credential-fingerprint.test.ts index 6ef316818d..bc07da5514 100644 --- a/src/provider-credential-fingerprint.test.ts +++ b/src/provider-credential-fingerprint.test.ts @@ -1,15 +1,27 @@ -import fs from 'node:fs'; -import path from 'node:path'; import { expect, test } from 'vitest'; import { providerCredentialFingerprint as fingerprintFor } from '@agent-device/plugins/credential-fingerprint'; import { readDaemonProviderCredentials as daemonCredentialsFor } from './provider-credential-fingerprint.ts'; +import type { PluginInventoryEntry } from '@agent-device/contracts/plugin-inventory'; import type { EnvMap } from '@agent-device/kernel/source-value'; import { builtinPluginInventory } from './__tests__/test-utils/builtin-plugin-inventory.ts'; -import { pluginHome, selectPluginManifest } from '@agent-device/test-kit'; - -const inventory = await builtinPluginInventory(); -const providerCredentialFingerprint = (provider: string, env: EnvMap, leaseBackend?: string) => - fingerprintFor(provider, env, leaseBackend, inventory); +import { browserstackPluginInventory } from './__tests__/test-utils/browserstack-plugin-inventory.ts'; +import { awsDeviceFarmPluginInventory } from './__tests__/test-utils/aws-device-farm-plugin-inventory.ts'; +import { pluginHome, selectV2Plugin, v2RegistrationSource } from '@agent-device/test-kit'; +import { BUILTIN_PROVIDER_IDS } from './builtin-provider-ids.ts'; + +// BrowserStack and AWS Device Farm are installed plugins, so their credential variables come +// from their own inventory entries. +const inventory = [ + ...(await builtinPluginInventory()), + ...(await browserstackPluginInventory()), + ...(await awsDeviceFarmPluginInventory()), +]; +const providerCredentialFingerprint = ( + provider: string, + env: EnvMap, + leaseBackend?: string, + inventoryOverride?: readonly PluginInventoryEntry[], +) => fingerprintFor(provider, env, leaseBackend, inventoryOverride ?? inventory); const readDaemonProviderCredentials = (env: EnvMap, stateDir: string) => daemonCredentialsFor(env, stateDir, inventory); @@ -127,65 +139,107 @@ test('a Limrun lease fingerprint covers only the leased platform and the account ).toBe(ios(rotatedAndroid)); }); +/** The inventory the daemon publishes: the built-ins claim their ids, then the store loads. */ +async function storeInventory(env: Record) { + const { claimProviderIds, resolveProviderPlugins } = + await import('@agent-device/plugins/registry'); + const { storePluginCandidates } = await import('@agent-device/plugins/store'); + const resolved = await resolveProviderPlugins([ + ...claimProviderIds(BUILTIN_PROVIDER_IDS), + ...(await storePluginCandidates(env)), + ]); + return resolved.inventory(); +} + function pluginWithCredentialVariables(credentialVariables?: string[], provider = 'example') { const { home, env } = pluginHome(); - selectPluginManifest(home, { - name: '@example/provider', - version: '1.2.3', - agentDevicePlugin: { apiVersion: 1, provider, entry: './plugin.js', credentialVariables }, - }); - return env; + selectV2Plugin( + home, + '@example/provider', + v2RegistrationSource(provider, { + credentials: `{ variables: ${JSON.stringify(credentialVariables ?? [])} }`, + }), + ); + return { env: env as Record, home }; } -test('a plugin provider fingerprint hashes the variables its manifest declares', () => { - const home = pluginWithCredentialVariables(['EXAMPLE_USER', 'EXAMPLE_KEY']); +test('a plugin provider fingerprint hashes the variables its factory declares', async () => { + const { env: home } = pluginWithCredentialVariables(['EXAMPLE_USER', 'EXAMPLE_KEY']); + const inventory = await storeInventory(home); const env = { ...home, EXAMPLE_USER: 'user', EXAMPLE_KEY: 'key-1' }; - const fingerprint = providerCredentialFingerprint('example', env); + const fingerprint = providerCredentialFingerprint('example', env, undefined, inventory); expect(fingerprint).toMatch(/^v1:[0-9a-f]{16}$/); - expect(providerCredentialFingerprint('example', { ...env, UNRELATED: 'x' })).toBe(fingerprint); - expect(providerCredentialFingerprint('example', { ...env, EXAMPLE_KEY: 'key-2' })).not.toBe( - fingerprint, - ); - expect(providerCredentialFingerprint('example', { ...env, EXAMPLE_KEY: 'key-1 ' })).not.toBe( - fingerprint, - ); - expect(providerCredentialFingerprint('example', { ...home, EXAMPLE_USER: ' ' })).toBe(undefined); - expect(readDaemonProviderCredentials(env, '/state').fingerprint('example')).toBe(fingerprint); + expect( + providerCredentialFingerprint('example', { ...env, UNRELATED: 'x' }, undefined, inventory), + ).toBe(fingerprint); + expect( + providerCredentialFingerprint( + 'example', + { ...env, EXAMPLE_KEY: 'key-2' }, + undefined, + inventory, + ), + ).not.toBe(fingerprint); + expect( + providerCredentialFingerprint( + 'example', + { ...env, EXAMPLE_KEY: 'key-1 ' }, + undefined, + inventory, + ), + ).not.toBe(fingerprint); + expect( + providerCredentialFingerprint('example', { ...home, EXAMPLE_USER: ' ' }, undefined, inventory), + ).toBe(undefined); +}); + +test('a plugin provider without declared credential variables has no fingerprint', async () => { + const { env: home } = pluginWithCredentialVariables(); + const inventory = await storeInventory(home); + const env = { ...home, EXAMPLE_USER: 'user' }; + expect(providerCredentialFingerprint('example', env, undefined, inventory)).toBe(undefined); + expect(providerCredentialFingerprint('other', env, undefined, inventory)).toBe(undefined); }); -test('a plugin provider without declared credential variables has no fingerprint', () => { - const env = { ...pluginWithCredentialVariables(), EXAMPLE_USER: 'user' }; - expect(providerCredentialFingerprint('example', env)).toBe(undefined); - expect(providerCredentialFingerprint('other', env)).toBe(undefined); +test('a plugin declaration never adds a fingerprint to a bundled provider', async () => { + const { env: home } = pluginWithCredentialVariables(['AWS_ACCESS_KEY_ID'], 'limrun'); + const inventory = await storeInventory(home); + const env = { ...home, AWS_ACCESS_KEY_ID: 'id' }; + expect(providerCredentialFingerprint('limrun', env, undefined, inventory)).toBe(undefined); + // The built-in's own answer is unchanged by the store package that claims its id. + expect(providerCredentialFingerprint('limrun', env)).toBe(undefined); }); -test('a plugin declaration never adds a fingerprint to a bundled provider', () => { - const env = { - ...pluginWithCredentialVariables(['AWS_ACCESS_KEY_ID'], 'aws-device-farm'), - AWS_ACCESS_KEY_ID: 'id', - }; +test('an installed AWS Device Farm plugin declares no credential variables', async () => { + const env = { AWS_ACCESS_KEY_ID: 'id', AWS_SECRET_ACCESS_KEY: 'secret' }; + // The package answers through the AWS CLI credential chain, so nothing is hashed. expect(providerCredentialFingerprint('aws-device-farm', env)).toBe(undefined); + expect(readDaemonProviderCredentials(env, '/state').fingerprint('aws-device-farm')).toBe( + undefined, + ); }); -function testMuPluginEnv(): Record { - const manifest = path.resolve(import.meta.dirname, '../packages/provider-testmu/package.json'); +test('a store plugin declares per-backend credential variables in code', async () => { const { home, env } = pluginHome(); - selectPluginManifest(home, JSON.parse(fs.readFileSync(manifest, 'utf8'))); - return env; -} - -test('the bundled TestMu AI plugin manifest fingerprints its LT credentials', () => { - const home = testMuPluginEnv(); - const env = { ...home, LT_USERNAME: 'user', LT_ACCESS_KEY: 'key-1' }; - const fingerprint = providerCredentialFingerprint('testmu', env); - - expect(fingerprint).toMatch(/^v1:[0-9a-f]{16}$/); - expect(providerCredentialFingerprint('testmu', { ...env })).toBe(fingerprint); - expect(providerCredentialFingerprint('testmu', { ...env, LT_ACCESS_KEY: 'key-2' })).not.toBe( - fingerprint, + selectV2Plugin( + home, + '@example/backend', + v2RegistrationSource('example', { + credentials: + '{ variables: ["EXAMPLE_ACCOUNT"], byBackend: { "shared-session": ["EXAMPLE_POOL"] } }', + }), + ); + const inventory = await storeInventory(env as Record); + const envMap = { ...env, EXAMPLE_ACCOUNT: 'acct', EXAMPLE_POOL: 'pool-1' }; + const fingerprint = (values: Record, leaseBackend?: string) => + providerCredentialFingerprint('example', values, leaseBackend, inventory); + + // Without a backend the common variables answer; the pool belongs to one backend only. + expect(fingerprint(envMap)).toMatch(/^v1:[0-9a-f]{16}$/); + expect(fingerprint({ ...envMap, EXAMPLE_POOL: 'pool-2' })).toBe(fingerprint(envMap)); + expect(fingerprint({ ...envMap, EXAMPLE_POOL: 'pool-2' }, 'shared-session')).not.toBe( + fingerprint(envMap, 'shared-session'), ); - expect(providerCredentialFingerprint('testmu', home)).toBe(undefined); - expect(readDaemonProviderCredentials(env, '/state').fingerprint('testmu')).toBe(fingerprint); - expect(readDaemonProviderCredentials(home, '/state').fingerprint('testmu')).toBe(undefined); + expect(fingerprint({ EXAMPLE_ACCOUNT: 'acct' }, 'shared-session')).toBe(undefined); }); diff --git a/src/provider-device-runtimes.test.ts b/src/provider-device-runtimes.test.ts index a023aba458..5ff9a3f553 100644 --- a/src/provider-device-runtimes.test.ts +++ b/src/provider-device-runtimes.test.ts @@ -42,7 +42,11 @@ test('Limrun retries an expired provider lease persisted by a daemon before rest try { firstDaemon = await startPublicDaemonRuntime({ stateDir, env }); - const client = createAgentDeviceClient({ stateDir, daemonTransport: 'http' }); + const client = createAgentDeviceClient({ + stateDir, + daemonTransport: 'http', + session: 'agent-a', + }); const lease = await client.leases.allocate({ tenant: 'team-a', runId: 'run-a', diff --git a/src/provider-device-runtimes.ts b/src/provider-device-runtimes.ts index ee678d0c93..7bc8e5c990 100644 --- a/src/provider-device-runtimes.ts +++ b/src/provider-device-runtimes.ts @@ -4,12 +4,14 @@ import type { PluginCleanupOutcome, PluginInventoryEntry, } from '@agent-device/contracts/plugin-inventory'; -import type { PluginCandidate } from '@agent-device/plugins/registry'; +import type { PluginCandidate, PluginRegistryPolicy } from '@agent-device/plugins/registry'; import type { PlatformRuntimeProviderRegistration } from './platform-runtime-gateway.ts'; import { builtinProviderCandidates } from './builtin-provider-plugins.ts'; import { PROVIDER_PLUGIN_POLICY } from './provider-plugin-policy.ts'; export type ProviderRuntimeComposition = Readonly<{ + resolveReplayBackend: import('@agent-device/plugins/replay-backend').ReplayBackendResolver; + resolveReplayExecution: import('@agent-device/contracts/replay-execution').ReplayExecutionResolver; runtimes: readonly ProviderDeviceRuntime[]; platformModules: readonly PlatformRuntimeProviderRegistration[]; /** Every plugin the registry saw, built-in or not, active or failed. */ @@ -25,17 +27,27 @@ export type ProviderRuntimeComposition = Readonly<{ export async function createDaemonProviderRuntimeComposition( host: HostEnvironment, ): Promise { - const { storePluginCandidates } = await import('@agent-device/plugins/store'); - return await createEmbeddedProviderRuntimeComposition( - host, - await storePluginCandidates(host.env), - ); + const { storePluginCandidates, createPluginSelectionGuard } = + await import('@agent-device/plugins/store'); + const candidates = await storePluginCandidates(host.env); + return await composeProviderRuntime(host, candidates, { + ...PROVIDER_PLUGIN_POLICY, + assertReplaySelectionCurrent: createPluginSelectionGuard(candidates, host.env), + }); } /** Composes built-ins followed by supplied candidates without reading the plugin store. */ export async function createEmbeddedProviderRuntimeComposition( host: HostEnvironment, candidates: readonly PluginCandidate[], +): Promise { + return await composeProviderRuntime(host, candidates, PROVIDER_PLUGIN_POLICY); +} + +async function composeProviderRuntime( + host: HostEnvironment, + candidates: readonly PluginCandidate[], + policy: PluginRegistryPolicy, ): Promise { const { resolveProviderPlugins, startProviderRegistry } = await import('@agent-device/plugins/registry'); @@ -43,7 +55,7 @@ export async function createEmbeddedProviderRuntimeComposition( ...builtinProviderCandidates(host), ...candidates, ]); - const registry = await startProviderRegistry(resolved, host.env, PROVIDER_PLUGIN_POLICY); + const registry = await startProviderRegistry(resolved, host, policy); return Object.freeze({ runtimes: Object.freeze(registry.registrations.map(({ runtime }) => runtime)), platformModules: Object.freeze( @@ -53,6 +65,8 @@ export async function createEmbeddedProviderRuntimeComposition( })), ), inventory: registry.inventory, + resolveReplayBackend: registry.resolveReplayBackend, + resolveReplayExecution: registry.resolveReplayExecution, shutdown: registry.close, }); } diff --git a/src/provider-limrun-runtime.ts b/src/provider-limrun-runtime.ts deleted file mode 100644 index 793e28d213..0000000000 --- a/src/provider-limrun-runtime.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { captureSdkHost } from './sdk/host.ts'; -import type { - DeviceInventoryProvider, - LeaseLifecycleProvider, - ProviderDeviceInstallOptions, - ProviderDeviceInstallResult, - ProviderDeviceRuntime, - ProviderExpiredLeaseRecovery, - ProviderPortReverseOptions, -} from '@agent-device/contracts/device'; -import type { Interactor } from '@agent-device/contracts/interactor-types'; -import type { DeviceInfo } from '@agent-device/kernel/device'; -import { - createLimrunRuntime, - type LimrunRuntime as LimrunRuntimeImplementation, - type LimrunRuntimeOptions, - LIMRUN_PROVIDER, -} from '@agent-device/provider-limrun'; -import { createLimrunRuntimeDependencies } from './sdk/limrun-runtime-dependencies.ts'; -import type { LimrunDeviceSession } from './sdk/limrun-runtime-types.ts'; - -export class LimrunRuntime implements ProviderDeviceRuntime { - private readonly implementation: LimrunRuntimeImplementation; - // Called through ProviderDeviceRuntime composition and the public Limrun SDK. - readonly provider = LIMRUN_PROVIDER; - - constructor(options: LimrunRuntimeOptions) { - this.implementation = createLimrunRuntime( - options, - createLimrunRuntimeDependencies(captureSdkHost()), - ); - } - - get leaseLifecycle(): LeaseLifecycleProvider { - return this.implementation.leaseLifecycle; - } - - get recoverExpiredLease(): ProviderExpiredLeaseRecovery { - return this.implementation.recoverExpiredLease; - } - - // Called through ProviderDeviceRuntime composition. - get deviceInventoryProvider(): DeviceInventoryProvider { - return this.implementation.deviceInventoryProvider; - } - - // Called through ProviderDeviceRuntime composition and the public Limrun SDK. - ownsDevice(device: DeviceInfo): boolean { - return this.implementation.ownsDevice(device); - } - - getInteractor(device: DeviceInfo): Interactor | undefined { - return this.implementation.getInteractor(device); - } - - getDeviceSession(device: DeviceInfo): LimrunDeviceSession | undefined { - return this.implementation.getDeviceSession(device) as LimrunDeviceSession | undefined; - } - - async installApp( - device: DeviceInfo, - app: string, - appPath: string, - options?: ProviderDeviceInstallOptions, - ): Promise { - return await this.implementation.installApp?.(device, app, appPath, options); - } - - // Called through ProviderDeviceRuntime composition and the public Limrun SDK. - async installInstallablePath( - device: DeviceInfo, - installablePath: string, - options?: ProviderDeviceInstallOptions, - ): Promise { - return await this.implementation.installInstallablePath?.(device, installablePath, options); - } - - async configurePortReverse( - options: ProviderPortReverseOptions, - ): Promise | undefined> { - return await this.implementation.configurePortReverse?.(options); - } - - async shutdown(): Promise { - await this.implementation.shutdown(); - } -} - -export type { LimrunRuntimeOptions }; diff --git a/src/provider-plugin-policy-revyl.test.ts b/src/provider-plugin-policy-revyl.test.ts index 7dda569b79..8af8ca0127 100644 --- a/src/provider-plugin-policy-revyl.test.ts +++ b/src/provider-plugin-policy-revyl.test.ts @@ -51,7 +51,11 @@ test('a Revyl device the shutdown could not stop is named in the message and hin const resolved = await resolveProviderPlugins([ { source: 'embedder', provider: 'revyl', load: () => revyl({ apiKey: 'test-key', apiUrl }) }, ]); - const registry = await startProviderRegistry(resolved, {}, PROVIDER_PLUGIN_POLICY); + const registry = await startProviderRegistry( + resolved, + { env: {}, cwd: '/' }, + PROVIDER_PLUGIN_POLICY, + ); const runtime = registry.registrations[0]!.runtime; const lease: DeviceLease = { leaseId: 'lease-1', diff --git a/src/provider-plugin-policy.test.ts b/src/provider-plugin-policy.test.ts index 8e0c4f8776..2bcd3fa89f 100644 --- a/src/provider-plugin-policy.test.ts +++ b/src/provider-plugin-policy.test.ts @@ -8,7 +8,7 @@ import { startProviderRegistry, } from '@agent-device/plugins/registry'; import { storePluginCandidates } from '@agent-device/plugins/store'; -import { pluginHome, selectPlugin, webDriverPluginSource } from '@agent-device/test-kit'; +import { pluginHome, selectV2Plugin, webDriverPluginSource } from '@agent-device/test-kit'; import { PROVIDER_PLUGIN_POLICY } from './provider-plugin-policy.ts'; const realFetch = globalThis.fetch; @@ -30,7 +30,7 @@ async function startStoreRegistry(env: NodeJS.ProcessEnv) { ...claimProviderIds([]), ...(await storePluginCandidates(env)), ]); - return await startProviderRegistry(resolved, env, PROVIDER_PLUGIN_POLICY); + return await startProviderRegistry(resolved, { env, cwd: '/' }, PROVIDER_PLUGIN_POLICY); } afterEach(() => { @@ -39,7 +39,7 @@ afterEach(() => { test('a WebDriver plugin allocates through the shared engine under the process policy', async () => { const { home, env } = pluginHome(); - selectPlugin(home, 'example', 'example', webDriverPluginSource('example', ['awsProjectArn'])); + selectV2Plugin(home, 'example', webDriverPluginSource('example', ['awsProjectArn'])); const registry = await startStoreRegistry(env); const { runtime, platformModule } = registry.registrations[0]!; assert.equal(runtime.provider, 'example'); @@ -71,11 +71,13 @@ test('a WebDriver plugin allocates through the shared engine under the process p test('a WebDriver descriptor missing what the engine needs is listed as an invalid plugin', async () => { const { home, env } = pluginHome(); - selectPlugin( + selectV2Plugin( home, 'example', - 'example', - "export default () => ({ webDriver: { provider: 'example' } });", + `export default () => ({ + apiVersion: 2, provider: 'example', credentials: { variables: [] }, + setup: async () => ({ webDriver: { provider: 'example' } }), + });`, ); const registry = await startStoreRegistry(env); assert.deepEqual(registry.registrations, []); diff --git a/src/provider-webdriver.test.ts b/src/provider-webdriver.test.ts deleted file mode 100644 index e048733061..0000000000 --- a/src/provider-webdriver.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; -import { test } from 'vitest'; -import { bundledCloudWebDriverProvider } from '@agent-device/provider-webdriver'; -import { createBundledCloudWebDriverHost } from './provider-webdriver.ts'; -import { mkdtempForTestSync } from '@agent-device/test-kit'; - -test('bundled AWS artifact lookup runs through the host command adapter', async () => { - const tempDir = mkdtempForTestSync('agent-device-provider-webdriver-'); - const awsPath = path.join(tempDir, 'aws'); - const callsPath = path.join(tempDir, 'aws-calls.ndjson'); - const previousPath = process.env.PATH; - const previousCallsPath = process.env.AGENT_DEVICE_TEST_AWS_CALLS_PATH; - fs.writeFileSync( - awsPath, - [ - '#!/usr/bin/env node', - "const fs = require('node:fs');", - 'fs.appendFileSync(process.env.AGENT_DEVICE_TEST_AWS_CALLS_PATH, `${JSON.stringify(process.argv.slice(2))}\\n`);', - "process.stdout.write(JSON.stringify({ artifacts: [{ arn: 'artifact-1', name: 'video', type: 'VIDEO', url: 'https://aws.example/video.mp4' }] }));", - ].join('\n'), - ); - fs.chmodSync(awsPath, 0o755); - process.env.PATH = `${tempDir}${path.delimiter}${previousPath ?? ''}`; - process.env.AGENT_DEVICE_TEST_AWS_CALLS_PATH = callsPath; - - try { - const provider = bundledCloudWebDriverProvider('aws-device-farm'); - assert.ok(provider); - const { webDriver } = provider.create( - createBundledCloudWebDriverHost({ AWS_REGION: 'us-west-2' }), - ); - const providerSessionId = 'arn:aws:devicefarm:us-west-2:123:session/project/session/1'; - const result = await webDriver.listArtifacts?.({ - provider: 'aws-device-farm', - providerSessionId, - }); - - assert.equal(result?.provider, 'aws-device-farm'); - assert.equal(result?.status, 'ready'); - assert.deepEqual( - result?.cloudArtifacts.map(({ kind, url }) => ({ kind, url })), - [ - { kind: 'video', url: 'https://aws.example/video.mp4' }, - { kind: 'video', url: 'https://aws.example/video.mp4' }, - ], - ); - const calls = fs - .readFileSync(callsPath, 'utf8') - .trim() - .split('\n') - .map((line) => JSON.parse(line) as string[]) - .sort((left, right) => (left[7] ?? '').localeCompare(right[7] ?? '')); - assert.deepEqual( - calls.map((args) => args.slice(0, 6)), - [ - ['devicefarm', 'list-artifacts', '--region', 'us-west-2', '--arn', providerSessionId], - ['devicefarm', 'list-artifacts', '--region', 'us-west-2', '--arn', providerSessionId], - ], - ); - assert.deepEqual( - calls.map((args) => args.slice(6)), - [ - ['--type', 'FILE', '--output', 'json'], - ['--type', 'LOG', '--output', 'json'], - ], - ); - } finally { - restoreEnv('PATH', previousPath); - restoreEnv('AGENT_DEVICE_TEST_AWS_CALLS_PATH', previousCallsPath); - fs.rmSync(tempDir, { recursive: true, force: true }); - } -}); - -function restoreEnv(name: string, value: string | undefined): void { - if (value === undefined) { - delete process.env[name]; - return; - } - process.env[name] = value; -} diff --git a/src/provider-webdriver.ts b/src/provider-webdriver.ts deleted file mode 100644 index b2ab2176ed..0000000000 --- a/src/provider-webdriver.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { - bundledCloudWebDriverProvider, - type CloudWebDriverConnection, - type CloudWebDriverProviderHost, -} from '@agent-device/provider-webdriver'; -import { runCmd } from '@agent-device/host-kit/command'; -import { readVersion } from '@agent-device/host-kit/version'; -import type { EnvMap } from '@agent-device/kernel/source-value'; - -/** What this process hands a bundled provider: the plugin host shape plus a host-command runner. */ -export function createBundledCloudWebDriverHost(env: EnvMap): CloudWebDriverProviderHost { - return { - env, - clientVersion: readVersion(), - runHostCommand: async (command, args) => { - const result = await runCmd(command, [...args], { - maxBuffer: 10 * 1024 * 1024, - timeoutMs: 30_000, - }); - return { stdout: result.stdout }; - }, - }; -} - -/** The `connect` callbacks of a bundled provider, or undefined for any other provider name. */ -export function bundledCloudWebDriverConnection( - provider: string, - env: EnvMap, -): CloudWebDriverConnection | undefined { - return bundledCloudWebDriverProvider(provider)?.create(createBundledCloudWebDriverHost(env)) - .connection; -} diff --git a/src/sdk/android-adb.test.ts b/src/sdk/android-adb.test.ts index 7472c2fcee..72d0422b42 100644 --- a/src/sdk/android-adb.test.ts +++ b/src/sdk/android-adb.test.ts @@ -39,29 +39,47 @@ test('getAndroidAppStateWithAdb falls back to activity focus and settles empty', }); test.skipIf(process.platform === 'win32')( - 'standalone public Android shell helpers establish their process host before dispatch', + 'public Android helpers retain explicit hosts and only their own request overlays', async () => { const { runAndroidShell, runAndroidExecOut } = await import('./android-adb.ts'); const { ANDROID_EMULATOR, mkdtempForTestSync } = await import('@agent-device/test-kit'); - const { writeFileSync, chmodSync } = await import('node:fs'); + const { withCommandHost } = await import('@agent-device/host-kit/command'); + const { writeFileSync, chmodSync, realpathSync } = await import('node:fs'); const { join } = await import('node:path'); const bin = mkdtempForTestSync('agent-device-sdk-adb-'); - const adbPath = join(bin, 'adb'); writeFileSync( - adbPath, - `#!${process.execPath}\nprocess.stdout.write(JSON.stringify(process.argv.slice(2)));`, + join(bin, 'adb'), + `#!${process.execPath}\nprocess.stdout.write(JSON.stringify({args:process.argv.slice(2),owner:process.env.SDK_OWNER,cwd:process.cwd()}));`, ); - chmodSync(adbPath, 0o755); - const previousPath = process.env.PATH; - process.env.PATH = bin; - try { - const shell = await runAndroidShell(ANDROID_EMULATOR, ['id']); - const execOut = await runAndroidExecOut(ANDROID_EMULATOR, ['id']); - assert.deepEqual(JSON.parse(shell.stdout), ['-s', ANDROID_EMULATOR.id, 'shell', 'id']); - assert.deepEqual(JSON.parse(execOut.stdout), ['-s', ANDROID_EMULATOR.id, 'exec-out', 'id']); - } finally { - if (previousPath === undefined) delete process.env.PATH; - else process.env.PATH = previousPath; + chmodSync(join(bin, 'adb'), 0o755); + const host = (owner: string) => ({ env: { PATH: bin, SDK_OWNER: owner }, cwd: bin }); + const results = await withCommandHost( + { host: host('foreign'), requestEnv: { SDK_OWNER: 'request' } }, + () => + Promise.all([ + runAndroidShell(ANDROID_EMULATOR, ['id'], host('shell')), + runAndroidExecOut(ANDROID_EMULATOR, ['id'], host('exec')), + ]), + ); + for (const [index, command, owner] of [ + [0, 'shell', 'shell'], + [1, 'exec-out', 'exec'], + ] as const) { + assert.deepEqual(JSON.parse(results[index].stdout), { + args: ['-s', ANDROID_EMULATOR.id, command, 'id'], + owner, + cwd: realpathSync(bin), + }); } + const sharedHost = host('base'); + const scoped = await withCommandHost( + { host: sharedHost, requestEnv: { SDK_OWNER: 'overlay' } }, + () => runAndroidShell(ANDROID_EMULATOR, ['id'], sharedHost), + ); + assert.deepEqual(JSON.parse(scoped.stdout), { + args: ['-s', ANDROID_EMULATOR.id, 'shell', 'id'], + owner: 'overlay', + cwd: realpathSync(bin), + }); }, ); diff --git a/src/sdk/android-adb.ts b/src/sdk/android-adb.ts index 46c187b437..57de3c4319 100644 --- a/src/sdk/android-adb.ts +++ b/src/sdk/android-adb.ts @@ -1,3 +1,4 @@ +import type { HostEnvironment } from '@agent-device/kernel/source-value'; import '../platform-runtime-android-adb-host.ts'; export { createAndroidPortReverseManager, @@ -14,12 +15,22 @@ import { } from '@agent-device/platform-android/mechanics'; import { withSdkHost } from './host.ts'; -export async function runAndroidShell(...args: Parameters) { - return await withSdkHost(() => runAndroidShellOnHost(...args)); +export async function runAndroidShell( + device: Parameters[0], + words: Parameters[1], + host: HostEnvironment, + options?: Parameters[2], +) { + return await withSdkHost(host, () => runAndroidShellOnHost(device, words, options)); } -export async function runAndroidExecOut(...args: Parameters) { - return await withSdkHost(() => runAndroidExecOutOnHost(...args)); +export async function runAndroidExecOut( + device: Parameters[0], + words: Parameters[1], + host: HostEnvironment, + options?: Parameters[2], +) { + return await withSdkHost(host, () => runAndroidExecOutOnHost(device, words, options)); } export type { ShellWord } from '@agent-device/kernel/device-shell'; diff --git a/src/sdk/artifacts.test.ts b/src/sdk/artifacts.test.ts index 493eaa06c0..061a122273 100644 --- a/src/sdk/artifacts.test.ts +++ b/src/sdk/artifacts.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; -import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { chmodSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs'; import path from 'node:path'; import { test } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; @@ -8,53 +8,77 @@ import { withCommandHost } from '@agent-device/host-kit/command'; import { resolveAndroidArchivePackageName } from './artifacts.ts'; test.skipIf(process.platform === 'win32')( - 'standalone artifact resolution uses aapt after an unparseable manifest without poisoning later scoped calls', + 'public artifact resolution keeps each concurrent caller SDK and environment', async () => { const root = mkdtempForTestSync('agent-device-sdk-artifacts-'); + writeFileSync(path.join(root, 'AndroidManifest.xml'), ''); + const archive = path.join(root, 'fallback.apk'); + execFileSync('zip', ['-q', archive, 'AndroidManifest.xml'], { cwd: root }); + const host = (owner: string) => { + const sdk = path.join(root, owner); + const tools = path.join(sdk, 'build-tools', '99.0.0'); + mkdirSync(tools, { recursive: true }); + const aapt = path.join(tools, 'aapt'); + writeFileSync( + aapt, + `#!${process.execPath}\nprocess.stdout.write("package: name='com.example.${owner}' versionCode='1'\\n");`, + ); + chmodSync(aapt, 0o755); + return { + env: { ANDROID_HOME: sdk, ANDROID_SDK_ROOT: sdk, PATH: process.env.PATH }, + cwd: root, + }; + }; + const first = host('first'); + const second = host('second'); + assert.equal( + await resolveAndroidArchivePackageName(path.basename(archive), first), + 'com.example.first', + ); + const result = await withCommandHost({ host: host('foreign'), requestEnv: undefined }, () => + Promise.all([ + resolveAndroidArchivePackageName(path.basename(archive), first), + resolveAndroidArchivePackageName(path.basename(archive), second), + ]), + ); + assert.deepEqual(result, ['com.example.first', 'com.example.second']); + }, +); + +test.skipIf(process.platform === 'win32').each(['manifest', 'aapt'] as const)( + 'public archive inspection runs %s tools in the supplied cwd with a relative PATH', + async (source) => { + const root = realpathSync(mkdtempForTestSync('agent-device-sdk-archive-cwd-')); + const bin = path.join(root, 'bin'); const sdk = path.join(root, 'sdk'); const tools = path.join(sdk, 'build-tools', '99.0.0'); + mkdirSync(bin); mkdirSync(tools, { recursive: true }); - const manifest = path.join(root, 'AndroidManifest.xml'); - writeFileSync(manifest, ''); - const archive = path.join(root, 'fallback.apk'); - execFileSync('zip', ['-q', archive, 'AndroidManifest.xml'], { cwd: root }); - const calls = path.join(root, 'aapt-calls.jsonl'); + const unzip = path.join(bin, 'unzip'); const aapt = path.join(tools, 'aapt'); + const cwdGuard = `if(process.cwd()!==${JSON.stringify(root)})process.exit(2);`; + writeFileSync( + unzip, + `#!${process.execPath}\n${cwdGuard}${ + source === 'manifest' + ? `process.stdout.write('');` + : 'process.exit(1);' + }`, + ); writeFileSync( aapt, - `#!${process.execPath}\n` + - `require('node:fs').appendFileSync(${JSON.stringify(calls)}, JSON.stringify(process.argv.slice(2))+'\\n');\n` + - `process.stdout.write("package: name='com.example.fallback' versionCode='1'\\n");\n`, + `#!${process.execPath}\n${cwdGuard}process.stdout.write("package: name='com.example.aapt' versionCode='1'\\n");`, ); + chmodSync(unzip, 0o755); chmodSync(aapt, 0o755); - const previous = { - ANDROID_HOME: process.env.ANDROID_HOME, - ANDROID_SDK_ROOT: process.env.ANDROID_SDK_ROOT, - }; - process.env.ANDROID_HOME = sdk; - process.env.ANDROID_SDK_ROOT = sdk; - try { - const standalone = await resolveAndroidArchivePackageName(archive); - const scoped = await withCommandHost( - { host: { env: { ...process.env }, cwd: root }, requestEnv: undefined }, - () => resolveAndroidArchivePackageName(archive), - ); - assert.deepEqual([standalone, scoped], ['com.example.fallback', 'com.example.fallback']); - assert.deepEqual( - readFileSync(calls, 'utf8') - .trim() - .split('\n') - .map((line) => JSON.parse(line)), - [ - ['dump', 'badging', archive], - ['dump', 'badging', archive], - ], - ); - } finally { - for (const [key, value] of Object.entries(previous)) { - if (value === undefined) delete process.env[key]; - else process.env[key] = value; - } - } + const archive = path.join(root, 'app.apk'); + writeFileSync(archive, 'archive fixture'); + assert.equal( + await resolveAndroidArchivePackageName(archive, { + cwd: root, + env: { PATH: './bin', ANDROID_SDK_ROOT: sdk }, + }), + `com.example.${source}`, + ); }, ); diff --git a/src/sdk/artifacts.ts b/src/sdk/artifacts.ts index 379bfd87bc..61090690bd 100644 --- a/src/sdk/artifacts.ts +++ b/src/sdk/artifacts.ts @@ -1,3 +1,5 @@ +import path from 'node:path'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { loadAndroidMechanics } from '../platform-runtime-android-mechanics.ts'; import { withSdkHost } from './host.ts'; @@ -5,10 +7,12 @@ type ResolveAndroidArchivePackageName = typeof import('@agent-device/platform-android/mechanics').resolveAndroidArchivePackageName; export async function resolveAndroidArchivePackageName( - ...args: Parameters + archivePath: string, + host: HostEnvironment, + signal?: AbortSignal, ): Promise>> { - return await withSdkHost(async () => { + return await withSdkHost(host, async () => { const { resolveAndroidArchivePackageName: resolve } = await loadAndroidMechanics(); - return await resolve(...args); + return await resolve(path.resolve(host.cwd, archivePath), signal, host.cwd); }); } diff --git a/src/sdk/host-types.ts b/src/sdk/host-types.ts index e3ded0cc93..85a0392152 100644 --- a/src/sdk/host-types.ts +++ b/src/sdk/host-types.ts @@ -2,6 +2,7 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { AgentDeviceClientConfig } from '@agent-device/contracts/client'; import type { AgentDeviceClient } from '@agent-device/command-surface'; import type { AgentDevicePlugin } from '@agent-device/plugins/contract'; +import type { ReplayEnginePlugin } from '@agent-device/plugins/replay-backend'; import type { ShutdownReport } from '@agent-device/daemon'; export type StartAgentDeviceOptions = Readonly<{ @@ -10,7 +11,7 @@ export type StartAgentDeviceOptions = Readonly<{ /** The environment and working directory to run with. Defaults to one captured copy of this process's. */ host?: HostEnvironment; /** Imported plugins to register after the built-ins. The plugin store is not read. */ - plugins?: readonly AgentDevicePlugin[]; + plugins?: readonly (AgentDevicePlugin | ReplayEnginePlugin)[]; }>; export type AgentDeviceHost = Readonly<{ diff --git a/src/sdk/host.ts b/src/sdk/host.ts index a91f70e955..f7b2a20496 100644 --- a/src/sdk/host.ts +++ b/src/sdk/host.ts @@ -1,12 +1,6 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import { captureHostEnvironment } from '@agent-device/host-kit/process'; import { withCommandHost } from '@agent-device/host-kit/command'; -/** Released SDK defaults removed in 0.22 (#3759). */ -export function captureSdkHost(): HostEnvironment { - return captureHostEnvironment(process); -} - -export async function withSdkHost(task: () => Promise): Promise { - return await withCommandHost({ host: captureSdkHost(), requestEnv: undefined }, task); +export async function withSdkHost(host: HostEnvironment, task: () => Promise): Promise { + return await withCommandHost({ host, requestEnv: undefined }, task); } diff --git a/src/sdk/limrun-android-performance.test.ts b/src/sdk/limrun-runtime-dependencies-android-performance.test.ts similarity index 100% rename from src/sdk/limrun-android-performance.test.ts rename to src/sdk/limrun-runtime-dependencies-android-performance.test.ts diff --git a/src/sdk/limrun-host-scope.test.ts b/src/sdk/limrun-runtime-dependencies-host-scope.test.ts similarity index 100% rename from src/sdk/limrun-host-scope.test.ts rename to src/sdk/limrun-runtime-dependencies-host-scope.test.ts diff --git a/src/sdk/limrun-runtime-dependencies.test.ts b/src/sdk/limrun-runtime-dependencies.test.ts index 07e05ce4cb..2313b2cbb4 100644 --- a/src/sdk/limrun-runtime-dependencies.test.ts +++ b/src/sdk/limrun-runtime-dependencies.test.ts @@ -35,8 +35,12 @@ vi.mock('@agent-device/platform-apple/install-artifact', async (importOriginal) })); test('Limrun construction defers operation and opposite-platform helper modules', async () => { - const { LimrunRuntime } = await import('../provider-limrun-runtime.ts'); - const runtime = new LimrunRuntime({ apiKey: 'lim_test_key' }); + const { createLimrunRuntime } = await import('@agent-device/provider-limrun'); + const { createLimrunRuntimeDependencies } = await import('./limrun-runtime-dependencies.ts'); + const runtime = createLimrunRuntime( + { apiKey: 'lim_test_key' }, + createLimrunRuntimeDependencies({ env: process.env, cwd: process.cwd() }), + ); assert.deepEqual(moduleLoads, { androidAppHelpers: 0, @@ -45,7 +49,6 @@ test('Limrun construction defers operation and opposite-platform helper modules' }); await runtime.shutdown(); - const { createLimrunRuntimeDependencies } = await import('./limrun-runtime-dependencies.ts'); const dependencies = createLimrunRuntimeDependencies({ env: process.env, cwd: process.cwd() }); const device = { platform: 'android' as const, diff --git a/src/sdk/limrun-runtime-types.ts b/src/sdk/limrun-runtime-types.ts deleted file mode 100644 index 4d4699f236..0000000000 --- a/src/sdk/limrun-runtime-types.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { - AndroidAdbProvider, - AndroidKeyboardDismissResult, - AndroidKeyboardState, -} from '@agent-device/platform-android/mechanics'; -import type { - LimrunAndroidDeviceSession as InternalLimrunAndroidDeviceSession, - LimrunIosDeviceSession, -} from '@agent-device/provider-limrun'; - -export type LimrunAndroidDeviceSession = Omit< - InternalLimrunAndroidDeviceSession, - 'adb' | 'getKeyboardState' | 'dismissKeyboard' -> & { - readonly adb: AndroidAdbProvider; - getKeyboardState(): Promise; - dismissKeyboard(): Promise; -}; - -export type LimrunDeviceSession = LimrunAndroidDeviceSession | LimrunIosDeviceSession; diff --git a/src/sdk/limrun.ts b/src/sdk/limrun.ts deleted file mode 100644 index 0c0ac71ed9..0000000000 --- a/src/sdk/limrun.ts +++ /dev/null @@ -1,7 +0,0 @@ -export { LimrunRuntime, type LimrunRuntimeOptions } from '../provider-limrun-runtime.ts'; -export type { LimrunAndroidDeviceSession, LimrunDeviceSession } from './limrun-runtime-types.ts'; -export type { - LimrunInstanceAccess, - LimrunIosCommandExecution, - LimrunIosDeviceSession, -} from '@agent-device/provider-limrun'; diff --git a/src/sdk/metro-public.test.ts b/src/sdk/metro-public.test.ts index 27a90f8764..052ce0034c 100644 --- a/src/sdk/metro-public.test.ts +++ b/src/sdk/metro-public.test.ts @@ -1,3 +1,4 @@ +import { once } from 'node:events'; import { test } from 'vitest'; import assert from 'node:assert/strict'; import { @@ -73,7 +74,45 @@ test('public prepareMetroRuntime runs without a daemon or CLI host around it', a const { prepareMetroRuntime } = await import('./metro.ts'); await assert.rejects( - prepareMetroRuntime({}), + prepareMetroRuntime({}, { env: {}, cwd: process.cwd() }), (error: unknown) => (error as { code?: string }).code === 'INVALID_ARGS', ); }); + +test('public Metro preparation resolves concurrent runtime files against each explicit cwd', async () => { + const { prepareMetroRuntime } = await import('./metro.ts'); + const { createServer } = await import('node:http'); + const { readFileSync } = await import('node:fs'); + const { join } = await import('node:path'); + const { mkdtempForTestSync, closeLoopbackServer } = await import('@agent-device/test-kit'); + const server = createServer((_req, res) => res.end('packager-status:running')); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const address = server.address(); + assert.ok(address && typeof address !== 'string'); + const roots = [mkdtempForTestSync('sdk-metro-first-'), mkdtempForTestSync('sdk-metro-second-')]; + try { + const results = await Promise.all( + roots.map((cwd) => + prepareMetroRuntime( + { + kind: 'react-native', + publicBaseUrl: `http://127.0.0.1:${address.port}`, + metroPort: address.port, + installDependenciesIfNeeded: false, + runtimeFilePath: 'runtime.json', + }, + { env: {}, cwd }, + ), + ), + ); + for (const [index, result] of results.entries()) { + const runtimePath = join(roots[index]!, 'runtime.json'); + assert.equal(result.projectRoot, roots[index]); + assert.equal(result.runtimeFilePath, runtimePath); + assert.equal(JSON.parse(readFileSync(runtimePath, 'utf8')).reused, true); + } + } finally { + await closeLoopbackServer(server); + } +}); diff --git a/src/sdk/metro.ts b/src/sdk/metro.ts index ac0689b1a8..00658b0297 100644 --- a/src/sdk/metro.ts +++ b/src/sdk/metro.ts @@ -1,7 +1,5 @@ -import * as devServer from '@agent-device/react-native'; -import { captureSdkHost } from './host.ts'; - export { + prepareMetroRuntime, normalizeBaseUrl, buildBundleUrl, resolveRuntimeTransport, @@ -11,10 +9,3 @@ export { type MetroTunnelRequestMessage, type MetroTunnelResponseMessage, } from '@agent-device/react-native'; - -/** A JS host calls this with no daemon or CLI around it, so it reads the process's current environment. */ -export async function prepareMetroRuntime( - input: Parameters[0] = {}, -): ReturnType { - return await devServer.prepareMetroRuntime(input, captureSdkHost()); -} diff --git a/src/sdk/plugins.ts b/src/sdk/plugins.ts index 15dca39bd1..216c2dd383 100644 --- a/src/sdk/plugins.ts +++ b/src/sdk/plugins.ts @@ -6,7 +6,11 @@ import type { } from '@agent-device/plugins/contract'; import type { CloudWebDriverProviderOptions } from '@agent-device/provider-webdriver/plugin'; -export type { ProviderPluginHost } from '@agent-device/plugins/host'; +export type { + HostCommandResult, + ProviderPluginHost, + RunHostCommand, +} from '@agent-device/plugins/host'; export type { PluginConnection, PluginConnectionContext, @@ -25,3 +29,14 @@ export type AgentDevicePluginFactory> = Contra Options, CloudWebDriverProviderOptions >; + +export type { ReplayEnginePlugin, ReplayEngineSetup } from '@agent-device/plugins/replay-backend'; +export type { ReplayBackend, ReplayBackendHost } from '@agent-device/contracts/replay-backend'; + +export type { + ReplayExecution, + ReplayExecutionPlugin, + ReplayExecutionResolver, +} from '@agent-device/contracts/replay-execution'; + +export { addPluginArtifact } from '@agent-device/plugins/store'; diff --git a/src/sdk/remote-config.test.ts b/src/sdk/remote-config.test.ts index 0d10d35e3c..4a57c041f7 100644 --- a/src/sdk/remote-config.test.ts +++ b/src/sdk/remote-config.test.ts @@ -5,20 +5,15 @@ import path from 'node:path'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { resolveRemoteConfigProfile } from './remote-config.ts'; -test('the released remote-config entry reads the process environment when none is given', () => { +test('the public remote-config resolver uses each supplied environment and cwd', () => { const root = mkdtempForTestSync('agent-device-sdk-remote-config-'); - const previous = process.env.AGENT_DEVICE_METRO_PREPARE_PORT; - try { - const configPath = path.join(root, 'demo.remote.json'); - fs.writeFileSync(configPath, JSON.stringify({ platform: 'ios' }), 'utf8'); - process.env.AGENT_DEVICE_METRO_PREPARE_PORT = '9191'; - - const resolved = resolveRemoteConfigProfile({ configPath, cwd: root }); - - assert.equal(resolved.profile.metroPreparePort, 9191); - } finally { - if (previous === undefined) delete process.env.AGENT_DEVICE_METRO_PREPARE_PORT; - else process.env.AGENT_DEVICE_METRO_PREPARE_PORT = previous; - fs.rmSync(root, { recursive: true, force: true }); - } + fs.writeFileSync(path.join(root, 'demo.remote.json'), JSON.stringify({ platform: 'ios' })); + const resolve = (port: string) => + resolveRemoteConfigProfile({ + configPath: 'demo.remote.json', + cwd: root, + env: { AGENT_DEVICE_METRO_PREPARE_PORT: port }, + }); + assert.equal(resolve('9191').profile.metroPreparePort, 9191); + assert.equal(resolve('9292').profile.metroPreparePort, 9292); }); diff --git a/src/sdk/remote-config.ts b/src/sdk/remote-config.ts index 75aa99ac9e..34dd52e409 100644 --- a/src/sdk/remote-config.ts +++ b/src/sdk/remote-config.ts @@ -1,18 +1,2 @@ -import { captureSdkHost } from './host.ts'; -import { resolveRemoteConfigProfile as resolveRemoteConfigProfileOnHost } from '@agent-device/remote/remote-config'; -import type { - RemoteConfigProfileOptions, - ResolvedRemoteConfigProfile, -} from '@agent-device/remote/remote-config-schema'; - +export { resolveRemoteConfigProfile } from '@agent-device/remote/remote-config'; export type { RemoteConfigProfile } from '@agent-device/remote/remote-config-schema'; - -/** The released entry: without `env`, the profile resolves against the process's environment. */ -export function resolveRemoteConfigProfile( - options: RemoteConfigProfileOptions, -): ResolvedRemoteConfigProfile { - return resolveRemoteConfigProfileOnHost({ - ...options, - env: options.env ?? captureSdkHost().env, - }); -} diff --git a/test/ci/release-workflow.test.ts b/test/ci/release-workflow.test.ts index f67b9f43f9..d4e9df6b95 100644 --- a/test/ci/release-workflow.test.ts +++ b/test/ci/release-workflow.test.ts @@ -127,3 +127,8 @@ test('the internal nightly signs the planned source and every package before npm expect(writers).toEqual(['publish']); expect(steps.indexOf(binding!)).toBeLessThan(steps.findIndex((step) => step.name === 'Publish')); }); + +test('both fixed nightly source branches receive push CI', () => { + const ci = parse(fs.readFileSync(path.join(repoRoot, '.github/workflows/ci.yml'), 'utf8')); + expect(ci.on.push.branches).toEqual(['main', '0.22']); +}); diff --git a/test/integration/android-emulator-e2e/live-automation-scenario.test.ts b/test/integration/android-emulator-e2e/live-automation-scenario.test.ts new file mode 100644 index 0000000000..03445c601b --- /dev/null +++ b/test/integration/android-emulator-e2e/live-automation-scenario.test.ts @@ -0,0 +1,141 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { writeSnapshotEvidence } from './snapshot-evidence.ts'; +import { test, vi } from 'vitest'; +import { parseWaitPositionals } from '@agent-device/command-registry/wait-positionals'; +import { createCommandSurfaceAgentDevice } from '@agent-device/command-runtime'; +import { localCommandPolicy } from '@agent-device/contracts/command-policy'; +import { createLocalArtifactAdapter } from '@agent-device/host-kit/local-artifact-adapter'; +import { makeSnapshotState } from '@agent-device/selectors/snapshot-geometry-fixtures'; +import { assertAutomationSystem } from './live-automation-scenario.ts'; +import type { LiveContext } from './live-harness.ts'; + +const harness = vi.hoisted(() => ({ + runStep: vi.fn(), + captureDiagnosticSnapshot: vi.fn(), + verifyCommand: vi.fn(), + verifyBehavior: vi.fn(), +})); +vi.mock('./live-harness.ts', () => harness); + +test('catalog readiness waits until the automation screen has changed', async () => { + const previous = makeSnapshotState([ + { index: 0, depth: 0, type: 'android.widget.TextView', label: 'Automation lab' }, + { + index: 1, + depth: 0, + type: 'android.widget.Button', + label: 'Continue to catalog', + identifier: 'automation-continue-catalog', + rect: { x: 90, y: 1642, width: 900, height: 124 }, + }, + ]); + const catalog = makeSnapshotState([ + { + index: 0, + depth: 0, + type: 'android.view.ViewGroup', + identifier: 'catalog-title', + rect: { x: 47, y: 419, width: 986, height: 286 }, + }, + { index: 1, depth: 1, parentIndex: 0, type: 'android.widget.TextView', label: 'Catalog' }, + { index: 2, depth: 0, type: 'android.widget.Button', label: 'Settings', ref: 'e3' }, + ]); + let captures = 0; + let elapsed = 0; + const device = createCommandSurfaceAgentDevice({ + backend: { + platform: 'android', + captureSnapshot: async () => ({ snapshot: captures++ === 0 ? previous : catalog }), + }, + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), + policy: localCommandPolicy(), + clock: { + now: () => elapsed, + sleep: async (ms) => { + elapsed += ms; + }, + }, + }); + device.sessions.set({ name: 'default' }); + const done = new Error('reached Settings navigation'); + harness.runStep.mockImplementation(async (_context, _step, args: string[]) => { + const result = (data: unknown) => ({ + status: 0, + stdout: '', + stderr: '', + json: { success: true, data }, + }); + if (args[0] === 'get') + return result({ + text: args[2]?.includes('payload') ? '{"source":"android-deep-link"}' : 'cold.start', + }); + if (args[0] === 'wait') { + const parsed = parseWaitPositionals(args.slice(1)); + assert.ok(parsed && (parsed.kind === 'text' || parsed.kind === 'selector')); + const target = + parsed.kind === 'text' + ? { kind: 'text' as const, text: parsed.text, timeoutMs: parsed.timeoutMs ?? 10000 } + : { + kind: 'selector' as const, + selector: parsed.selectorExpression, + timeoutMs: parsed.timeoutMs ?? 10000, + }; + const waited = await device.selectors.wait({ session: 'default', target }); + assert.equal(captures, 2, 'readiness must not complete on Automation lab'); + return result(waited); + } + if (args[0] === 'snapshot') + return result({ + nodes: catalog.nodes, + androidSnapshot: { + backend: 'android-helper', + helperTransport: 'persistent-session', + helperSessionReused: true, + }, + }); + if (args[0] === 'click' && args[1]?.startsWith('@')) throw done; + return result({}); + }); + harness.captureDiagnosticSnapshot.mockImplementation((context, _name, step) => + harness.runStep(context, step, ['snapshot', '-i', '--debug']), + ); + await assert.rejects(assertAutomationSystem({} as LiveContext), (error) => error === done); +}); + +test('retains bounded original helper evidence with request correlation', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'android-snapshot-evidence-')); + try { + writeSnapshotEvidence(dir, 'catalog', 'fixture', 100, 200, { + status: 0, + stdout: '', + stderr: '', + json: { + data: { + androidSnapshot: { + backend: 'android-helper', + helperTransport: 'instrumentation', + nodeCount: 268, + foregroundWindowPackage: 'token=secret', + unexpected: 'private', + }, + warnings: Array(100).fill('token=secret ' + 'x'.repeat(1000)), + nodes: [{ label: 'private tree' }], + }, + }, + }); + const content = fs.readFileSync(path.join(dir, 'snapshot-catalog.json'), 'utf8'); + const evidence = JSON.parse(content); + assert.equal(evidence.session, 'fixture'); + assert.deepEqual([evidence.startedAtMs, evidence.finishedAtMs], [100, 200]); + assert.equal(evidence.androidSnapshot.helperTransport, 'instrumentation'); + assert.equal(evidence.androidSnapshot.nodeCount, 268); + assert.equal(evidence.warnings.length, 20); + assert.ok(!content.includes('secret') && !content.includes('private')); + assert.ok(content.length < 10_000); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/test/integration/android-emulator-e2e/live-automation-scenario.ts b/test/integration/android-emulator-e2e/live-automation-scenario.ts index 8d9b86ff8d..9d972093c2 100644 --- a/test/integration/android-emulator-e2e/live-automation-scenario.ts +++ b/test/integration/android-emulator-e2e/live-automation-scenario.ts @@ -14,7 +14,13 @@ import { requireAndroidResourceId, scrollToVisibleSelector, } from './live-assertions.ts'; -import { type LiveContext, runStep, verifyBehavior, verifyCommand } from './live-harness.ts'; +import { + type LiveContext, + runStep, + verifyBehavior, + verifyCommand, + captureDiagnosticSnapshot, +} from './live-harness.ts'; import { assertHumanSnapshotCompaction } from './live-snapshot-compaction.ts'; const C = PUBLIC_COMMANDS; @@ -37,11 +43,12 @@ export async function assertAutomationSystem(context: LiveContext): Promise + writeSnapshotEvidence( + context.artifactDir, + name, + context.session, + startedAtMs, + Date.now(), + result, + ), + }); +} diff --git a/test/integration/android-emulator-e2e/scenario-start.ts b/test/integration/android-emulator-e2e/scenario-start.ts index ce0cd79876..baa037f7a2 100644 --- a/test/integration/android-emulator-e2e/scenario-start.ts +++ b/test/integration/android-emulator-e2e/scenario-start.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { assertWaitText } from './live-assertions.ts'; -import { type LiveContext, runStep } from './live-harness.ts'; +import { type LiveContext, runStep, captureDiagnosticSnapshot } from './live-harness.ts'; export type AndroidEmulatorScenarioStart = { ime: 'system' | 'test'; @@ -24,7 +24,10 @@ export async function prepareAndroidEmulatorScenario( ...(start.ime === 'system' ? ['--no-test-ime'] : []), start.url, ]); - const preflight = await runStep(context, 'preflight Android snapshot helper', ['snapshot', '-i']); + const preflight = + context.currentScenario === 'smoke:automation-system' + ? await captureDiagnosticSnapshot(context, 'preflight', 'preflight Android snapshot helper') + : await runStep(context, 'preflight Android snapshot helper', ['snapshot', '-i']); assert.equal(preflight.json?.data?.androidSnapshot?.backend, 'android-helper'); await assertWaitText(context, start.landmark); } diff --git a/test/integration/android-emulator-e2e/snapshot-evidence.ts b/test/integration/android-emulator-e2e/snapshot-evidence.ts new file mode 100644 index 0000000000..9b8fac8ae0 --- /dev/null +++ b/test/integration/android-emulator-e2e/snapshot-evidence.ts @@ -0,0 +1,69 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { redactDiagnosticData } from '@agent-device/kernel/redaction'; +import type { CliJsonResult } from '../cli-json.ts'; + +const fields = [ + 'backend', + 'pixelDensity', + 'helperVersion', + 'helperApiVersion', + 'helperTransport', + 'helperSessionReused', + 'installReason', + 'waitForIdleTimeoutMs', + 'waitForIdleQuietMs', + 'timeoutMs', + 'maxDepth', + 'maxNodes', + 'rootPresent', + 'cacheInvalidated', + 'captureMode', + 'systemSurfaceOnly', + 'foregroundWindowPackage', + 'windowCount', + 'nodeCount', + 'helperTruncated', + 'elapsedMs', + 'occlusionScanUnavailable', +] as const; + +export function writeSnapshotEvidence( + dir: string, + name: 'preflight' | 'catalog', + session: string, + startedAtMs: number, + finishedAtMs: number, + result: CliJsonResult, +): void { + const data = result.json?.data; + const source = data?.androidSnapshot; + const androidSnapshot: Record = {}; + if (source && typeof source === 'object') { + for (const field of fields) { + const value: unknown = source[field]; + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') + androidSnapshot[field] = value; + } + } + if (Array.isArray(source?.missingRootWindowTypes)) { + const types = source.missingRootWindowTypes + .filter((value: unknown): value is number => typeof value === 'number') + .slice(0, 20); + Object.assign(androidSnapshot, { missingRootWindowTypes: types }); + } + const warnings = Array.isArray(data?.warnings) + ? data.warnings + .filter((value: unknown): value is string => typeof value === 'string') + .slice(0, 20) + : []; + const evidence = redactDiagnosticData({ + session, + startedAtMs, + finishedAtMs, + status: result.status, + androidSnapshot, + warnings, + }); + fs.writeFileSync(path.join(dir, `snapshot-${name}.json`), JSON.stringify(evidence, null, 2)); +} diff --git a/test/integration/client-api-doc-snippets.test.ts b/test/integration/client-api-doc-snippets.test.ts index 3c0fc2d608..dfe3e80b16 100644 --- a/test/integration/client-api-doc-snippets.test.ts +++ b/test/integration/client-api-doc-snippets.test.ts @@ -87,6 +87,11 @@ const KNOWN_FREE_NAME_STUB_TYPES: Record = { function writeSnippetProgram(snippets: string[]): string { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'client-api-doc-snippets-')); fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"type":"module"}\n'); + fs.symlinkSync( + path.join(repoRoot, 'node_modules'), + path.join(tmpDir, 'node_modules'), + 'junction', + ); fs.writeFileSync( path.join(tmpDir, 'tsconfig.json'), JSON.stringify({ diff --git a/test/integration/installed-package-metro.test.ts b/test/integration/installed-package-metro.test.ts index af30a389c7..6130ab327b 100644 --- a/test/integration/installed-package-metro.test.ts +++ b/test/integration/installed-package-metro.test.ts @@ -54,7 +54,11 @@ function ensureBuiltPackage(): void { }); } -function extractInstalledPackage(tarballPath: string, consumerRoot: string): string { +function extractInstalledPackage( + tarballPath: string, + consumerRoot: string, + packageName = 'agent-device', +): string { const nodeModulesRoot = path.join(consumerRoot, 'node_modules'); fs.mkdirSync(nodeModulesRoot, { recursive: true }); runCmdSync('tar', ['-xzf', tarballPath, '-C', nodeModulesRoot], { @@ -62,7 +66,8 @@ function extractInstalledPackage(tarballPath: string, consumerRoot: string): str timeoutMs: SUBPROCESS_TIMEOUT_MS, }); const extractedPackageRoot = path.join(nodeModulesRoot, 'package'); - const installedPackageRoot = path.join(nodeModulesRoot, 'agent-device'); + const installedPackageRoot = path.join(nodeModulesRoot, packageName); + fs.mkdirSync(path.dirname(installedPackageRoot), { recursive: true }); fs.renameSync(extractedPackageRoot, installedPackageRoot); return installedPackageRoot; } @@ -83,41 +88,6 @@ function linkRuntimeDependencies(installedPackageRoot: string, consumerRoot: str } } -/** - * Runs the packaged runScript child, whose `http.post` starts the packaged HTTP child. Both entries - * are found from the bundled chunk that holds the resolver, so this proves the shipped layout. - */ -async function assertPackagedRunScriptChild(installedPackageRoot: string, root: string) { - const childPath = fs.realpathSync( - path.join(installedPackageRoot, 'dist', 'src', 'internal', 'run-script-child.js'), - ); - assert.equal(fs.existsSync(childPath), true); - const aliasRoot = path.join(root, 'run-script-entry-alias'); - fs.symlinkSync(installedPackageRoot, aliasRoot, 'junction'); - const aliasChildPath = path.join(aliasRoot, 'dist', 'src', 'internal', 'run-script-child.js'); - const server = http.createServer((_req, res) => res.end('x'.repeat(2 * 1024 * 1024))); - try { - const port = await listenOnLoopback(server); - const scriptPath = path.join(root, 'run-script-setup.js'); - fs.writeFileSync(scriptPath, 'output.size = http.post(SERVER_URL).body.length'); - for (const entryPath of [childPath, aliasChildPath]) { - const result = await runCmd(process.execPath, [entryPath], { - stdin: JSON.stringify({ - scriptPath, - env: { SERVER_URL: `http://127.0.0.1:${port}/` }, - publicNetworkOnly: false, - }), - timeoutMs: SUBPROCESS_TIMEOUT_MS, - }); - assert.deepEqual(readJson(result.stdout), { - outputEnv: { 'output.size': String(2 * 1024 * 1024) }, - }); - } - } finally { - await closeLoopbackServer(server); - } -} - async function runNodeModuleJson(cwd: string, args: string[], script: string): Promise { const stdout = await execFileText(process.execPath, [...args, script], { cwd, @@ -127,14 +97,28 @@ async function runNodeModuleJson(cwd: string, args: string[], script: string): P /** A v2 plugin written against the packed `agent-device/plugins` types, type-checked as a consumer. */ async function typeCheckInstalledPluginContract(consumerRoot: string): Promise { + for (const name of ['maestro', 'replay']) { + const tarball = path.join(consumerRoot, `${name}.tgz`); + runCmdSync('pnpm', ['pack', '--out', tarball], { + cwd: path.join(repoRoot, 'packages', name), + timeoutMs: SUBPROCESS_TIMEOUT_MS, + }); + extractInstalledPackage(tarball, consumerRoot, `@agent-device/${name}`); + } const source = path.join(consumerRoot, 'plugin-contract-smoke.ts'); fs.writeFileSync( source, - `import type { AgentDevicePluginFactory } from 'agent-device/plugins'; + `import { addPluginArtifact, type AgentDevicePluginFactory } from 'agent-device/plugins'; import { startAgentDevice, type AgentDeviceHost, type StartAgentDeviceOptions, type AgentDeviceClientConfig } from 'agent-device'; +import maestro from '@agent-device/maestro/agent-device'; +import replay from '@agent-device/replay/agent-device'; + +export async function installArtifact(archive: string, host: { cwd: string; env: Record }) { + return await addPluginArtifact(archive, host); +} export async function hostConsumer(host: NonNullable) { - const options: StartAgentDeviceOptions = { stateDir: './state', host, plugins: [await example()] }; + const options: StartAgentDeviceOptions = { stateDir: './state', host, plugins: [await example(), maestro(), replay()] }; const running: AgentDeviceHost = await startAgentDevice(options); const config: AgentDeviceClientConfig = running.clientConfig; void config; @@ -318,7 +302,10 @@ test('installed package exposes Node APIs and packaged companion tunnel entrypoi fs.existsSync(path.join(installedPackageRoot, 'dist', 'src', 'companion-tunnel.js')), false, ); - await assertPackagedRunScriptChild(installedPackageRoot, root); + assert.equal( + fs.existsSync(path.join(installedPackageRoot, 'dist/src/internal/run-script-child.js')), + false, + ); const pluginTypes = fs.readFileSync(path.join(installedPackageRoot, 'dist/src/plugins.d.ts')); assert.ok(pluginTypes.length < 16 * 1024); @@ -340,6 +327,38 @@ test('installed package exposes Node APIs and packaged companion tunnel entrypoi ); } await typeCheckInstalledPluginContract(consumerRoot); + const managedHome = path.join(consumerRoot, 'managed-plugin-home'); + const replayArchive = path.join(consumerRoot, 'replay.tgz'); + const expectedIntegrity = `sha512-${crypto.createHash('sha512').update(fs.readFileSync(replayArchive)).digest('base64')}`; + const selection = await runNodeModuleJson( + consumerRoot, + ['--input-type=module', '-e'], + `import { addPluginArtifact } from 'agent-device/plugins'; + const selected = await addPluginArtifact(${JSON.stringify(replayArchive)}, { + cwd: process.cwd(), + env: { ...process.env, HOME: ${JSON.stringify(managedHome)}, AGENT_DEVICE_HOME: ${JSON.stringify(managedHome)} }, + }); + console.log(JSON.stringify(selected));`, + ); + assert.equal(selection.name, '@agent-device/replay'); + assert.equal(selection.integrity, expectedIntegrity); + const inventory = await runCmd( + process.execPath, + [path.join(installedPackageRoot, 'bin/agent-device.mjs'), 'plugins', 'list', '--json'], + { + cwd: consumerRoot, + env: { ...process.env, HOME: managedHome, AGENT_DEVICE_HOME: managedHome }, + timeoutMs: SUBPROCESS_TIMEOUT_MS, + }, + ); + const selectedPlugin = readJson(inventory.stdout).data.plugins.find( + (plugin: { name?: string }) => plugin.name === '@agent-device/replay', + ); + assert.equal(selectedPlugin?.installation, selection.installation); + assert.equal(selectedPlugin?.integrity, expectedIntegrity); + assert.equal(selectedPlugin?.version, selection.version); + assert.equal(selectedPlugin?.backend, 'ad'); + assert.equal(selectedPlugin?.compatible, true); fs.writeFileSync( path.join(consumerRoot, 'fixture-plugin.mjs'), String.raw` @@ -627,6 +646,7 @@ assert.equal(fs.existsSync(path.join(cwd, 'host-a', 'daemon.json')), false); './artifacts': async (mod) => { const name = await mod.resolveAndroidArchivePackageName( nodePath.join(process.cwd(), 'package.json'), + { env: { ...process.env }, cwd: process.cwd() }, ); return String(name); }, @@ -644,13 +664,8 @@ assert.equal(fs.existsSync(path.join(cwd, 'host-a', 'daemon.json')), false); './finders': (mod) => mod.findBestMatchesByLocator([], 'text', 'anything').matches.length, './install-source': (mod) => typeof mod.isTrustedInstallSourceUrl('https://example.test/app.apk'), './io': (mod) => typeof mod.createLocalArtifactAdapter({ cwd: process.cwd() }).reserveOutput, - './limrun': async (mod) => { - const runtime = new mod.LimrunRuntime({ apiKey: 'lim_test_key' }); - await runtime.shutdown(); - return runtime.provider; - }, './metro': (mod) => mod.buildBundleUrl('https://public.example.test', 'ios'), - './plugins': (mod) => Object.keys(mod).length === 0, + './plugins': (mod) => Object.keys(mod).length === 1 && typeof mod.addPluginArtifact === 'function', './plugins/webdriver': (mod) => Object.keys(mod).length === 0, './remote-config': (mod) => typeof mod, './selectors': (mod) => @@ -669,6 +684,7 @@ assert.equal(fs.existsSync(path.join(cwd, 'host-a', 'daemon.json')), false); 'agent-device/commands', 'agent-device/testing/conformance', 'agent-device/observability', + 'agent-device/limrun', ].map(async (specifier) => { try { await import(specifier); @@ -731,7 +747,6 @@ assert.equal(fs.existsSync(path.join(cwd, 'host-a', 'daemon.json')), false); './finders': 0, './install-source': 'boolean', './io': 'function', - './limrun': 'limrun', './plugins': true, './plugins/webdriver': true, // Type-only subpath: resolving the module from the packed exports map is diff --git a/test/integration/interaction-contract/daemon-harness.test.ts b/test/integration/interaction-contract/daemon-harness.test.ts new file mode 100644 index 0000000000..b61f1c2cea --- /dev/null +++ b/test/integration/interaction-contract/daemon-harness.test.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { withIosContractDaemon } from './daemon-harness.ts'; + +test('independent contract daemons can use their own fake simulator with the same ID', async () => { + const inheritedClaimsDir = process.env.AGENT_DEVICE_CLAIMS_DIR; + process.env.AGENT_DEVICE_CLAIMS_DIR = mkdtempForTestSync('shared-contract-claims-'); + try { + await withIosContractDaemon([], async () => { + await withIosContractDaemon([], async () => {}); + }); + } finally { + if (inheritedClaimsDir === undefined) delete process.env.AGENT_DEVICE_CLAIMS_DIR; + else process.env.AGENT_DEVICE_CLAIMS_DIR = inheritedClaimsDir; + } +}); diff --git a/test/integration/interaction-contract/daemon-harness.ts b/test/integration/interaction-contract/daemon-harness.ts index 826ccc9bee..5c24d9dacd 100644 --- a/test/integration/interaction-contract/daemon-harness.ts +++ b/test/integration/interaction-contract/daemon-harness.ts @@ -1,3 +1,4 @@ +import { mkdtempForTestSync } from '@agent-device/test-kit'; import { assertRpcOk } from '../provider-scenarios/assertions.ts'; import { FIRST_SCREEN_NODES, @@ -69,6 +70,7 @@ export async function withIosContractDaemon( appleRunnerProvider: () => appleRunnerProvider, appleToolProvider: () => appleTool.provider, deviceInventoryProvider: async () => [PROVIDER_SCENARIO_IOS_SIMULATOR], + env: { AGENT_DEVICE_CLAIMS_DIR: mkdtempForTestSync('interaction-contract-claims-') }, }), async (daemon) => { const open = await daemon.callCommand('open', [CONTRACT_APP], { diff --git a/test/integration/interaction-contract/runtime-harness.ts b/test/integration/interaction-contract/runtime-harness.ts index 4edfc4bd33..927b8ecac8 100644 --- a/test/integration/interaction-contract/runtime-harness.ts +++ b/test/integration/interaction-contract/runtime-harness.ts @@ -53,7 +53,7 @@ export function createContractDevice( performGesture: overrides.performGesture, resolveGestureViewport: overrides.resolveGestureViewport, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), policy: localCommandPolicy(), ...(overrides.clock ? { clock: overrides.clock } : {}), }); diff --git a/test/integration/limrun-public-types.test.ts b/test/integration/limrun-public-types.test.ts deleted file mode 100644 index 6accf62a49..0000000000 --- a/test/integration/limrun-public-types.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; -import test from 'node:test'; -import { fileURLToPath } from 'node:url'; -import { runCmdSync } from '@agent-device/host-kit/command'; - -const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..'); -const TSC_BIN = path.join(repoRoot, 'node_modules/.bin/tsc'); -const COMMAND_TIMEOUT_MS = 120_000; - -function ensureBuiltPackage(): void { - const declarationPath = path.join(repoRoot, 'dist', 'src', 'limrun.d.ts'); - if (fs.existsSync(declarationPath)) return; - - runCmdSync('pnpm', ['build'], { - cwd: repoRoot, - timeoutMs: COMMAND_TIMEOUT_MS, - }); -} - -test('compiled Limrun subpath preserves its downstream type surface', () => { - ensureBuiltPackage(); - - // Keep the fixture under the package root so TypeScript resolves the - // package self-reference through package.json's compiled `types` export. - const tempRoot = fs.mkdtempSync(path.join(repoRoot, '.tmp-limrun-types-')); - try { - fs.writeFileSync( - path.join(tempRoot, 'tsconfig.json'), - JSON.stringify( - { - compilerOptions: { - module: 'NodeNext', - moduleResolution: 'NodeNext', - noEmit: true, - strict: true, - types: ['node'], - }, - include: ['fixture.ts'], - }, - null, - 2, - ), - ); - fs.writeFileSync( - path.join(tempRoot, 'fixture.ts'), - `import type { - LimrunDeviceSession, - LimrunIosCommandExecution, - LimrunIosDeviceSession, - LimrunRuntime, - LimrunRuntimeOptions, -} from 'agent-device/limrun'; - -declare const runtime: LimrunRuntime; -declare const options: LimrunRuntimeOptions; -declare const session: LimrunDeviceSession; -declare const iosSession: LimrunIosDeviceSession; -declare const execution: LimrunIosCommandExecution; -void [runtime, options, session, iosSession, execution]; -`, - ); - - const result = runCmdSync( - TSC_BIN, - ['--noEmit', '-p', path.join(tempRoot, 'tsconfig.json'), '--pretty', 'false'], - { - cwd: tempRoot, - timeoutMs: COMMAND_TIMEOUT_MS, - allowFailure: true, - }, - ); - - assert.equal( - result.exitCode, - 0, - `The compiled agent-device/limrun declarations no longer preserve the downstream contract:\n${result.stdout}${result.stderr}`, - ); - } finally { - fs.rmSync(tempRoot, { recursive: true, force: true }); - } -}); diff --git a/test/integration/live-device-e2e-runtime.test.ts b/test/integration/live-device-e2e-runtime.test.ts index adcff789c4..00281597b0 100644 --- a/test/integration/live-device-e2e-runtime.test.ts +++ b/test/integration/live-device-e2e-runtime.test.ts @@ -5,6 +5,7 @@ import test from 'node:test'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import type { CliJsonResult } from './cli-json.ts'; +import { writeSnapshotEvidence } from './android-emulator-e2e/snapshot-evidence.ts'; import { createLiveDeviceContext, createLiveDeviceHarness } from './live-device-e2e/runtime.ts'; function fixture(options: { captureThrows?: boolean; deviceEvidence?: string } = {}) { @@ -318,3 +319,110 @@ test('unwritable artifact output cannot replace the scenario failure', async () ); assert.equal(reports(), 1); }); + +test('snapshot evidence write failure preserves the successful issued result', async () => { + const context = createLiveDeviceContext({ + artifactRoot: mkdtempForTestSync('snapshot-observer-success-'), + session: 'fixture-session', + }); + const result: CliJsonResult = { + status: 0, + stdout: '', + stderr: '', + json: { + data: { + androidSnapshot: { backend: 'android-helper', helperTransport: 'persistent-session' }, + }, + }, + }; + let observations = 0; + let issues = 0; + const harness = createLiveDeviceHarness({ + behaviorsForScenario: () => [], + commandsForScenario: () => [], + commonFlags: (_context, args) => [...args], + runCli: async () => { + issues++; + return result; + }, + writeCoverageReport: () => {}, + }); + const returned = await harness.runStep(context, 'original', ['snapshot', '-i', '--debug'], { + observeResult: (observed: CliJsonResult) => { + observations++; + writeSnapshotEvidence( + path.join(context.artifactDir, 'missing'), + 'catalog', + context.session, + 10, + 20, + observed, + ); + }, + }); + assert.equal(returned, result); + assert.equal(returned.status, 0); + assert.equal(observations, 1); + assert.equal(issues, 1); + assert.equal(context.stepHistory[0]?.accepted, true); +}); + +test('failed original snapshot evidence is written before failure collection and assertion', async () => { + const context = createLiveDeviceContext({ + artifactRoot: mkdtempForTestSync('snapshot-observer-failure-'), + session: 'fixture-session', + }); + const original: CliJsonResult = { + status: 17, + stdout: '', + stderr: '', + json: { + data: { + androidSnapshot: { + backend: 'android-helper', + helperTransport: 'instrumentation', + nodeCount: 268, + }, + warnings: ['original warning'], + }, + }, + }; + const followup: CliJsonResult = { + status: 0, + stdout: '', + stderr: '', + json: { data: { androidSnapshot: { nodeCount: 1 } } }, + }; + const calls: string[] = []; + const evidencePath = path.join(context.artifactDir, 'snapshot-catalog.json'); + let presentBeforeCollection = false; + const harness = createLiveDeviceHarness({ + behaviorsForScenario: () => [], + commandsForScenario: () => [], + commonFlags: (_context, args) => [...args], + runCli: async (args) => { + calls.push(args[0]!); + if (calls.length === 1) return original; + presentBeforeCollection = fs.existsSync(evidencePath); + return followup; + }, + writeCoverageReport: () => {}, + }); + await assert.rejects( + harness.runStep(context, 'original', ['snapshot', '-i', '--debug'], { + observeResult: (result: CliJsonResult) => + writeSnapshotEvidence(context.artifactDir, 'catalog', context.session, 10, 20, result), + }), + (error: unknown) => error instanceof assert.AssertionError, + ); + assert.deepEqual(calls, ['snapshot', 'screenshot', 'snapshot']); + assert.equal(presentBeforeCollection, true); + const evidence = JSON.parse(fs.readFileSync(evidencePath, 'utf8')); + assert.equal(evidence.status, 17); + assert.equal(evidence.session, 'fixture-session'); + assert.deepEqual([evidence.startedAtMs, evidence.finishedAtMs], [10, 20]); + assert.equal(evidence.androidSnapshot.nodeCount, 268); + assert.deepEqual(evidence.warnings, ['original warning']); + assert.equal(context.stepHistory.length, 1); + assert.equal(context.stepHistory[0]?.accepted, false); +}); diff --git a/test/integration/live-device-e2e/runtime.ts b/test/integration/live-device-e2e/runtime.ts index c1c387befe..98ddbac8db 100644 --- a/test/integration/live-device-e2e/runtime.ts +++ b/test/integration/live-device-e2e/runtime.ts @@ -62,6 +62,8 @@ type HarnessOptions = { }; type RunStepOptions = { + /** Observes each issued result without changing its verdict; observer failures are ignored. */ + observeResult?: (result: CliJsonResult) => void; allowFailure?: boolean; commonFlags?: boolean; expectFailure?: boolean; @@ -251,6 +253,9 @@ export function createLiveDeviceHarness< step, }); updateSessionState(context, args[0], result.status); + try { + stepOptions.observeResult?.(result); + } catch {} return { result, fullArgs }; } diff --git a/test/integration/provider-scenarios/active-session-script-publication.test.ts b/test/integration/provider-scenarios/active-session-script-publication.test.ts index 3b7f5b4d97..d9185a3450 100644 --- a/test/integration/provider-scenarios/active-session-script-publication.test.ts +++ b/test/integration/provider-scenarios/active-session-script-publication.test.ts @@ -4,7 +4,7 @@ import os from 'node:os'; import path from 'node:path'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { INTERNAL_COMMANDS } from '@agent-device/command-registry/catalog'; -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import { assertRpcError, assertRpcOk } from './assertions.ts'; import { androidSettingsXml, createAndroidSettingsWorld } from './android-world.ts'; import { withProviderScenarioResource } from './harness.ts'; @@ -496,3 +496,32 @@ test('#1398: a read-only wait recorded after a parameterized fill never re-seria }, ); }, 20_000); + +test('ordinary open/close recording works with no replay plugin and replay refuses before another device call', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'core-recording-no-plugin-')); + vi.stubEnv('AGENT_DEVICE_HOME', path.join(root, 'empty-plugin-home')); + try { + await withProviderScenarioResource(createAndroidSettingsWorld, async (world) => { + const scriptPath = path.join(root, 'recorded.ad'); + const client = world.daemon.client(); + await client.apps.open({ app: 'settings', saveScript: scriptPath, ...world.selection }); + await client.command.wait({ selector: 'label="Search"', ...world.selection }); + await client.sessions.close(); + assert.match(fs.readFileSync(scriptPath, 'utf8'), /agent-device:target-v1/); + const deviceCalls = world.adbCalls.length; + await assert.rejects( + client.replay.run({ path: scriptPath, ...world.selection }), + (error: unknown) => { + assert.equal( + (error as { details?: { reason?: string } }).details?.reason, + 'plugin-not-installed', + ); + return true; + }, + ); + assert.equal(world.adbCalls.length, deviceCalls); + }); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/test/integration/provider-scenarios/aws-runtime.ts b/test/integration/provider-scenarios/aws-runtime.ts new file mode 100644 index 0000000000..75dcd028b9 --- /dev/null +++ b/test/integration/provider-scenarios/aws-runtime.ts @@ -0,0 +1,33 @@ +import awsDeviceFarm from '@agent-device/aws-device-farm'; +import { createPluginHost } from '@agent-device/plugins/host'; +import { createCloudWebDriverRuntime } from '@agent-device/provider-webdriver/plugin'; +import type { RunHostCommand } from '@agent-device/plugins/host'; + +export const AWS_DEVICE_FARM_PROVIDER = 'aws-device-farm'; + +/** The WebDriver descriptor the AWS Device Farm plugin's `setup` builds from `env`, as `clientVersion` hosted. */ +async function awsDeviceFarmWebDriver( + env: Record, + clientVersion: string, + runHostCommand: RunHostCommand, +) { + const setup = await awsDeviceFarm().setup({ + ...createPluginHost({ env, cwd: '/' }, undefined), + clientVersion, + runHostCommand, + }); + if (!('webDriver' in setup)) throw new Error('AWS Device Farm sets up a WebDriver descriptor'); + return setup.webDriver; +} + +/** An AWS Device Farm runtime composed the way the registry composes a plugin's WebDriver descriptor. */ +export async function createAwsDeviceFarmRuntime(options: { + env: Record; + clientVersion: string; + runHostCommand: RunHostCommand; +}) { + return await createCloudWebDriverRuntime({ + ...(await awsDeviceFarmWebDriver(options.env, options.clientVersion, options.runHostCommand)), + clientVersion: options.clientVersion, + }); +} diff --git a/test/integration/provider-scenarios/browserstack-runtime.ts b/test/integration/provider-scenarios/browserstack-runtime.ts new file mode 100644 index 0000000000..7a73bffa7e --- /dev/null +++ b/test/integration/provider-scenarios/browserstack-runtime.ts @@ -0,0 +1,26 @@ +import browserstack from '@agent-device/browserstack'; +import { createPluginHost } from '@agent-device/plugins/host'; +import { createCloudWebDriverRuntime } from '@agent-device/provider-webdriver/plugin'; + +export const BROWSERSTACK_PROVIDER = 'browserstack'; + +/** The WebDriver descriptor the BrowserStack plugin's `setup` builds from `env`, as `clientVersion` hosted. */ +export async function browserStackWebDriver(env: Record, clientVersion: string) { + const setup = await browserstack().setup({ + ...createPluginHost({ env, cwd: '/' }, undefined), + clientVersion, + }); + if (!('webDriver' in setup)) throw new Error('BrowserStack sets up a WebDriver descriptor'); + return setup.webDriver; +} + +/** A BrowserStack runtime composed the way the registry composes a plugin's WebDriver descriptor. */ +export async function createBrowserStackRuntime(options: { + env: Record; + clientVersion: string; +}) { + return await createCloudWebDriverRuntime({ + ...(await browserStackWebDriver(options.env, options.clientVersion)), + clientVersion: options.clientVersion, + }); +} diff --git a/test/integration/provider-scenarios/bundled-cloud-webdriver-runtimes.ts b/test/integration/provider-scenarios/bundled-cloud-webdriver-runtimes.ts index 08906126cf..50a740e1dc 100644 --- a/test/integration/provider-scenarios/bundled-cloud-webdriver-runtimes.ts +++ b/test/integration/provider-scenarios/bundled-cloud-webdriver-runtimes.ts @@ -1,18 +1,10 @@ -import { - BUNDLED_CLOUD_WEBDRIVER_PROVIDERS, - type CloudWebDriverProviderHost, -} from '@agent-device/provider-webdriver'; -import { createCloudWebDriverRuntime } from '@agent-device/provider-webdriver/plugin'; +import { createAwsDeviceFarmRuntime } from './aws-runtime.ts'; +import type { RunHostCommand } from '@agent-device/plugins/host'; -/** One runtime per bundled provider, composed the way the registry composes a WebDriver descriptor. */ -export async function createBundledCloudWebDriverRuntimes(host: CloudWebDriverProviderHost) { - return await Promise.all( - BUNDLED_CLOUD_WEBDRIVER_PROVIDERS.map( - async (bundled) => - await createCloudWebDriverRuntime({ - ...bundled.create(host).webDriver, - clientVersion: host.clientVersion, - }), - ), - ); +export async function createBundledCloudWebDriverRuntimes(host: { + env: Record; + clientVersion: string; + runHostCommand: RunHostCommand; +}) { + return [await createAwsDeviceFarmRuntime(host)]; } diff --git a/test/integration/provider-scenarios/cloud-webdriver-ios-text-entry.test.ts b/test/integration/provider-scenarios/cloud-webdriver-ios-text-entry.test.ts index c850de9a9a..46a85c1a14 100644 --- a/test/integration/provider-scenarios/cloud-webdriver-ios-text-entry.test.ts +++ b/test/integration/provider-scenarios/cloud-webdriver-ios-text-entry.test.ts @@ -1,7 +1,7 @@ import type { DaemonWireRequest } from '@agent-device/contracts/command'; import assert from 'node:assert/strict'; import { test } from 'vitest'; -import { createBundledCloudWebDriverRuntimes } from './bundled-cloud-webdriver-runtimes.ts'; +import { BROWSERSTACK_PROVIDER, createBrowserStackRuntime } from './browserstack-runtime.ts'; import type { DeviceLease } from '@agent-device/contracts/device'; import { createProviderDeviceRuntimeRequestProviders } from '../../../src/provider-device-runtime.ts'; import { assertRpcOk } from './assertions.ts'; @@ -18,9 +18,8 @@ import { startCloudWebDriverTestServer, type StartedCloudWebDriverTestServer, } from './cloud-webdriver-test-server.ts'; -import { CLOUD_WEBDRIVER_PROVIDERS } from '@agent-device/provider-webdriver/providers'; -const WEBDRIVER_PROVIDER = CLOUD_WEBDRIVER_PROVIDERS.browserStack; +const WEBDRIVER_PROVIDER = BROWSERSTACK_PROVIDER; const CLIENT_VERSION = '0.20.6-test'; /** @@ -407,18 +406,17 @@ function textEntryTranscript(server: FakeIosWebDriverServer): string[] { async function createCloudIosWorld() { const server = await FakeIosWebDriverServer.start(); - const runtimes = await createBundledCloudWebDriverRuntimes({ - env: { - BROWSERSTACK_USERNAME: 'browser-user', - BROWSERSTACK_ACCESS_KEY: 'browser-key', - BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, - BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `${server.url}/app-automate/sessions`, - }, - clientVersion: CLIENT_VERSION, - runHostCommand: async () => { - throw new Error('BrowserStack scenario must not run host commands'); - }, - }); + const runtimes = [ + await createBrowserStackRuntime({ + env: { + BROWSERSTACK_USERNAME: 'browser-user', + BROWSERSTACK_ACCESS_KEY: 'browser-key', + BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, + BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `${server.url}/app-automate/sessions`, + }, + clientVersion: CLIENT_VERSION, + }), + ]; const providers = createProviderDeviceRuntimeRequestProviders(runtimes); const daemon = await createProviderScenarioHarness({ ...providers, diff --git a/test/integration/provider-scenarios/cloud-webdriver-lease-http.test.ts b/test/integration/provider-scenarios/cloud-webdriver-lease-http.test.ts index 4cf182824c..2c4cd85781 100644 --- a/test/integration/provider-scenarios/cloud-webdriver-lease-http.test.ts +++ b/test/integration/provider-scenarios/cloud-webdriver-lease-http.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { buildScenarioRpcRequest } from './harness-rpc.ts'; import http from 'node:http'; import { test } from 'vitest'; -import { createBundledCloudWebDriverRuntimes } from './bundled-cloud-webdriver-runtimes.ts'; +import { BROWSERSTACK_PROVIDER, createBrowserStackRuntime } from './browserstack-runtime.ts'; import { createProviderDeviceRuntimeRequestProviders } from '../../../src/provider-device-runtime.ts'; import { skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; import { createProviderScenarioHarness, withProviderScenarioResource } from './harness.ts'; @@ -13,7 +13,6 @@ import { startCloudWebDriverTestServer, type StartedCloudWebDriverTestServer, } from './cloud-webdriver-test-server.ts'; -import { CLOUD_WEBDRIVER_PROVIDERS } from '@agent-device/provider-webdriver/providers'; const CLIENT_VERSION = '0.20.3-test'; @@ -30,19 +29,18 @@ test('lease_allocate over HTTP prepares the BrowserStack session end to end', as } await withProviderScenarioResource(FakeBrowserStackServer.start, async (server) => { - const runtimes = await createBundledCloudWebDriverRuntimes({ - env: { - BROWSERSTACK_USERNAME: 'browser-user', - BROWSERSTACK_ACCESS_KEY: 'browser-key', - BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, - BROWSERSTACK_APP_UPLOAD_ENDPOINT: `${server.url}/app-automate/upload`, - BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `${server.url}/app-automate/sessions`, - }, - clientVersion: CLIENT_VERSION, - runHostCommand: async () => { - throw new Error('BrowserStack scenario must not run host commands'); - }, - }); + const runtimes = [ + await createBrowserStackRuntime({ + env: { + BROWSERSTACK_USERNAME: 'browser-user', + BROWSERSTACK_ACCESS_KEY: 'browser-key', + BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, + BROWSERSTACK_APP_UPLOAD_ENDPOINT: `${server.url}/app-automate/upload`, + BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `${server.url}/app-automate/sessions`, + }, + clientVersion: CLIENT_VERSION, + }), + ]; const providers = createProviderDeviceRuntimeRequestProviders(runtimes); const providerModules = runtimes.map((runtime) => Object.freeze({ runtime, module: runtime.platformRuntimeModule }), @@ -74,7 +72,7 @@ test('lease_allocate over HTTP prepares the BrowserStack session end to end', as tenantId: 'team-a', runId: 'run-a', leaseBackend: 'android-instance', - leaseProvider: CLOUD_WEBDRIVER_PROVIDERS.browserStack, + leaseProvider: BROWSERSTACK_PROVIDER, deviceKey: 'webdriver-android-a', clientId: 'client-a', }, diff --git a/test/integration/provider-scenarios/cloud-webdriver-provider-adapters.test.ts b/test/integration/provider-scenarios/cloud-webdriver-provider-adapters.test.ts index bf9d7633e5..8852e9c5c9 100644 --- a/test/integration/provider-scenarios/cloud-webdriver-provider-adapters.test.ts +++ b/test/integration/provider-scenarios/cloud-webdriver-provider-adapters.test.ts @@ -1,19 +1,16 @@ -import { createBundledCloudWebDriverRuntimes } from './bundled-cloud-webdriver-runtimes.ts'; +import { + BROWSERSTACK_PROVIDER, + browserStackWebDriver, + createBrowserStackRuntime, +} from './browserstack-runtime.ts'; +import { AWS_DEVICE_FARM_PROVIDER, createAwsDeviceFarmRuntime } from './aws-runtime.ts'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import type { IncomingHttpHeaders } from 'node:http'; import path from 'node:path'; import { test } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { - bundledCloudWebDriverProvider, - type RunHostCommand, -} from '@agent-device/provider-webdriver'; -import type { - DeviceLease, - LeaseLifecycleContext, - ProviderDeviceRuntime, -} from '@agent-device/contracts/device'; +import type { DeviceLease, LeaseLifecycleContext } from '@agent-device/contracts/device'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; import type { CloudArtifactsResult } from '@agent-device/contracts/observability'; import { withProviderScenarioResource, withProviderScenarioTempDir } from './harness.ts'; @@ -26,9 +23,8 @@ import { } from './cloud-webdriver-test-server.ts'; import testmu from '@agent-device/testmu'; -import { createPluginHost } from '@agent-device/plugins/host'; +import { createPluginHost, type RunHostCommand } from '@agent-device/plugins/host'; import { createCloudWebDriverRuntime } from '@agent-device/provider-webdriver/plugin'; -import { CLOUD_WEBDRIVER_PROVIDERS } from '@agent-device/provider-webdriver/providers'; const CLIENT_VERSION = '0.20.3-test'; @@ -37,21 +33,17 @@ test('BrowserStack facade prepares capabilities, uploads apps, and returns artif await withProviderScenarioTempDir('agent-device-browserstack-adapter-', async (tempDir) => { const appPath = path.join(tempDir, 'demo.apk'); fs.writeFileSync(appPath, 'fake apk'); - const runtime = runtimeFor( - await createBundledCloudWebDriverRuntimes({ - env: { - BROWSERSTACK_USERNAME: 'user', - BROWSERSTACK_ACCESS_KEY: 'key', - BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, - BROWSERSTACK_APP_UPLOAD_ENDPOINT: `${server.url}/app-automate/upload`, - BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `${server.url}/app-automate/sessions`, - }, - clientVersion: CLIENT_VERSION, - runHostCommand: unexpectedHostCommand, - }), - CLOUD_WEBDRIVER_PROVIDERS.browserStack, - ); - const lease = makeLease(CLOUD_WEBDRIVER_PROVIDERS.browserStack); + const runtime = await createBrowserStackRuntime({ + env: { + BROWSERSTACK_USERNAME: 'user', + BROWSERSTACK_ACCESS_KEY: 'key', + BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, + BROWSERSTACK_APP_UPLOAD_ENDPOINT: `${server.url}/app-automate/upload`, + BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `${server.url}/app-automate/sessions`, + }, + clientVersion: CLIENT_VERSION, + }); + const lease = makeLease(BROWSERSTACK_PROVIDER); try { const allocation = await runtime.leaseLifecycle.allocate?.( lease, @@ -90,20 +82,16 @@ test('BrowserStack facade prepares capabilities, uploads apps, and returns artif test('BrowserStack facade nests device-feature capabilities inside bstack:options', async () => { await withProviderScenarioResource(FakeCloudProviderServer.start, async (server) => { - const runtime = runtimeFor( - await createBundledCloudWebDriverRuntimes({ - env: { - BROWSERSTACK_USERNAME: 'user', - BROWSERSTACK_ACCESS_KEY: 'key', - BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, - BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `${server.url}/app-automate/sessions`, - }, - clientVersion: CLIENT_VERSION, - runHostCommand: unexpectedHostCommand, - }), - CLOUD_WEBDRIVER_PROVIDERS.browserStack, - ); - const lease = makeLease(CLOUD_WEBDRIVER_PROVIDERS.browserStack); + const runtime = await createBrowserStackRuntime({ + env: { + BROWSERSTACK_USERNAME: 'user', + BROWSERSTACK_ACCESS_KEY: 'key', + BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, + BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `${server.url}/app-automate/sessions`, + }, + clientVersion: CLIENT_VERSION, + }); + const lease = makeLease(BROWSERSTACK_PROVIDER); const context = browserStackContext(lease); try { await runtime.leaseLifecycle.allocate?.(lease, { @@ -152,15 +140,12 @@ test('BrowserStack facade nests device-feature capabilities inside bstack:option test('AWS Device Farm facade rejects device features it does not read at session preparation', async () => { await withProviderScenarioResource(FakeCloudProviderServer.start, async (server) => { const host = new FakeAwsHostCommand(`${server.url}/wd/hub/`); - const runtime = runtimeFor( - await createBundledCloudWebDriverRuntimes({ - env: { AWS_REGION: 'us-west-2' }, - clientVersion: CLIENT_VERSION, - runHostCommand: host.run, - }), - CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, - ); - const lease = makeLease(CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm); + const runtime = await createAwsDeviceFarmRuntime({ + env: { AWS_REGION: 'us-west-2' }, + clientVersion: CLIENT_VERSION, + runHostCommand: host.run, + }); + const lease = makeLease(AWS_DEVICE_FARM_PROVIDER); const context = awsContext(lease); try { @@ -195,7 +180,7 @@ test('AWS Device Farm facade rejects device features it does not read at session }, 15_000); async function testMuWebDriver(env: Record) { - const setup = await testmu().setup(createPluginHost(env, undefined)); + const setup = await testmu().setup(createPluginHost({ env, cwd: '/' }, undefined)); if (!('webDriver' in setup)) throw new Error('TestMu AI sets up a WebDriver descriptor'); return setup.webDriver; } @@ -321,19 +306,15 @@ test('TestMu uploads the materializer-selected simulator archive through the plu test('BrowserStack refuses a refused field on a repeat allocation of its live lease', async () => { await withProviderScenarioResource(FakeCloudProviderServer.start, async (server) => { - const runtime = runtimeFor( - await createBundledCloudWebDriverRuntimes({ - env: { - BROWSERSTACK_USERNAME: 'user', - BROWSERSTACK_ACCESS_KEY: 'key', - BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, - }, - clientVersion: CLIENT_VERSION, - runHostCommand: unexpectedHostCommand, - }), - CLOUD_WEBDRIVER_PROVIDERS.browserStack, - ); - const lease = makeLease(CLOUD_WEBDRIVER_PROVIDERS.browserStack); + const runtime = await createBrowserStackRuntime({ + env: { + BROWSERSTACK_USERNAME: 'user', + BROWSERSTACK_ACCESS_KEY: 'key', + BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, + }, + clientVersion: CLIENT_VERSION, + }); + const lease = makeLease(BROWSERSTACK_PROVIDER); const context = browserStackContext(lease); try { await runtime.leaseLifecycle.allocate?.(lease, context); @@ -353,7 +334,7 @@ test('BrowserStack refuses a refused field on a repeat allocation of its live le ); assert.equal(server.calls.length, sessionCalls); assert.deepEqual(await runtime.leaseLifecycle.heartbeat?.(lease), { - provider: CLOUD_WEBDRIVER_PROVIDERS.browserStack, + provider: BROWSERSTACK_PROVIDER, }); } finally { await runtime.shutdown(); @@ -364,15 +345,12 @@ test('BrowserStack refuses a refused field on a repeat allocation of its live le test('AWS Device Farm facade uses the injected host-command capability for its full lifecycle', async () => { await withProviderScenarioResource(FakeCloudProviderServer.start, async (server) => { const host = new FakeAwsHostCommand(`${server.url}/wd/hub/`); - const runtime = runtimeFor( - await createBundledCloudWebDriverRuntimes({ - env: { AWS_REGION: 'us-west-2' }, - clientVersion: CLIENT_VERSION, - runHostCommand: host.run, - }), - CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, - ); - const lease = makeLease(CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm); + const runtime = await createAwsDeviceFarmRuntime({ + env: { AWS_REGION: 'us-west-2' }, + clientVersion: CLIENT_VERSION, + runHostCommand: host.run, + }); + const lease = makeLease(AWS_DEVICE_FARM_PROVIDER); try { const allocation = await runtime.leaseLifecycle.allocate?.(lease, awsContext(lease)); assert.equal(allocation?.awsDeviceFarmSessionArn, host.sessionArn); @@ -463,21 +441,18 @@ test('AWS Device Farm facade uses the injected host-command capability for its f }); }, 15_000); -test('bundled artifact lookup uses released provider ids without allocating a runtime', async () => { +test('BrowserStack artifact lookup uses the released provider id without allocating a runtime', async () => { await withProviderScenarioResource(FakeCloudProviderServer.start, async (server) => { - const provider = bundledCloudWebDriverProvider(CLOUD_WEBDRIVER_PROVIDERS.browserStack); - assert.ok(provider); - const { webDriver } = provider.create({ - env: { + const webDriver = await browserStackWebDriver( + { BROWSERSTACK_USERNAME: 'user', BROWSERSTACK_ACCESS_KEY: 'key', BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `${server.url}/app-automate/sessions`, }, - clientVersion: CLIENT_VERSION, - runHostCommand: unexpectedHostCommand, - }); + CLIENT_VERSION, + ); const result = await webDriver.listArtifacts?.({ - provider: CLOUD_WEBDRIVER_PROVIDERS.browserStack, + provider: BROWSERSTACK_PROVIDER, providerSessionId: 'wd-1', }); assert.deepEqual( @@ -488,15 +463,6 @@ test('bundled artifact lookup uses released provider ids without allocating a ru }); }); -function runtimeFor( - runtimes: readonly ProviderDeviceRuntime[], - provider: string, -): ProviderDeviceRuntime { - const runtime = runtimes.find((candidate) => candidate.provider === provider); - assert.ok(runtime, `missing ${provider} runtime`); - return runtime; -} - function operationSupport( allocation: Record | undefined, operation: string, @@ -607,10 +573,6 @@ function assertAgentDeviceHeaders(headers: IncomingHttpHeaders | undefined): voi assert.equal(headers?.['x-agent-device-version'], CLIENT_VERSION); } -const unexpectedHostCommand: RunHostCommand = async () => { - throw new Error('unexpected host command'); -}; - class FakeAwsHostCommand { readonly sessionArn = 'arn:aws:devicefarm:session/fake'; readonly calls: string[][] = []; diff --git a/test/integration/provider-scenarios/cloud-webdriver-provider-regressions.test.ts b/test/integration/provider-scenarios/cloud-webdriver-provider-regressions.test.ts index c6666abcf8..cd4bf0154b 100644 --- a/test/integration/provider-scenarios/cloud-webdriver-provider-regressions.test.ts +++ b/test/integration/provider-scenarios/cloud-webdriver-provider-regressions.test.ts @@ -1,10 +1,11 @@ +import { AWS_DEVICE_FARM_PROVIDER } from './aws-runtime.ts'; import { createBundledCloudWebDriverRuntimes } from './bundled-cloud-webdriver-runtimes.ts'; +import { BROWSERSTACK_PROVIDER, createBrowserStackRuntime } from './browserstack-runtime.ts'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { test, vi } from 'vitest'; -import { type RunHostCommand } from '@agent-device/provider-webdriver'; import type { CaptureSnapshotResult } from '@agent-device/contracts/client'; import type { DeviceLease } from '@agent-device/contracts/device'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; @@ -25,7 +26,6 @@ import { providerRegressionLease, providerRuntimeFor, } from './cloud-webdriver-regression-fixtures.ts'; -import { CLOUD_WEBDRIVER_PROVIDERS } from '@agent-device/provider-webdriver/providers'; test('AWS Device Farm endpoint selection skips live-control WebSocket URLs', async () => { await withProviderScenarioResource(ProviderRegressionServer.start, async (server) => { @@ -38,9 +38,9 @@ test('AWS Device Farm endpoint selection skips live-control WebSocket URLs', asy clientVersion: PROVIDER_REGRESSION_CLIENT_VERSION, runHostCommand: host.run, }), - CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, + AWS_DEVICE_FARM_PROVIDER, ); - const lease = providerRegressionLease(CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm); + const lease = providerRegressionLease(AWS_DEVICE_FARM_PROVIDER); try { await runtime.leaseLifecycle.allocate?.(lease, awsRegressionContext()); assert.equal(server.calls[0]?.path, '/wd/hub/session'); @@ -62,19 +62,15 @@ test('AWS Device Farm endpoint selection skips live-control WebSocket URLs', asy test('WebDriver session creation is not retried on transient provider failures', async () => { await withProviderScenarioResource(ProviderRegressionServer.start, async (server) => { server.sessionFailuresRemaining = 1; - const runtime = providerRuntimeFor( - await createBundledCloudWebDriverRuntimes({ - env: { - BROWSERSTACK_USERNAME: 'user', - BROWSERSTACK_ACCESS_KEY: 'key', - BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, - }, - clientVersion: PROVIDER_REGRESSION_CLIENT_VERSION, - runHostCommand: unexpectedHostCommand, - }), - CLOUD_WEBDRIVER_PROVIDERS.browserStack, - ); - const lease = providerRegressionLease(CLOUD_WEBDRIVER_PROVIDERS.browserStack); + const runtime = await createBrowserStackRuntime({ + env: { + BROWSERSTACK_USERNAME: 'user', + BROWSERSTACK_ACCESS_KEY: 'key', + BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, + }, + clientVersion: PROVIDER_REGRESSION_CLIENT_VERSION, + }); + const lease = providerRegressionLease(BROWSERSTACK_PROVIDER); try { await assert.rejects( () => runtime.leaseLifecycle.allocate!(lease, browserStackRegressionContext()), @@ -102,9 +98,9 @@ test('AWS Device Farm rejects local artifact install until upload support exists clientVersion: PROVIDER_REGRESSION_CLIENT_VERSION, runHostCommand: host.run, }), - CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, + AWS_DEVICE_FARM_PROVIDER, ); - const lease = providerRegressionLease(CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm); + const lease = providerRegressionLease(AWS_DEVICE_FARM_PROVIDER); try { await runtime.leaseLifecycle.allocate?.(lease, awsRegressionContext()); const [device] = @@ -135,11 +131,9 @@ test('an active AWS Device Farm owner binds no install-family deployment operati clientVersion: PROVIDER_REGRESSION_CLIENT_VERSION, runHostCommand: host.run, }); - const runtime = runtimes.find( - (candidate) => candidate.provider === CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, - ); + const runtime = runtimes.find((candidate) => candidate.provider === AWS_DEVICE_FARM_PROVIDER); assert.ok(runtime, 'Expected AWS Device Farm runtime'); - const lease = providerRegressionLease(CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm); + const lease = providerRegressionLease(AWS_DEVICE_FARM_PROVIDER); try { await runtime.leaseLifecycle.allocate?.(lease, awsRegressionContext()); @@ -209,9 +203,9 @@ test('AWS Device Farm sends the requested platform in WebDriver capabilities', a clientVersion: PROVIDER_REGRESSION_CLIENT_VERSION, runHostCommand: host.run, }), - CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, + AWS_DEVICE_FARM_PROVIDER, ); - const lease = providerRegressionLease(CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm); + const lease = providerRegressionLease(AWS_DEVICE_FARM_PROVIDER); try { await runtime.leaseLifecycle.allocate?.(lease, awsRegressionContext('ios')); assert.deepEqual(server.calls[0]?.body, { @@ -233,15 +227,16 @@ test('BrowserStack iOS snapshot reaches one shared presenter and public daemon o await withProviderScenarioResource( () => ProviderRegressionServer.start('ios'), async (server) => { - const runtimes = await createBundledCloudWebDriverRuntimes({ - env: { - BROWSERSTACK_USERNAME: 'user', - BROWSERSTACK_ACCESS_KEY: 'key', - BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, - }, - clientVersion: PROVIDER_REGRESSION_CLIENT_VERSION, - runHostCommand: unexpectedHostCommand, - }); + const runtimes = [ + await createBrowserStackRuntime({ + env: { + BROWSERSTACK_USERNAME: 'user', + BROWSERSTACK_ACCESS_KEY: 'key', + BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, + }, + clientVersion: PROVIDER_REGRESSION_CLIENT_VERSION, + }), + ]; const providers = createProviderDeviceRuntimeRequestProviders(runtimes); const daemon = await createProviderScenarioHarness({ ...providers, @@ -312,17 +307,13 @@ test('BrowserStack iOS snapshot reaches one shared presenter and public daemon o ); }); -const unexpectedHostCommand: RunHostCommand = async () => { - throw new Error('unexpected host command'); -}; - function browserStackIosFlags(leaseId?: string): DaemonWireRequest['flags'] { return { platform: 'ios', tenant: 'team-a', runId: 'run-a', leaseId, - leaseProvider: CLOUD_WEBDRIVER_PROVIDERS.browserStack, + leaseProvider: BROWSERSTACK_PROVIDER, device: 'iPhone 15', providerApp: 'bs://preuploaded', providerOsVersion: '17.0', @@ -338,7 +329,7 @@ function browserStackIosMeta(leaseId?: string): DaemonWireRequest['meta'] { runId: 'run-a', leaseId, leaseBackend: 'ios-instance', - leaseProvider: CLOUD_WEBDRIVER_PROVIDERS.browserStack, + leaseProvider: BROWSERSTACK_PROVIDER, deviceKey: 'webdriver-ios-a', clientId: 'client-a', }; diff --git a/test/integration/provider-scenarios/cloud-webdriver-regression-fixtures.ts b/test/integration/provider-scenarios/cloud-webdriver-regression-fixtures.ts index ca2fb6eed7..39dc3b0fb7 100644 --- a/test/integration/provider-scenarios/cloud-webdriver-regression-fixtures.ts +++ b/test/integration/provider-scenarios/cloud-webdriver-regression-fixtures.ts @@ -4,7 +4,7 @@ import type { LeaseLifecycleContext, ProviderDeviceRuntime, } from '@agent-device/contracts/device'; -import type { RunHostCommand } from '@agent-device/provider-webdriver'; +import type { RunHostCommand } from '@agent-device/plugins/host'; import { CloudWebDriverTestServer, type CloudWebDriverHttpCall, diff --git a/test/integration/provider-scenarios/cloud-webdriver-runtime.test.ts b/test/integration/provider-scenarios/cloud-webdriver-runtime.test.ts index 942133fef5..51a6d58d04 100644 --- a/test/integration/provider-scenarios/cloud-webdriver-runtime.test.ts +++ b/test/integration/provider-scenarios/cloud-webdriver-runtime.test.ts @@ -4,7 +4,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { test, vi } from 'vitest'; import { isRequestCanceledError } from '@agent-device/kernel/errors'; -import { createBundledCloudWebDriverRuntimes } from './bundled-cloud-webdriver-runtimes.ts'; +import { BROWSERSTACK_PROVIDER, createBrowserStackRuntime } from './browserstack-runtime.ts'; import type { CloudArtifact } from '@agent-device/contracts/observability'; import type { DeviceLease } from '@agent-device/contracts/device'; import { createProviderDeviceRuntimeRequestProviders } from '../../../src/provider-device-runtime.ts'; @@ -23,9 +23,8 @@ import { startCloudWebDriverTestServer, type StartedCloudWebDriverTestServer, } from './cloud-webdriver-test-server.ts'; -import { CLOUD_WEBDRIVER_PROVIDERS } from '@agent-device/provider-webdriver/providers'; -const WEBDRIVER_PROVIDER = CLOUD_WEBDRIVER_PROVIDERS.browserStack; +const WEBDRIVER_PROVIDER = BROWSERSTACK_PROVIDER; const CLIENT_VERSION = '0.20.3-test'; /** One transparent pixel: enough for a driver answer to be real base64 PNG. */ const TINY_PNG_BASE64 = @@ -223,6 +222,7 @@ test('packaged Cloud WebDriver cancels an abandoned source capture and keeps its try { const capture = daemon.client().capture.snapshot({ + session: 'default', signal: controller.signal, ...leaseClientOptions(lease.leaseId), }); @@ -308,19 +308,18 @@ async function waitForLeaseExpiry(server: FakeWebDriverServer): Promise { async function createCloudWebDriverWorld(params: { leaseTtlMs?: number } = {}) { const server = await FakeWebDriverServer.start(); - const runtimes = await createBundledCloudWebDriverRuntimes({ - env: { - BROWSERSTACK_USERNAME: 'browser-user', - BROWSERSTACK_ACCESS_KEY: 'browser-key', - BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, - BROWSERSTACK_APP_UPLOAD_ENDPOINT: `${server.url}/app-automate/upload`, - BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `${server.url}/app-automate/sessions`, - }, - clientVersion: CLIENT_VERSION, - runHostCommand: async () => { - throw new Error('BrowserStack scenario must not run host commands'); - }, - }); + const runtimes = [ + await createBrowserStackRuntime({ + env: { + BROWSERSTACK_USERNAME: 'browser-user', + BROWSERSTACK_ACCESS_KEY: 'browser-key', + BROWSERSTACK_WEBDRIVER_ENDPOINT: `${server.url}/wd/hub/`, + BROWSERSTACK_APP_UPLOAD_ENDPOINT: `${server.url}/app-automate/upload`, + BROWSERSTACK_SESSION_DETAILS_ENDPOINT: `${server.url}/app-automate/sessions`, + }, + clientVersion: CLIENT_VERSION, + }), + ]; const providers = createProviderDeviceRuntimeRequestProviders(runtimes); const providerModules = runtimes.map((runtime) => Object.freeze({ runtime, module: runtime.platformRuntimeModule }), diff --git a/test/integration/provider-scenarios/harness.ts b/test/integration/provider-scenarios/harness.ts index a0f86fd44c..57450a7348 100644 --- a/test/integration/provider-scenarios/harness.ts +++ b/test/integration/provider-scenarios/harness.ts @@ -109,6 +109,7 @@ export async function createProviderScenarioHarness( const env: NodeJS.ProcessEnv = { PATH: process.env.PATH, HOME: process.env.HOME, + AGENT_DEVICE_HOME: process.env.AGENT_DEVICE_HOME, TMPDIR: process.env.TMPDIR, // A scenario that seeds claims for its daemon names the directory through the process. AGENT_DEVICE_CLAIMS_DIR: process.env.AGENT_DEVICE_CLAIMS_DIR ?? path.join(testRoot, 'claims'), diff --git a/test/integration/provider-scenarios/ios-fold.test.ts b/test/integration/provider-scenarios/ios-fold.test.ts index 61634d53e9..56820f0ddd 100644 --- a/test/integration/provider-scenarios/ios-fold.test.ts +++ b/test/integration/provider-scenarios/ios-fold.test.ts @@ -572,7 +572,6 @@ test.each([ // Exercise the real client envelope and HTTP transport, including timeout classification. const pending: Promise = createDaemonTransport(createTestHostEnvironment())( request, - { daemonLifecycle: 'attach' }, ).catch((error) => ({ ok: false, error: normalizeError(error) })); let settled = false; void pending.then( diff --git a/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts b/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts index 45778445a1..4e0f04e86e 100644 --- a/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts +++ b/test/integration/provider-scenarios/remote-proxy-artifact-tenant.test.ts @@ -51,6 +51,7 @@ test('Provider-backed integration proxy materializes tenant-owned test artifacts id: 'tenant-artifact-lease', method: 'agent_device.lease.allocate', params: { + session: 'default', tenantId: TENANT, runId: 'artifact-run', backend: 'android-instance', diff --git a/test/integration/provider-scenarios/stale-provider-runtime-admission.test.ts b/test/integration/provider-scenarios/stale-provider-runtime-admission.test.ts index 5dca13a202..d64e9e4085 100644 --- a/test/integration/provider-scenarios/stale-provider-runtime-admission.test.ts +++ b/test/integration/provider-scenarios/stale-provider-runtime-admission.test.ts @@ -4,6 +4,7 @@ import path from 'node:path'; import { expect, test, vi } from 'vitest'; import type { DeviceLease } from '@agent-device/contracts/device'; import { createBundledCloudWebDriverRuntimes } from './bundled-cloud-webdriver-runtimes.ts'; +import { BROWSERSTACK_PROVIDER, createBrowserStackRuntime } from './browserstack-runtime.ts'; import { createLimrunRuntime, type LimrunRuntimeDependencies } from '@agent-device/provider-limrun'; import { limrunTestDependencies } from '../../../src/platform-runtime-gateway.fixtures.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -23,7 +24,6 @@ import { awsRegressionContext, } from './cloud-webdriver-regression-fixtures.ts'; import { inspectProviderDeploymentAdmission } from './stale-provider-runtime-admission.fixtures.ts'; -import { CLOUD_WEBDRIVER_PROVIDERS } from '@agent-device/provider-webdriver/providers'; bindTestCommandHost(); @@ -67,7 +67,7 @@ vi.mock('@limrun/api/instance-client', () => ({ test('a released WebDriver device remains provider-owned with deployment unavailable', async () => { const server = await startCloudWebDriverTestServer(new StaleWebDriverServer()); const runtime = await webDriverRuntime(server.url); - const lease = providerLease(CLOUD_WEBDRIVER_PROVIDERS.browserStack, 'webdriver-stale'); + const lease = providerLease(BROWSERSTACK_PROVIDER, 'webdriver-stale'); try { const allocate = runtime.leaseLifecycle.allocate; @@ -170,14 +170,14 @@ test('an active AWS WebDriver device denies unsupported install from facts befor tenant: 'team-a', runId: 'run-a', leaseId, - leaseProvider: CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, + leaseProvider: 'aws-device-farm', }; const meta = { tenantId: 'team-a', runId: 'run-a', leaseId, leaseBackend: 'android-instance' as const, - leaseProvider: CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, + leaseProvider: 'aws-device-farm', deviceKey: 'provider-device-regression', clientId: 'client-a', }; @@ -231,22 +231,14 @@ test('an active AWS WebDriver device denies unsupported install from facts befor }); async function webDriverRuntime(endpoint: string) { - const runtimes = await createBundledCloudWebDriverRuntimes({ + return await createBrowserStackRuntime({ env: { BROWSERSTACK_USERNAME: 'browser-user', BROWSERSTACK_ACCESS_KEY: 'browser-key', BROWSERSTACK_WEBDRIVER_ENDPOINT: `${endpoint}/wd/hub/`, }, clientVersion: 'test', - runHostCommand: async () => { - throw new Error('stale WebDriver admission never invokes host commands'); - }, }); - const runtime = runtimes.find( - (candidate) => candidate.provider === CLOUD_WEBDRIVER_PROVIDERS.browserStack, - ); - if (!runtime) throw new Error('Expected BrowserStack WebDriver runtime'); - return runtime; } async function awsWebDriverRuntime(host: AwsRemoteAccessHost) { @@ -255,9 +247,7 @@ async function awsWebDriverRuntime(host: AwsRemoteAccessHost) { clientVersion: 'test', runHostCommand: host.run, }); - const runtime = runtimes.find( - (candidate) => candidate.provider === CLOUD_WEBDRIVER_PROVIDERS.awsDeviceFarm, - ); + const runtime = runtimes.find((candidate) => candidate.provider === 'aws-device-farm'); if (!runtime) throw new Error('Expected AWS Device Farm WebDriver runtime'); return runtime; } diff --git a/test/integration/sdk-host-public-types.test.ts b/test/integration/sdk-host-public-types.test.ts new file mode 100644 index 0000000000..2d1ab4cb5a --- /dev/null +++ b/test/integration/sdk-host-public-types.test.ts @@ -0,0 +1,98 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { runCmdSync } from '@agent-device/host-kit/command'; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..'); +const TSC_BIN = path.join(repoRoot, 'node_modules/.bin/tsc'); +const COMMAND_TIMEOUT_MS = 120_000; + +function ensureBuiltPackage(): void { + const declarationPath = path.join(repoRoot, 'dist', 'src', 'android-adb.d.ts'); + if (fs.existsSync(declarationPath)) return; + + runCmdSync('pnpm', ['build'], { + cwd: repoRoot, + timeoutMs: COMMAND_TIMEOUT_MS, + }); +} + +test('compiled SDK subpaths require explicit hosts', () => { + ensureBuiltPackage(); + + // Keep the fixture under the package root so TypeScript resolves the + // package self-reference through package.json's compiled `types` export. + const tempRoot = fs.mkdtempSync(path.join(repoRoot, '.tmp-sdk-host-types-')); + try { + fs.writeFileSync( + path.join(tempRoot, 'tsconfig.json'), + JSON.stringify( + { + compilerOptions: { + module: 'NodeNext', + moduleResolution: 'NodeNext', + noEmit: true, + strict: true, + types: ['node'], + }, + include: ['fixture.ts'], + }, + null, + 2, + ), + ); + fs.writeFileSync( + path.join(tempRoot, 'fixture.ts'), + `import { runAndroidShell, runAndroidExecOut } from 'agent-device/android-adb'; +import { resolveAndroidArchivePackageName } from 'agent-device/artifacts'; +import { prepareMetroRuntime } from 'agent-device/metro'; +import { resolveRemoteConfigProfile } from 'agent-device/remote-config'; +import { createLocalArtifactAdapter, type LocalArtifactAdapterOptions } from 'agent-device/io'; + +const host = { env: {}, cwd: '/workspace' }; +declare const device: Parameters[0]; +runAndroidShell(device, ['id'], host); +runAndroidExecOut(device, ['id'], host); +resolveAndroidArchivePackageName('app.apk', host); +prepareMetroRuntime({}, host); +resolveRemoteConfigProfile({ configPath: 'remote.json', ...host }); +createLocalArtifactAdapter({ cwd: host.cwd }); +// @ts-expect-error Android shell requires a host. +runAndroidShell(device, ['id']); +// @ts-expect-error Android exec-out requires a host. +runAndroidExecOut(device, ['id']); +// @ts-expect-error Archive inspection requires a host. +resolveAndroidArchivePackageName('app.apk'); +// @ts-expect-error Metro requires a host. +prepareMetroRuntime({}); +// @ts-expect-error Remote config requires env, including when it is empty. +resolveRemoteConfigProfile({ configPath: 'remote.json', cwd: host.cwd }); +// @ts-expect-error Local artifact I/O requires cwd. +createLocalArtifactAdapter(); +// @ts-expect-error Local artifact options require cwd. +const missingCwd: LocalArtifactAdapterOptions = {}; +void missingCwd; +`, + ); + + const result = runCmdSync( + TSC_BIN, + ['--noEmit', '-p', path.join(tempRoot, 'tsconfig.json'), '--pretty', 'false'], + { + cwd: tempRoot, + timeoutMs: COMMAND_TIMEOUT_MS, + allowFailure: true, + }, + ); + + assert.equal( + result.exitCode, + 0, + `The compiled agent-device SDK declarations no longer preserve the downstream contract:\n${result.stdout}${result.stderr}`, + ); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } +}); diff --git a/test/integration/smoke-provider-cli-disconnect.test.ts b/test/integration/smoke-provider-cli-disconnect.test.ts index 7b666b1bbc..1bb34981c7 100644 --- a/test/integration/smoke-provider-cli-disconnect.test.ts +++ b/test/integration/smoke-provider-cli-disconnect.test.ts @@ -4,14 +4,57 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; +import { pluginHome, selectV2Plugin } from '@agent-device/test-kit'; import { formatResultDebug, runBuiltCliJson } from './cli-json.ts'; import './support/provider-disconnect-fetch.mjs'; +const PROVIDER = 'smoke-cloud'; + +/** + * A hosted provider arrives as an installed plugin, so this flow installs a minimal one: the point + * is the built CLI's connect, open, and disconnect ordering, not a particular provider's API. + */ +const PROVIDER_PLUGIN_SOURCE = `export default () => ({ + apiVersion: 2, + provider: ${JSON.stringify(PROVIDER)}, + credentials: { variables: [] }, + connection: { + capabilities: { + leaseKind: 'direct-device-provider', + requiresAppAttachment: false, + requiresRemoteDaemon: false, + supportsArtifacts: true, + supportsDeferredAppSelection: false, + supportsDirectPortReverse: false, + usesCloudWebDriverLease: true, + }, + resolve: ({ flags }) => ({ + profile: { + leaseProvider: ${JSON.stringify(PROVIDER)}, + platform: flags.platform, + device: flags.device, + providerOsVersion: flags.providerOsVersion, + providerApp: flags.providerApp, + }, + }), + verify: async ({ flags }) => ({ + provider: ${JSON.stringify(PROVIDER)}, + service: 'Smoke Cloud', + verificationMessage: 'Credentials, device, and uploaded app verified.', + device: { status: 'verified', name: flags.device, platform: flags.platform, osVersion: flags.providerOsVersion }, + app: { status: 'verified', reference: flags.providerApp }, + }), + }, + setup: async () => { + throw new Error('The smoke daemon is remote and sets up no provider runtime.'); + }, +});`; + test('built CLI provider flow closes its named session before disconnect cleanup', async (t) => { const fixture = createProviderDaemonFixture(t); const env = createProviderEnv(fixture); - await assertUnnamedRefused(fixture, env, browserStackConnectArgs(fixture)); - const activeSession = await connectBrowserStackProvider(fixture, env); + await assertUnnamedRefused(fixture, env, providerConnectArgs(fixture)); + const activeSession = await connectProvider(fixture, env); await assertUnnamedRefused(fixture, env, ['open', 'Demo']); await openProviderApp(fixture, env, activeSession); await disconnectProviderSession(fixture, env, activeSession); @@ -45,10 +88,11 @@ function createProviderEnv(fixture: ProviderDaemonFixture): NodeJS.ProcessEnv { const fetchFixtureUrl = pathToFileURL( path.join(import.meta.dirname, 'support/provider-disconnect-fetch.mjs'), ).href; + const { home, env: pluginEnv } = pluginHome(); + selectV2Plugin(home, '@agent-device/smoke-cloud', PROVIDER_PLUGIN_SOURCE); return { ...process.env, - BROWSERSTACK_USERNAME: 'browser-user', - BROWSERSTACK_ACCESS_KEY: 'browser-key', + ...pluginEnv, AGENT_DEVICE_TEST_RPC_LOG_PATH: fixture.rpcLogPath, // Generated connection state never persists the daemon bearer token // (ADR 0007), so commands after `connect` must resolve it from the @@ -69,11 +113,11 @@ function readRpcRequests(fixture: ProviderDaemonFixture): any[] { .map((line) => JSON.parse(line)); } -async function connectBrowserStackProvider( +async function connectProvider( fixture: ProviderDaemonFixture, env: NodeJS.ProcessEnv, ): Promise { - const connectArgs = [...browserStackConnectArgs(fixture), '--session', 'bs-smoke']; + const connectArgs = [...providerConnectArgs(fixture), '--session', 'provider-smoke']; const connectResult = await runBuiltCliJson(connectArgs, env); assert.equal(connectResult.status, 0, formatResultDebug('connect', connectArgs, connectResult)); @@ -83,14 +127,14 @@ async function connectBrowserStackProvider( formatResultDebug('connect', connectArgs, connectResult), ); const activeSession = connectResult.json?.data?.session; - assert.equal(activeSession, 'bs-smoke'); + assert.equal(activeSession, 'provider-smoke'); return activeSession; } -function browserStackConnectArgs(fixture: ProviderDaemonFixture): string[] { +function providerConnectArgs(fixture: ProviderDaemonFixture): string[] { return [ 'connect', - 'browserstack', + PROVIDER, '--platform', 'android', '--device', @@ -183,8 +227,8 @@ function assertProviderDisconnectRpc(rpcRequests: any[], activeSession: string): const releaseRpc = rpcRequests.find((request) => request.method === 'agent_device.lease.release'); assert.equal(releaseRpc?.params?.session, activeSession); - assert.equal(releaseRpc?.params?.leaseId, 'lease-bs-1'); - assert.equal(releaseRpc?.params?.leaseProvider, 'browserstack'); + assert.equal(releaseRpc?.params?.leaseId, 'lease-smoke-1'); + assert.equal(releaseRpc?.params?.leaseProvider, PROVIDER); } async function assertNoActiveConnection( diff --git a/test/integration/support/provider-disconnect-fetch.mjs b/test/integration/support/provider-disconnect-fetch.mjs index 383e169cb0..2294faea87 100644 --- a/test/integration/support/provider-disconnect-fetch.mjs +++ b/test/integration/support/provider-disconnect-fetch.mjs @@ -4,8 +4,6 @@ import { EventEmitter } from 'node:events'; import { Readable } from 'node:stream'; const DAEMON_BASE_URL = 'https://agent-device.test/agent-device'; -const DEVICES_URL = 'https://api-cloud.browserstack.com/app-automate/devices.json'; -const APPS_URL = 'https://api-cloud.browserstack.com/app-automate/recent_apps?limit=100'; const rpcLogPath = process.env.AGENT_DEVICE_TEST_RPC_LOG_PATH; if (rpcLogPath) installFixture(rpcLogPath); @@ -18,14 +16,6 @@ function installFixture(logPath) { function createFixtureFetch(logPath) { const routes = [ - route('GET', DEVICES_URL, () => - jsonResponse([ - { os: 'android', os_version: '14.0', device: 'Google Pixel 8', realMobile: true }, - ]), - ), - route('GET', APPS_URL, () => - jsonResponse([{ app_name: 'sample.apk', app_version: '1.2.3', app_url: 'bs://app-id' }]), - ), route('GET', `${DAEMON_BASE_URL}/health`, () => jsonResponse({ ok: true, @@ -103,7 +93,7 @@ async function fetchNodeResponse(fixtureFetch, options, chunks) { const RPC_METHOD_RESPONSES = { 'agent_device.lease.allocate': (params) => ({ lease: { - leaseId: 'lease-bs-1', + leaseId: 'lease-smoke-1', tenantId: params.tenantId, runId: params.runId, backend: params.backend, @@ -114,7 +104,7 @@ const RPC_METHOD_RESPONSES = { }), 'agent_device.lease.release': () => ({ released: true, - provider: { provider: 'browserstack', providerSessionId: 'bs-session-1' }, + provider: { provider: 'smoke-cloud', providerSessionId: 'smoke-session-1' }, }), }; @@ -126,11 +116,11 @@ const COMMAND_RESPONSES = { platform: 'android', target: 'mobile', device: 'Pixel', - id: 'browserstack-pixel', - serial: 'browserstack-pixel', + id: 'smoke-cloud-pixel', + serial: 'smoke-cloud-pixel', }), close: () => ({ - provider: { provider: 'browserstack', providerSessionId: 'bs-session-1' }, + provider: { provider: 'smoke-cloud', providerSessionId: 'smoke-session-1' }, }), }; diff --git a/test/repo-guards/npm-package-scripts.test.ts b/test/repo-guards/npm-package-scripts.test.ts index 7ad65885a9..010adee62d 100644 --- a/test/repo-guards/npm-package-scripts.test.ts +++ b/test/repo-guards/npm-package-scripts.test.ts @@ -98,7 +98,11 @@ test('publishing cannot skip the package gate', () => { assert.equal(getCheckSpec('package').localRunnable, true); // The minimum-Node job runs the script directly — the repo's pinned pnpm needs a newer Node than // the floor that job covers — so it must still name the same entry point the script does. - assert.match(script('check:package'), /scripts\/check-package\.ts$/); + assert.deepEqual(script('check:package').split(' && '), [ + 'node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs packages/maestro/test/package-smoke.mjs packages/replay/test/package-smoke.mjs', + 'node --experimental-strip-types scripts/check-package.ts', + ]); + assert.match(packagedCliWorkflow, /with: \{ gate: package \}/); assert.match( packagedCliWorkflow, /run: node --experimental-strip-types scripts\/check-package\.ts/, diff --git a/test/repo-guards/package-exports.test.ts b/test/repo-guards/package-exports.test.ts index 74860be94f..6b8e0e93fb 100644 --- a/test/repo-guards/package-exports.test.ts +++ b/test/repo-guards/package-exports.test.ts @@ -29,7 +29,6 @@ const supportedSubpaths = [ './remote-config', './install-source', './android-adb', - './limrun', './contracts', './selectors', './finders', diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index bdabba0ca5..7a29d7aaa8 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -120,10 +120,10 @@ "packages/daemon/src/server/http/http-authorization.ts#readHeaderValue": "sha256:0ec16993e5d9b460ba02deb4a43bbc4c248f9697eaed9aa64003eec7d5dce6bf", "packages/daemon/src/server/http/http-authorization.ts#resolveToken": "sha256:3abcb019e1325317618045b7138e41845990af10953dd937571997cd6ec35981", "packages/daemon/src/server/http/http-rpc-envelope.ts#sendJson": "sha256:a1de00da3f1db8c98e69a85dfe2e11b626a4d2ce472840e3b8f519aa8a207a8f", - "packages/daemon/src/server/http/http-rpc-methods.ts#toDaemonRequest": "sha256:d6afa5f8f1219e519e72bbd6fddd7de7763818f1ed7ae2a1e2a12001bd66bd52", - "packages/daemon/src/server/http/http-rpc-methods.ts#toInstallFromSourceDaemonRequest": "sha256:071c53e7bd8e553cb9df820961294ed4d1e2e385053485364d895cb1777e9429", - "packages/daemon/src/server/http/http-rpc-methods.ts#toLeaseDaemonRequest": "sha256:e017795c86534feb8a7e6e53ffbd614db893aad20c5406b2bc53c771ee646948", - "packages/daemon/src/server/http/http-rpc-methods.ts#toReleaseMaterializedPathsDaemonRequest": "sha256:708736ca03d6a3fc449bb408382dbd509e490de1f84ecc8771fd77d4adda0154", + "packages/daemon/src/server/http/http-rpc-methods.ts#toDaemonRequest": "sha256:14743424656a7a4097eb184d2be2c6272d0b1ff645591e4f4f9430d030789013", + "packages/daemon/src/server/http/http-rpc-methods.ts#toInstallFromSourceDaemonRequest": "sha256:ed1ddf10113ac9c076b3fc0d08a77c12f22ac1ca98347f8f3f8271a5a0daf74e", + "packages/daemon/src/server/http/http-rpc-methods.ts#toLeaseDaemonRequest": "sha256:3e4211293791d67371ece10bf88a6f197598b399ece1041fc22e253691f3cdc2", + "packages/daemon/src/server/http/http-rpc-methods.ts#toReleaseMaterializedPathsDaemonRequest": "sha256:a600285c173c95a75093c9eae65ee96df63d9524f7cc96c0479cf9884069f17c", "packages/daemon/src/server/http/http-rpc-envelope.ts#writeProgressEnvelope": "sha256:7be778b3902c72d7aa6282c16dc7106fdd64e99c0b5daf9f413ff5dd3fb044f1", "packages/daemon/src/server/http/http-rpc-envelope.ts#writeRpcResponseEnvelope": "sha256:7a8155e9fcbb53485489728250a85109b5dab0d96cdd4aa8b7e7eb87a4898ddb", "packages/daemon/src/core/session-tenant-scope.ts#TenantSessionNamespace": "sha256:a6613d22933caa053e479f05b7f016664f6be8d0afdbbf81e578ff497fc1b13d", @@ -197,7 +197,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#isRemoteInstanceMismatchResponse": "sha256:7670f48fe0fc7344f8a000cd303e49788ec7ea9d1c729bcdc2af73ff02dae04d", "packages/daemon-client/src/daemon-client-transport.ts#isRemoteInstanceMismatch": "sha256:6d4cfdd36bd44686d2a48990491faf63ba9117fb760f982fd72922c99be8daee", "packages/contracts/src/lease-scope.ts#buildDaemonRpcRequest": "sha256:b3d03bb08f8f332b04dea6d2ea30abca2faf83a10f11cb874df2344b3f54c2b6", - "packages/contracts/src/lease-scope.ts#buildLeaseRpcParams": "sha256:365490a0fe1833d7ce8b0d3f5425462608a85119b12c1a2c4f16bb83b5d28e06", + "packages/contracts/src/lease-scope.ts#buildLeaseRpcParams": "sha256:25b138457410480048ee3899ce758cdd80bd7a4d11dc6e025f1365e7e8729116", "packages/contracts/src/lease-scope.ts#isLeaseRpcCommand": "sha256:955dc1b73462d40593e5728dbcbaeec1307944b08262a22627e84cc5dc507e8f", "packages/contracts/src/lease-scope.ts#leaseRpcMethodForCommand": "sha256:3613555c6002c23ab5bec4b98bc1b4d6947014b52fa100176177f955cf762881", "packages/contracts/src/daemon-wire-request.ts#DaemonWireRequestMeta": "sha256:369be6aca9cfe20d221b40f5f6ab287ff11e148cc3f7e04fbbfa78be5df31e52", @@ -217,7 +217,8 @@ "packages/remote/src/session-script-destination.ts#publishScriptVersion": "sha256:9d6ceb538019c0ce30813fcf98d2484c5abc2d8fd7a3dfdd4141cf6430f086ff", "packages/remote/src/session-script-destination.ts#PublishOutcome": "sha256:a4ae6fc3298d3c560719591372edddbfa83ce749f4cf3f3e2ed1d8369313bd2d", "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen": "sha256:10ab07a6f276c7b03996c6b46fa218e03e7b1d21e2c95df5515dfb88095416b6", - "packages/remote/src/session-script-destination.ts#RemoteEndpoint": "sha256:9c48e8e0ee14a25b85ebd930243fd263134836b35ecda55fb927919911263c15" + "packages/remote/src/session-script-destination.ts#RemoteEndpoint": "sha256:9c48e8e0ee14a25b85ebd930243fd263134836b35ecda55fb927919911263c15", + "packages/daemon/src/core/request-session-intake.ts#resolveRequestSessionAtIntake": "sha256:d620b6ee56a8c2f74d2c161016fa19974cbc833e3b87fa522411e35b381d9bc9" }, "compatibleChanges": [ { @@ -252,8 +253,8 @@ }, { "declaration": "packages/daemon/src/server/http/http-rpc-methods.ts#toLeaseDaemonRequest", - "digest": "sha256:e017795c86534feb8a7e6e53ffbd614db893aad20c5406b2bc53c771ee646948", - "rationale": "#2110 read the optional providerApp lease-allocation parameter into the existing flags bag; #2494 reads the full provider-allocation flag set into that same bag through the shared readLeaseAllocateProviderFlags projection, so the reconstructed req.flags handed to prepareSession match what the line transport forwards for free. Released protocol-2 clients omit these and follow the unchanged allocation path; no existing field is required or reinterpreted. The optional retainOnClose boolean parameter is read into meta.leaseRetainOnClose; a released daemon ignores it and keeps releasing on session close. Reads the optional providerCredentialFingerprint lease-allocation parameter into request meta, so a local caller over HTTP gets the same credential check as over the socket. A daemon with an auth hook treats every HTTP caller as remote and strips it, as it does developerDir. Released protocol-2 clients omit it and follow the unchanged allocation path; no existing field is required or reinterpreted. Reads or forwards the optional devicePin allocation parameter. Released clients omit it; older daemons ignore it. Existing fields keep their meanings under ADR 0006. Validates the optional devicePin metadata through the shared parser before dispatch. Existing valid pins and requests that omit a pin keep their request projection. Malformed pin objects now fail clearly with the existing INVALID_ARGS envelope and invalid_device_pin reason instead of a later TypeError. This repairs validation of an unreleased optional field; routes, authentication, framing, and existing fields are unchanged under ADR 0006." + "digest": "sha256:3e4211293791d67371ece10bf88a6f197598b399ece1041fc22e253691f3cdc2", + "rationale": "#2110 read the optional providerApp lease-allocation parameter into the existing flags bag; #2494 reads the full provider-allocation flag set into that same bag through the shared readLeaseAllocateProviderFlags projection, so the reconstructed req.flags handed to prepareSession match what the line transport forwards for free. Released protocol-2 clients omit these and follow the unchanged allocation path; no existing field is required or reinterpreted. The optional retainOnClose boolean parameter is read into meta.leaseRetainOnClose; a released daemon ignores it and keeps releasing on session close. Reads the optional providerCredentialFingerprint lease-allocation parameter into request meta, so a local caller over HTTP gets the same credential check as over the socket. A daemon with an auth hook treats every HTTP caller as remote and strips it, as it does developerDir. Released protocol-2 clients omit it and follow the unchanged allocation path; no existing field is required or reinterpreted. Reads or forwards the optional devicePin allocation parameter. Released clients omit it; older daemons ignore it. Existing fields keep their meanings under ADR 0006. Validates the optional devicePin metadata through the shared parser before dispatch. Existing valid pins and requests that omit a pin keep their request projection. Malformed pin objects now fail clearly with the existing INVALID_ARGS envelope and invalid_device_pin reason instead of a later TypeError. This repairs validation of an unreleased optional field; routes, authentication, framing, and existing fields are unchanged under ADR 0006. #4171 records a request that names no session in daemon-only request state: a missing or blank session, or meta.sessionExplicit false with no named flag. A missing name becomes default, a blank one keeps its literal as released daemons did, and the literal default from a client stays. Lease params gain an optional sessionExplicit, which a released daemon ignores. A released client that names no session on a provider lease through the command method now gets a normal INVALID_ARGS error with reason REMOTE_SESSION_REQUIRED, and no peer misreads a payload." }, { "declaration": "packages/kernel/src/errors.ts#DaemonError", @@ -308,7 +309,7 @@ { "declaration": "packages/daemon/src/server/http/http-authorization.ts#authorizeAuxiliaryHttpRequest", "digest": "sha256:1c323f97c3cefec8f95633b6abd127342bf75494bfb109d1cc6eadf3ceacaeae", - "rationale": "#2198 context: adds one optional field to the value this DAEMON-INTERNAL gate hands its own route handlers — sessionNamespace, the caller's tenant plus whether the daemon partitioned that caller's session names. Nothing about it is serialized: no request header is read that was not read before, no response field is added, and a refusal keeps the same 401 {ok:false,error,code} REST body sendRestJsonError already sent. What it enables is a refusal DROPPED, never one added — an unattested (client-declared) tenant no longer has the : prefix rule applied to it, because scopeRequestSession never applied that prefix to its sessions either. A released peer that now gets 200 where it got 401 is getting the ndjson record it asked for and already parses." + "rationale": "#2198 context: adds one optional field to the value this DAEMON-INTERNAL gate hands its own route handlers \u2014 sessionNamespace, the caller's tenant plus whether the daemon partitioned that caller's session names. Nothing about it is serialized: no request header is read that was not read before, no response field is added, and a refusal keeps the same 401 {ok:false,error,code} REST body sendRestJsonError already sent. What it enables is a refusal DROPPED, never one added \u2014 an unattested (client-declared) tenant no longer has the : prefix rule applied to it, because scopeRequestSession never applied that prefix to its sessions either. A released peer that now gets 200 where it got 401 is getting the ndjson record it asked for and already parses." }, { "declaration": "packages/daemon/src/server/request-diagnostics-http.ts#RequestDiagnosticsHttpAuthorizer", @@ -472,8 +473,8 @@ }, { "declaration": "packages/contracts/src/lease-scope.ts#buildLeaseRpcParams", - "digest": "sha256:365490a0fe1833d7ce8b0d3f5425462608a85119b12c1a2c4f16bb83b5d28e06", - "rationale": "The client names its request as DaemonWireRequest (packages/contracts/src/daemon-wire-request.ts, a narrowing of the listed kernel DaemonRequest) and its response as the kernel DaemonResponse, instead of the daemon package's DaemonRequest/DaemonResponse aliases, so the daemon package is no longer a client import. The declaration's serialized fields, method names and framing are unchanged; only the compile-time type names in its signature moved, so a peer on protocol 2 parses exactly what it did." + "digest": "sha256:25b138457410480048ee3899ce758cdd80bd7a4d11dc6e025f1365e7e8729116", + "rationale": "The client names its request as DaemonWireRequest (packages/contracts/src/daemon-wire-request.ts, a narrowing of the listed kernel DaemonRequest) and its response as the kernel DaemonResponse, instead of the daemon package's DaemonRequest/DaemonResponse aliases, so the daemon package is no longer a client import. The declaration's serialized fields, method names and framing are unchanged; only the compile-time type names in its signature moved, so a peer on protocol 2 parses exactly what it did. #4171 records a request that names no session in daemon-only request state: a missing or blank session, or meta.sessionExplicit false with no named flag. A missing name becomes default, a blank one keeps its literal as released daemons did, and the literal default from a client stays. Lease params gain an optional sessionExplicit, which a released daemon ignores. A released client that names no session on a provider lease through the command method now gets a normal INVALID_ARGS error with reason REMOTE_SESSION_REQUIRED, and no peer misreads a payload." }, { "declaration": "packages/daemon/src/server/http-errors.ts#statusCodeForNormalizedError", @@ -537,8 +538,8 @@ }, { "declaration": "packages/daemon/src/server/http/http-rpc-methods.ts#toInstallFromSourceDaemonRequest", - "digest": "sha256:071c53e7bd8e553cb9df820961294ed4d1e2e385053485364d895cb1777e9429", - "rationale": "Implementation-only validation repair: a supplied retentionMs is validated before request projection instead of silently dropping fractions or malformed values. Existing integer values in the supported 1..2147483647 range and omitted values keep their request projection, defaults, payload fields and response framing. Unsupported durations now fail clearly with the existing INVALID_ARGS envelope; released clients can parse that normal command error. No route, authentication, method or wire field changes; no protocol bump under ADR 0006." + "digest": "sha256:ed1ddf10113ac9c076b3fc0d08a77c12f22ac1ca98347f8f3f8271a5a0daf74e", + "rationale": "Implementation-only validation repair: a supplied retentionMs is validated before request projection instead of silently dropping fractions or malformed values. Existing integer values in the supported 1..2147483647 range and omitted values keep their request projection, defaults, payload fields and response framing. Unsupported durations now fail clearly with the existing INVALID_ARGS envelope; released clients can parse that normal command error. No route, authentication, method or wire field changes; no protocol bump under ADR 0006. #4171 records a request that names no session in daemon-only request state: a missing or blank session, or meta.sessionExplicit false with no named flag. A missing name becomes default, a blank one keeps its literal as released daemons did, and the literal default from a client stays. Lease params gain an optional sessionExplicit, which a released daemon ignores. A released client that names no session on a provider lease through the command method now gets a normal INVALID_ARGS error with reason REMOTE_SESSION_REQUIRED, and no peer misreads a payload." }, { "declaration": "packages/contracts/src/lease-scope.ts#buildDaemonRpcRequest", @@ -547,8 +548,8 @@ }, { "declaration": "packages/daemon/src/server/http/http-rpc-methods.ts#toDaemonRequest", - "digest": "sha256:d6afa5f8f1219e519e72bbd6fddd7de7763818f1ed7ae2a1e2a12001bd66bd52", - "rationale": "Validates the optional devicePin metadata through the shared parser before dispatch. Existing valid pins and requests that omit a pin keep their request projection. Malformed pin objects now fail clearly with the existing INVALID_ARGS envelope and invalid_device_pin reason instead of a later TypeError. This repairs validation of an unreleased optional field; routes, authentication, framing, and existing fields are unchanged under ADR 0006." + "digest": "sha256:14743424656a7a4097eb184d2be2c6272d0b1ff645591e4f4f9430d030789013", + "rationale": "Validates the optional devicePin metadata through the shared parser before dispatch. Existing valid pins and requests that omit a pin keep their request projection. Malformed pin objects now fail clearly with the existing INVALID_ARGS envelope and invalid_device_pin reason instead of a later TypeError. This repairs validation of an unreleased optional field; routes, authentication, framing, and existing fields are unchanged under ADR 0006. #4171 records a request that names no session in daemon-only request state: a missing or blank session, or meta.sessionExplicit false with no named flag. A missing name becomes default, a blank one keeps its literal as released daemons did, and the literal default from a client stays. Lease params gain an optional sessionExplicit, which a released daemon ignores. A released client that names no session on a provider lease through the command method now gets a normal INVALID_ARGS error with reason REMOTE_SESSION_REQUIRED, and no peer misreads a payload." }, { "declaration": "packages/contracts/src/device-inventory.ts#parseDevicePinSelector", @@ -584,6 +585,16 @@ "declaration": "packages/remote/src/artifact-download.ts#RemoteArtifactDownload", "digest": "sha256:e87a625bdff05fa55f6321ff09a35496f59edd228a1d7420268d54fcc2982868", "rationale": "#4511 adds the optional client-local privateFile field: the download creates a new 0600 file exclusively, never through a symbolic link, and stops once it crosses maxBytes. It is never sent, and every existing call site omits it, so the GET /artifacts/:id framing is unchanged." + }, + { + "declaration": "packages/daemon/src/server/http/http-rpc-methods.ts#toReleaseMaterializedPathsDaemonRequest", + "digest": "sha256:a600285c173c95a75093c9eae65ee96df63d9524f7cc96c0479cf9884069f17c", + "rationale": "#4171 records a request that names no session in daemon-only request state: a missing or blank session, or meta.sessionExplicit false with no named flag. A missing name becomes default, a blank one keeps its literal as released daemons did, and the literal default from a client stays. Lease params gain an optional sessionExplicit, which a released daemon ignores. A released client that names no session on a provider lease through the command method now gets a normal INVALID_ARGS error with reason REMOTE_SESSION_REQUIRED, and no peer misreads a payload." + }, + { + "declaration": "packages/daemon/src/core/request-session-intake.ts#resolveRequestSessionAtIntake", + "digest": "sha256:d620b6ee56a8c2f74d2c161016fa19974cbc833e3b87fa522411e35b381d9bc9", + "rationale": "#4171 records a request that names no session in daemon-only request state: a missing or blank session, or meta.sessionExplicit false with no named flag. A missing name becomes default, a blank one keeps its literal as released daemons did, and the literal default from a client stays. Lease params gain an optional sessionExplicit, which a released daemon ignores. A released client that names no session on a provider lease through the command method now gets a normal INVALID_ARGS error with reason REMOTE_SESSION_REQUIRED, and no peer misreads a payload." } ] } diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index 323fd76881..2bd63e05d3 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -269,6 +269,10 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'toInstallFromSourceDaemonRequest', 'toReleaseMaterializedPathsDaemonRequest', ), + ...from( + 'packages/daemon/src/core/request-session-intake.ts', + 'resolveRequestSessionAtIntake', + ), // Consumer side: the payload the client actually puts on the wire. A // client-only change here breaks an older daemon just as surely. ...from(CLIENT_RPC, 'buildHttpRpcPayload'), diff --git a/test/wire-compat/wire-mutations.test.ts b/test/wire-compat/wire-mutations.test.ts index a88c4e027a..7b673cb5a2 100644 --- a/test/wire-compat/wire-mutations.test.ts +++ b/test/wire-compat/wire-mutations.test.ts @@ -147,6 +147,13 @@ const MUTATIONS: readonly WireMutation[] = [ from: "'agent-device.lease.allocate': 'lease_allocate',", to: '', }, + { + breakClass: 'session intake: an unnamed request stops being marked as unnamed', + file: 'packages/daemon/src/core/request-session-intake.ts', + name: 'resolveRequestSessionAtIntake', + from: 'internal: { sessionOmitted: true }', + to: 'internal: {}', + }, { breakClass: 'response serialization: the RPC envelope stops being newline-framed', file: 'packages/daemon-contracts/src/request-progress-protocol.ts', diff --git a/tsconfig.typecheck.json b/tsconfig.typecheck.json index 8380463560..294ec3aa87 100644 --- a/tsconfig.typecheck.json +++ b/tsconfig.typecheck.json @@ -5,6 +5,7 @@ "extends": "./tsconfig.json", "compilerOptions": { "tsBuildInfoFile": "./.tmp/tsconfig.typecheck.tsbuildinfo" }, "references": [ + { "path": "packages/build-config" }, { "path": "packages/ad-replay" }, { "path": "packages/ad-script" }, { "path": "packages/apple-runner" }, @@ -30,6 +31,8 @@ { "path": "packages/platform-web" }, { "path": "packages/plugins" }, { "path": "packages/provider-limrun" }, + { "path": "packages/provider-aws-device-farm" }, + { "path": "packages/provider-browserstack" }, { "path": "packages/provider-revyl" }, { "path": "packages/provider-testmu" }, { "path": "packages/provider-webos" }, @@ -39,6 +42,7 @@ { "path": "packages/proxy" }, { "path": "packages/react-native" }, { "path": "packages/remote" }, + { "path": "packages/replay" }, { "path": "packages/replay-port" }, { "path": "packages/replay-test" }, { "path": "packages/selectors" }, diff --git a/tsdown.config.ts b/tsdown.config.ts index 5412d1a204..71ad1a64f0 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -1,9 +1,13 @@ import { buildEntries } from './scripts/build-entries.ts'; import fs from 'node:fs'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; import { defineConfig, type TsdownPluginOption } from 'tsdown'; import { bundledLicenseNotices } from './scripts/lib/bundled-license-notices.ts'; -const typeScriptPackageJsonUrl = import.meta.resolve('typescript/package.json'); +const typeScriptPackageJsonUrl = pathToFileURL( + createRequire(import.meta.url).resolve('typescript/package.json'), +); const { default: getTypeScript7ExePath } = await import( new URL('lib/getExePath.js', typeScriptPackageJsonUrl).href ); @@ -151,10 +155,16 @@ export default defineConfig({ hash: false, outputOptions: { codeSplitting: { - groups: publicSdkChunkGroups.flatMap(([name, dtsTest, jsTest]) => [ - { test: dtsTest, name: `${name}.d` }, - { test: jsTest, name }, - ]), + groups: [ + ...publicSdkChunkGroups.flatMap(([name, dtsTest, jsTest]) => [ + { test: dtsTest, name: `${name}.d` }, + { test: jsTest, name }, + ]), + { + test: /packages[\\/]contracts[\\/]src[\\/]replay-backend\.d\.[cm]?ts$/, + name: 'sdk-replay-backend.d', + }, + ], }, }, outExtensions: () => ({ js: '.js', dts: '.d.ts' }), diff --git a/vitest.config.ts b/vitest.config.ts index 0335d9caac..837250d672 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -87,6 +87,7 @@ export const SETUP_FILES = [ 'src/__tests__/hermetic-env-setup.ts', 'src/__tests__/hermetic-signal-setup.ts', 'src/__tests__/process-memo-setup.ts', + 'src/__tests__/replay-plugin-setup.ts', ]; export default defineConfig({ @@ -219,6 +220,7 @@ export default defineConfig({ 'scripts/__tests__/release-version.test.ts', 'scripts/__tests__/release-plan.test.ts', 'scripts/__tests__/release-publish.test.ts', + 'scripts/__tests__/install-workspace-replay-plugins.test.ts', 'scripts/ios-snapshot-benchmark/*.test.ts', // The perf suite's pure logic, without a device. 'scripts/perf/*.test.ts', @@ -242,6 +244,7 @@ export default defineConfig({ // The Android failed-step evidence reader: it replays adb output through the probe // seam, so the crash/process/activity selectors need no emulator to be pinned. 'test/integration/android-emulator-e2e/device-evidence.test.ts', + 'test/integration/android-emulator-e2e/live-automation-scenario.test.ts', 'test/integration/android-emulator-e2e/live-ime-window.test.ts', // The frozen replay-compat corpus (#1417): parse-only, no device or // subprocess work, so it belongs in the fast lane next to the diff --git a/vitest.mutation.config.ts b/vitest.mutation.config.ts index ea62e42ed9..d036797710 100644 --- a/vitest.mutation.config.ts +++ b/vitest.mutation.config.ts @@ -22,6 +22,7 @@ export default defineConfig({ alias: workspaceAliases, }, test: { + globalSetup: [path.join(repoRoot, 'scripts/vitest-tmpdir-global-setup.ts')], include: scope, exclude: [ ...MUTATION_EXCLUDED_TESTS, diff --git a/website/docs/docs/ai-sdk.md b/website/docs/docs/ai-sdk.md index b508497b0e..65b401e24b 100644 --- a/website/docs/docs/ai-sdk.md +++ b/website/docs/docs/ai-sdk.md @@ -19,8 +19,10 @@ Alternatively, pass a model from your configured AI SDK provider. See the AI SDK ```ts import { ToolLoopAgent } from 'ai'; +import { ensureDaemon, isAgentDeviceError } from 'agent-device'; import { createAgentDeviceTools } from 'agent-device/ai-sdk'; +await ensureDaemon(); const { tools, client } = await createAgentDeviceTools({ session: 'ai-sdk-agent', platform: 'ios', @@ -42,7 +44,11 @@ try { console.log(result.text); } finally { - await client.sessions.close(); + await client.sessions.close().catch((error) => { + if (isAgentDeviceError(error) && error.code === 'SESSION_NOT_FOUND') return; + console.error('Session cleanup failed:', error); + process.exitCode = 1; + }); } ``` diff --git a/website/docs/docs/aws-device-farm.md b/website/docs/docs/aws-device-farm.md index 5770ec8d24..9c064ee7b0 100644 --- a/website/docs/docs/aws-device-farm.md +++ b/website/docs/docs/aws-device-farm.md @@ -5,6 +5,29 @@ description: Drive AWS Device Farm remote-access sessions with agent-device. Use AWS Device Farm to run agent-device on hosted Android and iOS devices through remote-access WebDriver sessions. You need an AWS account with a Device Farm project and the AWS CLI installed. AWS Device Farm does not cover Vega OS: agent-device rejects a Vega Fire TV ARN. For Vega, use a local Vega Virtual Device (VVD). +## Install the plugin + +Install the plugin on the host that runs the daemon. + +```bash +agent-device plugins add @agent-device/aws-device-farm@nightly-0.22 +``` + +If the CLI prints an install command in a missing-plugin error, use that command. + +After installing or changing a plugin, finish sessions and run `agent-device daemon stop --state-dir ` for the matching detached daemon, then retry the command. + +For an embedded runtime, import the factory and pass it to `startAgentDevice`. The embedded runtime does not read the CLI plugin store. After changing plugins, close and recreate the runtime. + +```ts +import { startAgentDevice } from "agent-device"; +import awsDeviceFarm from "@agent-device/aws-device-farm/agent-device"; + +const runtime = await startAgentDevice({ stateDir: "./.agent-device-state", plugins: [awsDeviceFarm()] }); +// Close the runtime when its owner is finished. +await runtime.close(); +``` + ## Set credentials and connect agent-device runs `aws devicefarm ...`, so it uses the AWS CLI credential provider chain and works with any non-interactive AWS CLI credential source in CI. You do not need `aws login`. See the [AWS CLI environment variable reference](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html) for supported credential sources. @@ -83,9 +106,11 @@ To drive AWS Device Farm only through MCP, see [Use a provider only through MCP] Configure the client directly when your Node.js process manages the AWS credentials and selectors: ```ts -import { createAgentDeviceClient } from 'agent-device'; +import { createAgentDeviceClient, ensureDaemon } from 'agent-device'; +await ensureDaemon(); const client = createAgentDeviceClient({ + session: 'checkout-android', leaseProvider: 'aws-device-farm', awsProjectArn: process.env.AWS_DEVICE_FARM_PROJECT_ARN, awsDeviceArn: process.env.AWS_DEVICE_FARM_DEVICE_ARN, diff --git a/website/docs/docs/browserstack.md b/website/docs/docs/browserstack.md index fd78e337b3..a45582a2fd 100644 --- a/website/docs/docs/browserstack.md +++ b/website/docs/docs/browserstack.md @@ -3,7 +3,21 @@ title: BrowserStack description: Drive BrowserStack App Automate sessions with agent-device. --- -Use BrowserStack App Automate to run agent-device on hosted Android and iOS devices over WebDriver. You need a BrowserStack account with App Automate access. +Use BrowserStack App Automate to run agent-device on hosted Android and iOS devices over WebDriver. You need a BrowserStack account with App Automate access and the `@agent-device/browserstack` plugin. + +## Install the plugin + +Install the plugin on the host that runs the daemon. + +```bash +agent-device plugins add @agent-device/browserstack@nightly-0.22 +``` + +If the CLI prints an install command in a missing-plugin error, use that command. + +The plugin is an optional npm package installed under `AGENT_DEVICE_HOME`. +After you add or update it, close open sessions and run `agent-device daemon stop` +with `--state-dir ` set to the state directory you use; the next device command loads the plugin. ## Set credentials and connect @@ -90,9 +104,11 @@ To drive BrowserStack only through MCP, see [Use a provider only through MCP](/d Configure the client directly when your Node.js process manages the BrowserStack credentials and selectors instead of a saved CLI connection profile: ```ts -import { createAgentDeviceClient } from 'agent-device'; +import { createAgentDeviceClient, ensureDaemon } from 'agent-device'; +await ensureDaemon(); const client = createAgentDeviceClient({ + session: 'checkout-android', leaseProvider: 'browserstack', providerOsVersion: '14.0', providerApp: 'bs://app-id', diff --git a/website/docs/docs/build-an-integration.md b/website/docs/docs/build-an-integration.md index 6118f6b90a..6c3bd6dc4c 100644 --- a/website/docs/docs/build-an-integration.md +++ b/website/docs/docs/build-an-integration.md @@ -35,7 +35,7 @@ Entry points for integrations: - `listAndroidAppsWithAdb(executor)` - `getAndroidAppStateWithAdb(executor)` - `runAdbShell(executor, words, options?)` / `runAdbExecOut(executor, words, options?)` - - `runAndroidShell(device, words, options?)` / `runAndroidExecOut(device, words, options?)` + - `runAndroidShell(device, words, host, options?)` / `runAndroidExecOut(device, words, host, options?)` - types: `AndroidAdbExecutor`, `AndroidAdbExecutorOptions`, `AndroidAdbProvider`, `AndroidKeyboardState`, `AndroidKeyboardDismissResult`, `AndroidPortReverseEndpoint` - `agent-device/batch` @@ -47,7 +47,7 @@ Entry points for integrations: - `buildBundleUrl(baseUrl, platform)` - `normalizeBaseUrl(baseUrl)` - `resolveRuntimeTransport(runtime)` - - `prepareMetroRuntime(options?)`, `reloadMetro(options?)`, `stopMetroTunnel(options)` + - `prepareMetroRuntime(options, host)`, `reloadMetro(options?)`, `stopMetroTunnel(options)` - types: `MetroBridgeDescriptor`, `MetroTunnelRequestMessage`, `MetroTunnelResponseMessage` - `agent-device/contracts` - `centerOfRect(rect)` @@ -74,17 +74,27 @@ Entry points for integrations: - `validateDownloadSourceUrl(url)` - types: `MaterializeInstallSource` - `agent-device/artifacts` - - `resolveAndroidArchivePackageName(archivePath)` -- `agent-device/limrun` - - `new LimrunRuntime(options)` - - `runtime.getDeviceSession(device)` - - types: `LimrunRuntimeOptions`, `LimrunDeviceSession`, `LimrunAndroidDeviceSession`, - `LimrunIosDeviceSession`, `LimrunIosCommandExecution` + - `resolveAndroidArchivePackageName(archivePath, host, signal?)` - `agent-device/plugins/webdriver` - experimental `WebDriverPluginOptions` for providers using the shared engine. - `agent-device/plugins` - experimental plugin contract: `AgentDevicePluginFactory` and `ProviderPluginHost`; see [provider plugins](./plugins.md). +## Migrate SDK hosts to 0.22 + +In 0.22, Android host ADB helpers, archive inspection, and Metro preparation require an explicit `{ env, cwd }` host. `resolveRemoteConfigProfile` requires `env`, and `createLocalArtifactAdapter` requires `cwd`. Capture these values in your application's entry point and pass the same host to its operations: + +```ts +import { resolveAndroidArchivePackageName } from 'agent-device/artifacts'; +import { createLocalArtifactAdapter } from 'agent-device/io'; + +const host = { env: { ...process.env }, cwd: process.cwd() }; +const artifacts = createLocalArtifactAdapter({ cwd: host.cwd }); +const packageName = await resolveAndroidArchivePackageName('./app.apk', host); +``` + +Use separate hosts for integrations with different environments or working directories. Pass `env: {}` when profile resolution should use only the file's settings. `startAgentDevice({ stateDir })` still captures a host when you omit `host`. CLI and MCP entry points continue to capture their process host. + ## Android ADB providers Use `agent-device/android-adb` when your bridge owns Android device access and you want @@ -112,7 +122,7 @@ begins with `shell` or `exec-out` and did not come from those builders is refuse `details.reason: 'unguarded-device-shell-argv'` instead of being dispatched. A bridge that composes its own device commands calls `runAdbShell(executor, words, options?)` or `runAdbExecOut(executor, words, options?)` from `agent-device/android-adb`, passing each value as its -own word; `runAndroidShell(device, words, options?)` and `runAndroidExecOut(device, words, options?)` +own word; `runAndroidShell(device, words, host, options?)` and `runAndroidExecOut(device, words, host, options?)` resolve the executor from a device instead. ```ts @@ -143,9 +153,10 @@ Full example from [`examples/sdk/batch-orchestration.ts`](https://github.com/cal import { prepareMetroRuntime, reloadMetro, stopMetroTunnel } from 'agent-device/metro'; import { resolveRemoteConfigProfile } from 'agent-device/remote-config'; +const host = { env: { ...process.env }, cwd: process.cwd() }; const remoteConfig = resolveRemoteConfigProfile({ configPath: './agent-device.remote.json', - cwd: process.cwd(), + ...host, }); const prepared = await prepareMetroRuntime({ @@ -159,7 +170,7 @@ const prepared = await prepareMetroRuntime({ leaseId: remoteConfig.profile.leaseId!, }, companionProfileKey: remoteConfig.resolvedPath, -}); +}, host); console.log(prepared.iosRuntime, prepared.androidRuntime); diff --git a/website/docs/docs/client-api.md b/website/docs/docs/client-api.md index 12d4a81e6c..4cd5b37611 100644 --- a/website/docs/docs/client-api.md +++ b/website/docs/docs/client-api.md @@ -32,7 +32,7 @@ Entry points for driving devices from Node.js: - `startAgentDevice(options)` - types: `AgentDeviceHost`, `StartAgentDeviceOptions` - `ensureDaemon(options?)` - - `createLocalArtifactAdapter(options?)` + - `createLocalArtifactAdapter({ cwd, rootDir?, tempDir? })` - `AppError`, `isAgentDeviceError(error)`, `normalizeAgentDeviceError(error)` - `isUnreadableCaptureContentError(error)`: true when an Android helper capture found no readable app content yet (`empty-helper-output`, `system-window-only`, `content-poor-app-window`), for @@ -47,7 +47,7 @@ Entry points for driving devices from Node.js: - types: `SnapshotNode`, `RawSnapshotNode`, `SnapshotState`, `Rect`, `Point` - types: `NormalizedError`, `AppErrorCode`, `KnownAppErrorCode`, `AppErrorDetails`, `ErrorCause` - `agent-device/io` - - `createLocalArtifactAdapter(options?)` + - `createLocalArtifactAdapter({ cwd, rootDir?, tempDir? })` - types: `ArtifactAdapter`, `ArtifactDescriptor`, `CreateTempFileOptions`, `FileInputRef`, `FileOutputRef`, `LocalArtifactAdapterOptions`, `OutputVisibility`, `ReserveOutputOptions`, `ReservedOutputFile`, `ResolveInputOptions`, `ResolvedInputFile`, `TemporaryFile` @@ -90,18 +90,11 @@ if ('cloudArtifacts' in result) { ## Daemon lifecycle -A client talks to one local daemon per state directory. `daemonLifecycle` says who owns that daemon. +Client calls attach to the local daemon for their state directory without starting, replacing or stopping it, including after a timeout. This includes `client.replay.run()` and `client.replay.test()`. Only CLI/MCP one-shot replay/test operations start and clean up a private daemon. A missing daemon reports `daemon-not-running`; an incompatible daemon reports `daemon-incompatible`. -Close an embedded runtime in its host process with the handle returned by `startAgentDevice()`. `agent-device daemon stop --state-dir ` refuses a live runtime with `error.details.reason: 'daemon-owner-embedded'` and a hint naming the host PID. It sends no request or signal. If the recorded host lifetime has provably exited, `daemon stop` retires its abandoned registration. A record with live unrecognized ownership is also refused, with `daemon-owner-unrecognized`. Without `--clean`, an unreadable `daemon.json` fails with `daemon-record-unreadable`. +To migrate from `daemonLifecycle: 'managed'`, remove that option and call `ensureDaemon({ stateDir })` with the same `stateDir` as the client before creating it, including clients used only for replay/test. To own the daemon in your process instead, use `startAgentDevice()` as shown below. CLI and MCP commands continue to ensure the local daemon when needed. -A `'managed'` client reuses a matching embedded runtime. Takeover, drain, and timeout recovery refuse a live embedded or unrecognized owner without a signal. A provably exited owner is retired so you can reuse the state directory. - -| Mode | What the client does with the daemon | -| --- | --- | -| `'managed'` (default) | Starts a missing daemon, replaces one that does not match the client, and retires an unresponsive one after a timeout. | -| `'attach'` | Connects to the running daemon. Never starts, replaces or stops one, even after a timeout. | - -`'managed'` stays the default until 0.22. Use `'attach'` when your code, or another process, owns the daemon, and call `ensureDaemon()` to start or replace it deliberately: +Close an embedded runtime in its host process with the handle returned by `startAgentDevice()`. `agent-device daemon stop --state-dir ` refuses a live embedded runtime with `daemon-owner-embedded`. If the recorded host lifetime has provably exited, it retires the abandoned registration. A record with live unrecognized ownership is also refused, with `daemon-owner-unrecognized`. ```ts import { createAgentDeviceClient, ensureDaemon } from 'agent-device'; @@ -112,7 +105,7 @@ await ensureDaemon({ stateDir, onStart: (reason, previous) => console.log(`started a daemon: ${reason}`, previous), }); -const client = createAgentDeviceClient({ stateDir, daemonLifecycle: 'attach' }); +const client = createAgentDeviceClient({ stateDir }); ``` `ensureDaemon()` starts a daemon when none runs. It replaces a daemon that does not match the client only if that daemon holds no work: no request in flight, no session, no repair session and no live lease. A resumable upload still streaming and a host human-control hold that names no lease are not counted, so a replacement can end them. Otherwise it fails and leaves the daemon alone. Two cases retire a daemon without that proof, because it cannot be asked: a registered daemon that answers nothing on any transport, and one that times out on the quiesce request and then fails repeated liveness probes. A daemon that accepted the quiesce request is never signaled while it drains: the call waits up to 60 s for it to exit and clear its registration. One still running after that fails repeated liveness probes and is force-retired when its process is provably a daemon. A daemon that still answers, or whose process cannot be proven to be a daemon, fails the call with `daemon-drain-timeout`; a force retirement that cannot be confirmed fails it with `daemon_retirement_unconfirmed`. It returns `{ stateDir, daemon, started }`; `daemon` holds the pid, version and code identity, and no credentials. `onStart` runs when the call started a daemon: `'incompatible'` when it replaced a daemon that agreed to leave, with that daemon as `previous`, and `'missing'` otherwise. A `'missing'` start that also has a `previous` replaced a registered daemon that answered nothing, or one that accepted the request to leave and was force-retired after outlasting its drain. @@ -121,15 +114,15 @@ These failures carry a typed `error.details.reason`: | Reason | Meaning | | --- | --- | -| `daemon-not-running` | An `'attach'` client found no daemon to connect to. Call `ensureDaemon()`. | -| `daemon-incompatible` | The running daemon does not match the client. `details.daemon` and `details.client` hold both identities. For an embedded runtime, close it in its host process. For a detached daemon, use `agent-device daemon stop --state-dir `. Then call `ensureDaemon()`. A daemon from a release that predates quiescing cannot be asked to leave, so `ensureDaemon()` reports it the same way. | +| `daemon-not-running` | A client found no daemon to connect to. Call `ensureDaemon({ stateDir })` for the client's state directory. | +| `daemon-incompatible` | The running daemon does not match the client. `details.daemon` and `details.client` hold both identities. For an embedded runtime, close it in its host process. For a detached daemon, use `agent-device daemon stop --state-dir `. Then call `ensureDaemon({ stateDir })` for that directory. A daemon from a release that predates quiescing cannot be asked to leave, so `ensureDaemon()` reports it the same way. | | `daemon-busy` | `ensureDaemon()` found an incompatible daemon that still holds work. `details` counts `inFlightRequests`, `sessions`, `repairSessions` and `leases`. Wait for them to end and retry. | | `daemon-drain-timeout` | A daemon accepted the request to leave but was still running 60 s later and could not be force-retired, either because it still answers or because its process cannot be proven to be a detached daemon. It was not signaled. Retry once it has exited, or stop it with `agent-device daemon stop --state-dir `. | | `daemon-owner-embedded` | A live host process owns the daemon on `stateDir`, so this client neither replaced it nor retired it, and signaled nothing. A daemon that matches the client is still usable. Close the runtime in its host process with its `close()` handle. | | `daemon-owner-unrecognized` | The record on `stateDir` states an owner this version cannot read, so this client replaced nothing and signaled nothing. Update agent-device if the record comes from a newer build. Otherwise check what owns that process: a host that started it closes it with its own close, and otherwise remove `daemon.json` once that process is gone. | | `daemon-binding-mismatch` | A client pinned to one daemon instance reached another one instead. `details.mismatch` says which: `replaced`, `absent`, or `unaddressable`. Nothing was dispatched, started, or signaled. Take a fresh config from the host that owns the daemon, or start a host of your own. | -`ensureDaemon()` only ever manages the local daemon on `stateDir`. A client with `daemonBaseUrl` never starts or stops a local daemon in either mode, and `daemonLifecycle` does not change `daemonTransport` or `daemonServerMode`. +`ensureDaemon()` only ever manages the local daemon on `stateDir`. A client with `daemonBaseUrl` connects to the remote daemon and does not start or stop a local daemon. ## Running the daemon inside your process @@ -170,6 +163,7 @@ You drive Limrun, BrowserStack, AWS Device Farm, and TestMu AI devices with the import { createAgentDeviceClient } from 'agent-device'; const client = createAgentDeviceClient({ + session: 'checkout-android', leaseProvider: 'browserstack', providerOsVersion: '14.0', providerApp: 'bs://app-id', @@ -241,7 +235,7 @@ const controller = new AbortController(); await client.interactions.press({ ref: '@e12', signal: controller.signal }); ``` -With the built-in transport, a signal that is already aborted rejects the call without sending anything (`error.details.dispatched: 'no'`). Aborting while the request is in flight closes that request's connection, the daemon marks the request canceled, and the promise rejects with the typed canceled-request error (`error.details.reason: 'request_canceled'`, `error.details.dispatched: 'unknown'`). A custom transport receives the signal on its context and may cancel differently. The daemon and the session stay alive for other requests. On iOS, a command that already reached the device keeps running there, so the daemon holds the session while the device reports it running. Your promise still rejects at once. The hold ends when the device reports the command finished, when the command's own timeout runs out, or when the device cannot confirm the command (it never received it, or the status check fails). Only in the first case is the canceled work known to be over before the session's next request starts. An abort is not a timeout: it never triggers the runner cleanup or daemon reset that a timeout does. Cancellation covers only the daemon request, so a response-artifact download already underway is not stopped, and a canceled one-shot replay still runs the existing cleanup that can tear down a daemon this client started. +With the built-in transport, a signal that is already aborted rejects the call without sending anything (`error.details.dispatched: 'no'`). Aborting while the request is in flight closes that request's connection, the daemon marks the request canceled, and the promise rejects with the typed canceled-request error (`error.details.reason: 'request_canceled'`, `error.details.dispatched: 'unknown'`). A custom transport receives the signal on its context and may cancel differently. The daemon and the session stay alive for other requests. On iOS, a command that already reached the device keeps running there, so the daemon holds the session while the device reports it running. Your promise still rejects at once. The hold ends when the device reports the command finished, when the command's own timeout runs out, or when the device cannot confirm the command (it never received it, or the status check fails). Only in the first case is the canceled work known to be over before the session's next request starts. An abort is not a timeout: it never triggers the runner cleanup or daemon reset that a timeout does. Cancellation covers only the daemon request, so a response-artifact download already underway is not stopped. ```ts await client.command.wait({ @@ -353,7 +347,7 @@ Domain client methods: - `client.sessions.list()`, `stateDir()`, `close()`, `saveScript()`, `artifacts()` - `client.apps.install()`, `reinstall()`, `uninstall()`, `installFromSource()`, `list()`, `open()`, `close()`, `push()`, `triggerEvent()` - `client.materializations.release()` -- `client.leases.allocate()`, `heartbeat()`, `release()`. Pass `retainOnClose: true` to `allocate()` when you release the lease yourself; session `close` then leaves it active until `release()`, expiry, or graceful daemon shutdown. The returned lease has `retainOnClose: true` only when the daemon honored it. Keep heartbeating a retained lease between sessions: it expires after its `ttlMs` like any other lease. On iOS simulators, a healthy idle XCTest runner can stay available between those sessions. Releasing or expiring the lease stops its runner unless a session outside the lease has taken over the device. Pass `leaseId` (16 to 128 hex characters) to `allocate()` to name a new lease with an id the daemon has never issued, or to get back your live lease with that id when you retry with the same tenant, run, client, lease backend, and provider (and no device, or the leased one), then use the returned `leaseId`: a run that already holds a lease gets that one back, and an older daemon mints its own. `allocate()` also tells you which of those you got, on the returned lease's `created`: `true` when your request created that lease, `false` when it was already there, and omitted on `heartbeat()` or when an older daemon does not support ownership evidence. The CLI releases an allocate response it discards before recording (a spec refusal, identity refusal, or keyless replacement), unless `created` is `false`. After binding, rollback on a later preparation failure requires `created:true`. Against an older daemon that omits `created`, refused or replaced leases are released, but a bound, unrecorded lease remains until expiry if preparation fails. `allocate()` with a `leaseProvider` the daemon has no runtime for fails with `UNSUPPORTED_OPERATION`, reason `provider-not-registered`, and `details.registeredProviders`; no lease is recorded. Leases with no provider, `proxy`, or `cloud` need no runtime. +- `client.leases.allocate()`, `heartbeat()`, `release()`. A client on a lease from a lease provider must name its session, or the daemon refuses it with reason `REMOTE_SESSION_REQUIRED`. Pass `retainOnClose: true` to `allocate()` when you release the lease yourself; session `close` then leaves it active until `release()`, expiry, or graceful daemon shutdown. The returned lease has `retainOnClose: true` only when the daemon honored it. Keep heartbeating a retained lease between sessions: it expires after its `ttlMs` like any other lease. On iOS simulators, a healthy idle XCTest runner can stay available between those sessions. Releasing or expiring the lease stops its runner unless a session outside the lease has taken over the device. Pass `leaseId` (16 to 128 hex characters) to `allocate()` to name a new lease with an id the daemon has never issued, or to get back your live lease with that id when you retry with the same tenant, run, client, lease backend, and provider (and no device, or the leased one), then use the returned `leaseId`: a run that already holds a lease gets that one back, and an older daemon mints its own. `allocate()` also tells you which of those you got, on the returned lease's `created`: `true` when your request created that lease, `false` when it was already there, and omitted on `heartbeat()` or when an older daemon does not support ownership evidence. The CLI releases an allocate response it discards before recording (a spec refusal, identity refusal, or keyless replacement), unless `created` is `false`. After binding, rollback on a later preparation failure requires `created:true`. Against an older daemon that omits `created`, refused or replaced leases are released, but a bound, unrecorded lease remains until expiry if preparation fails. `allocate()` with a `leaseProvider` the daemon has no runtime for fails with `UNSUPPORTED_OPERATION`, reason `provider-not-registered`, and `details.registeredProviders`; no lease is recorded. Leases with no provider, `proxy`, or `cloud` need no runtime. - `client.metro.prepare()`, `reload()` - `client.capture.snapshot()`, `screenshot()`, `diff()` - `client.interactions.gesture()`, `click()`, `press()`, `longPress()`, `swipe()`, `pan()`, `drag()`, `fling()`, `swipeGesture()`, `focus()`, `type()`, `fill()`, `scroll()`, `pinch()`, `rotateGesture()`, `transformGesture()`, `tapGesture()`, `get()`, `is()`, `find()` diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 90dac45f0a..2a8dd7588a 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -107,6 +107,7 @@ Open apps and links: - Android React Native: `open --relaunch` needs an installed package name. Install or reinstall the APK first; `open --relaunch` is rejected. For Metro-backed JS changes, run `metro reload` before reaching for `open --relaunch`. - Android (adb): an intent target such as `open settings` records the package that opened as `appBundleId`. `open settings --relaunch` stops and restarts that app. If the intent matches more than one activity, `--relaunch` fails. - Android (ADB): `close` force-stops the app, then checks for 2 seconds that it has left the foreground, waits up to 10 seconds for the processes it killed to exit, and checks for 2 more that no new process started. If a check window ends first, `close` fails with `details.reason: android-app-close-timeout` and `details.phase` set to `foreground`, `exit`, or `process`; a process that survives the force-stop fails with `exit`, and apps Android restarts at once, such as the launcher, fail with `process`. `open --relaunch` runs the same checks but accepts a new process once the killed ones exit, because Android can restart an app at once for a background client, such as Settings on Android 17. When `pidof` cannot list the app's processes, `close` fails with `details.reason: android-process-probe-unavailable`; if that happens before the force-stop, the app keeps running. +- To diagnose an Android foreground-close timeout (`details.phase: foreground`), inspect `details.foregroundObservations` and `details.initialProcessCount` in the JSON error. The observations retain at most the last five probes: `startMs` and `endMs` are milliseconds from the start of the foreground check, `remainingMs` is the budget left when the probe ends, and `result` is `target`, `other`, or `unknown`. The process count is read before force-stop. In the [session request log](/docs/sessions#find-a-sessions-logs-and-artifacts), the `android_close_foreground_fence` diagnostic records this history as `data.observations` with `data.initialProcessCount`. If a foreground probe throws, that diagnostic also retains the history with an `error` result for the failed probe; the command reports the probe failure. - When `close` cannot confirm its cleanup on a session that holds a device claim, it fails and keeps the session and its claim, so the device is not handed on unconfirmed. Run `close` again with the same options to retry the cleanup and release the device, leaving out `--save-script` once the first attempt has published the script. Only `close`, or a successful `open`, is supported on the kept session: other commands work, but the session stays marked, so an idle daemon can still shut it down. If nobody retries, the kept session does not keep the daemon alive: when the daemon has been idle for its idle timeout and shuts down, its shutdown retries the cleanup, and a claim it still cannot confirm goes stale instead of being released. Embedded runtimes and `AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0` never shut down for idleness, so there a retried `close` is the only release. - If `open --relaunch` leaves an existing session's device effects unconfirmed, the session and claim remain available for `close`, but idle shutdown can retry cleanup and leave an unconfirmed claim stale; embedded runtimes and `AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0` do not shut down for idleness, so use `close` to release the claim. diff --git a/website/docs/docs/device-clouds.md b/website/docs/docs/device-clouds.md index 99566acfae..5e10af18dd 100644 --- a/website/docs/docs/device-clouds.md +++ b/website/docs/docs/device-clouds.md @@ -5,8 +5,8 @@ description: Choose a hosted device provider for agent and CI workflows. Use a device cloud or farm when an agent needs to drive a hosted mobile device without an interactive login. Pick the provider whose account and devices you use: -- [BrowserStack](/docs/browserstack): Android and iOS App Automate sessions over WebDriver. -- [AWS Device Farm](/docs/aws-device-farm): Android and iOS remote-access sessions through AWS. +- [BrowserStack](/docs/browserstack): Android and iOS App Automate sessions over WebDriver. Install the `@agent-device/browserstack` plugin first. +- [AWS Device Farm](/docs/aws-device-farm): Android and iOS remote-access sessions through AWS. Install the `@agent-device/aws-device-farm` plugin first. - [TestMu AI](/docs/testmu): Android emulator, iOS simulator, and real-device sessions over WebDriver. - [Limrun](/docs/limrun): direct iOS simulator and Android emulator instances. - [Revyl](/docs/revyl): iOS simulators and Android emulators rented from Revyl's execution API. @@ -16,7 +16,7 @@ Use a device cloud or farm when an agent needs to drive a hosted mobile device w | | BrowserStack | AWS Device Farm | TestMu AI | Limrun | Revyl | | --- | --- | --- | --- | --- | --- | | Devices | Android and iOS real devices | Android and iOS real devices | Android emulators and iOS simulators by default; real devices with `--provider-device-type real` | Android emulators and iOS simulators | Android emulators and iOS simulators | -| Ships as | Built in | Built in; needs the AWS CLI | The `@agent-device/testmu` plugin | Built in | The `@agent-device/revyl` plugin | +| Ships as | The `@agent-device/browserstack` plugin | The `@agent-device/aws-device-farm` plugin; needs the AWS CLI | The `@agent-device/testmu` plugin | Built in | The `@agent-device/revyl` plugin | | Credentials | `BROWSERSTACK_USERNAME`, `BROWSERSTACK_ACCESS_KEY` | The AWS CLI credential chain, such as `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, `AWS_REGION` | `LT_USERNAME`, `LT_ACCESS_KEY` | `LIMRUN_API_KEY` (optional `LIMRUN_REGION`), or `LIM_*_INSTANCE_*` for an existing instance | `REVYL_API_KEY` (optional `REVYL_API_URL` for another Revyl backend) | | Device allocated on | `open` | `open` | `open` | First device command, such as `install` or `open` | First device command, such as `open` | | App source | `--provider-app`: `bs://` reference, HTTP(S) URL, or local path | `--aws-app-arn` upload ARN; no install after allocation | `--provider-app`: `lt://` reference, HTTP(S) URL, or local path | `install `, or `open ` for an uploaded asset | `--provider-app`: a public HTTPS URL only, installed when the device starts | diff --git a/website/docs/docs/eve.md b/website/docs/docs/eve.md index 890341c9b6..712a539ff6 100644 --- a/website/docs/docs/eve.md +++ b/website/docs/docs/eve.md @@ -15,7 +15,7 @@ pnpm add agent-device Add `agent/tools/agent_device.ts`: ```ts -import { createAgentDeviceClient } from 'agent-device'; +import { createAgentDeviceClient, ensureDaemon } from 'agent-device'; import { defineTool } from 'eve/tools'; import { z } from 'zod'; @@ -44,6 +44,7 @@ export default defineTool({ }), ]), async execute(input) { + await ensureDaemon(); switch (input.action) { case 'open': return await client.apps.open({ app: input.app, platform: input.platform }); diff --git a/website/docs/docs/installation.md b/website/docs/docs/installation.md index bd9afb69dc..e2cf97a116 100644 --- a/website/docs/docs/installation.md +++ b/website/docs/docs/installation.md @@ -24,7 +24,7 @@ Install `agent-device` on the machine where your coding agent runs terminal comm ## Global install ```bash -npm install -g agent-device@latest +npm install -g agent-device@nightly-0.22 agent-device doctor agent-device --version agent-device help @@ -46,33 +46,22 @@ For Cursor, Codex, Claude Code, Windsurf, Cline, Goose, skills, and project rule Interactive CLI runs periodically check npm for a newer `agent-device` release in the background. When one is available, the CLI suggests reinstalling globally: ```bash -npm install -g agent-device@latest +npm install -g agent-device@nightly-0.22 agent-device doctor agent-device --version ``` Set `AGENT_DEVICE_NO_UPDATE_NOTIFIER=1` to disable the notice. -## Nightly builds - -Nightly builds publish `main` after its CI passes, at most once per UTC day: - -```bash -npm install -g agent-device@nightly -``` - -A nightly install's update notice recommends a newer nightly when an update check finds one. To -return to stable releases, install `agent-device@latest`. - ## Without installing ```bash -npx agent-device --version -npx agent-device help workflow -npx agent-device open Settings --platform ios +npx agent-device@nightly-0.22 --version +npx agent-device@nightly-0.22 help workflow +npx agent-device@nightly-0.22 open Settings --platform ios ``` -One-off `npx` use is fine for you and for scripts that intentionally fetch from npm. For agents, use a global install, a project-local install, or a version pinned by you or your project config, so repeated commands resolve to a known CLI. Don't let agents choose a version or run `npx -y agent-device@latest` unless you've decided to trust whatever npm serves. +One-off `npx` use is fine for you and for scripts that intentionally fetch from npm. For agents, use a global install, a project-local install, or a version pinned by you or your project config, so repeated commands resolve to a known CLI. ## Vega OS TV prerequisites diff --git a/website/docs/docs/limrun.md b/website/docs/docs/limrun.md index 3c93401ab5..5da589edd8 100644 --- a/website/docs/docs/limrun.md +++ b/website/docs/docs/limrun.md @@ -63,11 +63,11 @@ On an attached Android instance, agent-device does not replace an existing port If your shell's account variables, or its instance variables for the platform you lease, differ from the ones the daemon started with, the first `install` or `open` refuses before it creates or attaches to an instance. See [Change credentials while the daemon runs](/docs/device-clouds#change-credentials-while-the-daemon-runs). -`install` and `reinstall` sync local app files directly to the instance. An attached iOS instance needs its URL and token. An attached Android instance also needs `LIM_ANDROID_INSTANCE_ADB_URL` to connect the provider; the app upload itself uses HTTP. `apps` before the first `open` needs `LIMRUN_API_KEY` to list stored assets. After `open`, `apps` lists the apps installed on the instance without the key. From the Node.js runtime, `getDeviceSession(device).installRemoteApp(url)` installs from a signed asset URL without the API key. +`install` and `reinstall` sync local app files directly to the instance. An attached iOS instance needs its URL and token. An attached Android instance also needs `LIM_ANDROID_INSTANCE_ADB_URL` to connect the provider; the app upload itself uses HTTP. `apps` before the first `open` needs `LIMRUN_API_KEY` to list stored assets. After `open`, `apps` lists the apps installed on the instance without the key. For a signed asset URL, use `install-from-source ` in the active session. This path does not need `LIMRUN_API_KEY`. ## Keep idle sessions alive -Limrun ends an instance after its inactivity timeout, which an idle session can reach while a model thinks between steps. Set `LIMRUN_KEEP_ALIVE=1` (or `true`) to ping the instance every 30 seconds while a session is open. Keep-alive is off by default. In the Node.js runtime, pass `keepAlive: true`. +Limrun ends an instance after its inactivity timeout, which an idle session can reach while a model thinks between steps. Set `LIMRUN_KEEP_ALIVE=1` (or `true`) to ping the instance every 30 seconds while a session is open. Keep-alive is off by default. Two timers can end an idle Limrun session. @@ -78,7 +78,7 @@ Two timers can end an idle Limrun session. ## Run a session from the CLI -A new Limrun instance does not contain your app. Run `install ` before `open`. `install` allocates the instance when needed, so you do not need to run `devices` first. +A new Limrun instance does not contain your app. Run `install ` before `open`. `install` allocates the instance when needed, so you do not need to run `devices` first. ```bash export LIMRUN_API_KEY=... @@ -119,7 +119,7 @@ On Android, agent-device connects to Limrun over an ADB tunnel. Snapshots use th Use the same snapshot, selector, text-entry, gesture, navigation, clipboard, and alert commands as on a local iOS simulator. Limrun iOS uses the agent-device XCTest runner. The runner reads snapshots with the same accessibility reader as a local iOS simulator, so snapshot output, selectors, and refs match local runs. When that reader cannot serve the screen, for example while a system sign-in sheet is open, the snapshot uses XCTest instead and says so in a warning. `fill` replaces text and `type` appends it; both support `--delay-ms`. -Use a stable agent-device release. It downloads and starts the matching runner automatically. You do not need local Xcode or any runner network configuration. Stop Appium or other XCTest sessions on the simulator before you start, because only one XCTest run can use it at a time. Limrun limits each XCTest run to one hour; close and reopen your session when it reaches that limit. +Stop Appium or other XCTest sessions on the simulator before you start, because only one XCTest run can use it at a time. Limrun limits each XCTest run to one hour; close and reopen your session when it reaches that limit. If startup fails with `limrun_xctest_slot_occupied`, stop the agent-device or Appium session that owns the simulator and wait for its XCTest run to end. If that client has exited and the slot remains occupied, recreate the Limrun instance. If a snapshot fails with `limrun_runner_snapshot_unavailable`, close and reopen your agent-device session. Recreate the instance if captures still fail. Do not reuse snapshot references after a failed capture. @@ -127,7 +127,7 @@ Open your app before taking a snapshot. Snapshots target the app you opened in t `install` leaves your app stopped. Use `open` to launch it. To change launch arguments on an app that is already running, use `open --relaunch --launch-args`. Screenshots download as lossless PNG files, and recording downloads the finished MP4 when you stop it. Push notifications use the same command and payload format as local simulators. -If you use a nightly or unpublished agent-device build, obtain a matching packaged iOS runner from the build's maintainer. Set `AGENT_DEVICE_LIMRUN_IOS_RUNNER_APP` to the extracted `.app` path before starting agent-device. The runner must be built with Xcode 27, because Limrun runs XCTest with Xcode 27. agent-device refuses a runner built with an older Xcode. If the daemon is already running, stop it with `agent-device daemon stop` using the same `--state-dir`, then reconnect. +To supply the packaged iOS runner from your build, set `AGENT_DEVICE_LIMRUN_IOS_RUNNER_APP` to the extracted `.app` path before starting agent-device. The runner must be built with Xcode 27, because Limrun runs XCTest with Xcode 27. agent-device refuses a runner built with an older Xcode. If the daemon is already running, stop it with `agent-device daemon stop` using the same `--state-dir`, then reconnect. ## Connect an iOS app to Metro @@ -204,25 +204,47 @@ The count includes these kinds: `request-failed` (the host didn't resolve, refus Now and then, a request skips the capture: it is missing from the HAR and from the failure count. If a request you expect is missing, repeat it. If the HAR stays empty while the app makes requests, run `close` and `disconnect`, then connect again. -## Embed the Node.js runtime +## Drive Limrun from a Node.js integration -A Node.js bridge, such as agent-device-cloud, can embed agent-device's Limrun runtime: +The `agent-device/limrun` SDK subpath was removed in 0.22. A Node.js bridge, such as agent-device-cloud, drives Limrun through the typed client against the daemon that hosts the provider. -```ts -import { LimrunRuntime } from 'agent-device/limrun'; +### Allocate an iOS instance + +Start the daemon with `LIMRUN_API_KEY`. Allocate a lease and install an iOS simulator build before opening the app. If you attach to an instance that already has the app, skip installation. -const apiKey = process.env.LIMRUN_API_KEY; -if (!apiKey) throw new Error('LIMRUN_API_KEY is required'); +```ts +import { createAgentDeviceClient, ensureDaemon } from 'agent-device'; -const runtime = new LimrunRuntime({ - apiKey, - region: process.env.LIMRUN_REGION, -}); +await ensureDaemon(); +const scope = { + session: 'checkout-ios', + tenant: 'limrun', + runId: process.env.GITHUB_RUN_ID ?? 'local-run', + leaseBackend: 'ios-instance', + leaseProvider: 'limrun', +} as const; +const control = createAgentDeviceClient(scope); +const lease = await control.leases.allocate({ ...scope, platform: 'ios', retainOnClose: true }); +try { + const client = createAgentDeviceClient({ + ...scope, + leaseId: lease.leaseId, + sessionIsolation: 'tenant', + }); + await client.apps.install({ + app: 'com.example.app', + appPath: './build/Build/Products/Debug-iphonesimulator/Example.app', + platform: 'ios', + }); + await client.apps.open({ app: 'com.example.app', platform: 'ios' }); +} finally { + await control.leases.release({ ...scope, leaseId: lease.leaseId }); +} ``` -To drive existing instances, pass `instances: { ios: { apiUrl, token } }` (Android also takes `adbUrl`), with or without `apiKey`. The runtime never creates or deletes instances for a platform listed there. +### Attach to a harness-owned instance -A provider that reaches a harness-owned instance through the Node.js client allocates a Limrun lease in `acquire` and releases that same lease in `release`. Put the returned `lease.leaseId` on the client scope, and pass that same id to `leases.release`. Start the daemon with the instance URL and token (`LIM_IOS_INSTANCE_URL` and `LIM_IOS_INSTANCE_TOKEN`). `leases.allocate` attaches to that instance. `leases.release` returns `{ released, provider }`. Neither call creates or deletes the instance. Allocate with `retainOnClose: true` because the provider releases the lease itself: without it, a session `close` before `release` ends the lease and `leases.release` returns `released: false`. A retained lease still expires after its `ttlMs`, so keep heartbeating it between sessions. On iOS, a retained lease can reuse a healthy runner between sessions in the same daemon. Releasing the lease or stopping the daemon stops the runner. A new daemon cannot adopt it. +A provider that reaches a harness-owned instance allocates a Limrun lease in `acquire` and releases that same lease in `release`. Put the returned `lease.leaseId` on the client scope, and pass that same id to `leases.release`. Start the daemon with the instance URL and token (`LIM_IOS_INSTANCE_URL` and `LIM_IOS_INSTANCE_TOKEN`). `leases.allocate` attaches to that instance. `leases.release` returns `{ released, provider }`. Neither call creates or deletes the instance. Allocate with `retainOnClose: true` because the provider releases the lease itself: without it, a session `close` before `release` ends the lease and `leases.release` returns `released: false`. A retained lease still expires after its `ttlMs`, so keep heartbeating it between sessions. On iOS, a retained lease can reuse a healthy runner between sessions in the same daemon. Releasing the lease or stopping the daemon stops the runner. A new daemon cannot adopt it. ```ts import { createAgentDeviceClient } from 'agent-device'; @@ -247,12 +269,12 @@ const provider = { }; }, release: async (lease: { id: string }) => { - await createAgentDeviceClient({}).leases.release({ ...scope, leaseId: lease.id }); + await createAgentDeviceClient({ session: `lease-${lease.id}` }).leases.release({ ...scope, leaseId: lease.id }); }, }; ``` -After allocating a lease, call `runtime.getDeviceSession(device)` to get the allocated device's capabilities: app inventory, foreground state where Limrun exposes it, key input, bounded log reads, recording, remote asset installation, and the interactor. On Android it also exposes agent-device's `AndroidAdbProvider` for helpers and reversible port forwarding. On iOS it exposes a typed `simctl` execution handle so your bridge can own runner lifecycle and launch policy. The runtime does not expose raw Limrun clients. +After allocating a lease, use the client commands for that session. App inventory, foreground state, key input, log reads, recording, remote asset installation, and interaction all run through the same typed client methods as on a local device. The client does not expose raw Limrun clients. ## Record the screen diff --git a/website/docs/docs/plugins.md b/website/docs/docs/plugins.md index d98f2cd4d1..1c0b08cbc8 100644 --- a/website/docs/docs/plugins.md +++ b/website/docs/docs/plugins.md @@ -1,8 +1,8 @@ --- -title: Provider plugins +title: Plugins --- -Provider plugins add device providers that agent-device does not bundle, such as [TestMu AI](/docs/testmu), [LG webOS](/docs/webos), and [Samsung Tizen](/docs/tizen). Installing one requires npm on your host: +Provider plugins add device providers that agent-device does not bundle, such as [BrowserStack](/docs/browserstack), [AWS Device Farm](/docs/aws-device-farm), [TestMu AI](/docs/testmu), [LG webOS](/docs/webos), and [Samsung Tizen](/docs/tizen). Installing one requires npm on your host: ```bash agent-device plugins add @example/agent-device-provider @@ -13,9 +13,9 @@ agent-device plugins remove @example/agent-device-provider `agent-device help connect` and `agent-device help remote` identify known optional providers as `plugin, install separately` and show their installation commands, even before you install them. -For example, TestMu AI requires `agent-device plugins add @agent-device/testmu`. +Use the install command shown for your provider. TestMu AI uses `agent-device plugins add @agent-device/testmu`. -If you run `agent-device connect testmu` without its plugin, the error gives that installation +If you run `agent-device connect browserstack`, `agent-device connect aws-device-farm`, or `agent-device connect testmu` without its plugin, the error gives that installation command and tells you to retry your original command. With `--json`, the error has `details.reason: plugin-not-installed`, `details.package`, and `details.installCommand`. If the plugin is selected but unavailable, the reason is `plugin-unavailable`; run @@ -29,9 +29,25 @@ Install only packages you trust: plugin factories run with the daemon's host per A failed install keeps the previous selection. A running daemon keeps the plugin set and files it started with, including removed installations. To apply changes, close sessions and run `agent-device daemon stop` with the matching `--state-dir`; the next device command uses the new set. Use separate state directories for different plugin homes. +## Install replay and test support + +Install the native replay plugin on the daemon host. + +```bash +agent-device plugins add @agent-device/replay +``` + +Finish your sessions and restart that daemon, then retry the original invocation with all its arguments. Native `.ad` scripts keep their syntax, variables, target verification, resume and repair behavior. Ordinary script recording stays in core. + +A remote daemon needs its own installation. A local plugin store does not make an engine available remotely. An embedded host imports the factory from `@agent-device/replay/agent-device` and supplies `plugins: [replay()]` to `startAgentDevice`. Supplied plugins are authoritative; the embedded runtime does not read the store. + +Maestro YAML replay requires `@agent-device/maestro` on both client and daemon hosts. Maestro suites also need `@agent-device/replay` on the daemon host. `replay export` needs the Maestro plugin on the client only. + +A missing installation returns `plugin-not-installed` with the package and installation command. Selected package failures keep `plugin_load_failed`, `invalid_plugin`, `incompatible_plugin` or `plugin_setup_failed`; repair or update that selected package. `daemon-plugin-set-stale` requires restarting the daemon after sessions finish. For an embedded daemon, its host closes and recreates the runtime. No recovery installs packages or ends sessions automatically. + ## See which providers are registered -`agent-device daemon status` lists every provider the running daemon registered: the bundled ones (BrowserStack, AWS Device Farm, and Limrun when it is configured), then installed plugins. With `--json`, each entry has: +`agent-device daemon status` lists every provider the running daemon registered: bundled Limrun when configured, then installed plugins such as BrowserStack and AWS Device Farm. With `--json`, each entry has: ```json { @@ -56,6 +72,12 @@ When two plugins claim the same provider, the first one wins: bundled providers, A lease that names a provider this daemon has no runtime for refuses with `UNSUPPORTED_OPERATION` and reason `provider-not-registered`, before any lease is recorded. The error lists the registered providers and, as `failedPlugins`, any plugin that failed to register for that provider (or failed before its provider was known); restart the daemon with the provider's plugin installed. Leases with no provider, `proxy`, and `cloud` need no provider runtime. +## Install Maestro support + +`agent-device plugins add @agent-device/maestro` installs the optional Maestro engine for `replay --maestro`, `test --maestro`, and `replay export`. [Run Maestro flows](/docs/run-maestro-flows) explains client and daemon installation. `help maestro` remains available without the plugin. + +Replay backends appear in plugin inventories with `backend` instead of `provider`. A daemon keeps its plugin set until it stops. Installing a package on a client does not change a remote or embedded daemon's plugin set. + ## Create a plugin The interface is experimental. A plugin package exports a factory at `./agent-device`. Use `agent-device` as a development dependency; plugins import only types from it. @@ -132,14 +154,60 @@ connection: { ### Package for installation -Bundle the plugin implementation and ship ready-to-run ESM: installation disables lifecycle scripts. Bundle shared helpers with the plugin; `AppError` carries a shared brand so the host preserves its code and details across package copies. Import types with `import type` to keep them out of the runtime dependency graph. +Bundle the plugin implementation and ship ready-to-run ESM: installation disables lifecycle scripts. Bundle shared helpers with the plugin; `AppError` carries a shared brand so the host preserves its code and details across package copies. Import types with `import type` to keep them out of the runtime dependency graph. A published plugin package names `./agent-device` in its `exports`: that is the subpath the host's loader and the publish checks read, so don't ship a plugin only through the root export or `main`. -## Version 1 plugins +## Migrating from a version 1 manifest -Packages that declare `agentDevicePlugin` with `apiVersion: 1` in `package.json` keep working. The host reads the manifest's `provider`, `entry`, `connection`, and `credentialVariables` before running any plugin code, then calls the default export with `ProviderPluginHost` and registers the `{ runtime, platformModule }` or `{ webDriver, connection? }` it returns. Support for this form ends in a later release; move to the `./agent-device` factory. +Earlier plugin packages declared `agentDevicePlugin` with `apiVersion: 1` in `package.json`, and the host read `provider`, `entry`, `connection`, and `credentialVariables` from it before loading any code. That form is no longer supported: a store package is loaded only through its exports, and everything it declares comes from the object its factory returns. -```json -{"agentDevicePlugin": {"apiVersion": 1, "provider": "example", "entry": "./dist/plugin.mjs"}} +To move a package: + +1. Export the factory from `./agent-device` instead of naming an entry file in the manifest, and drop `agentDevicePlugin` from `package.json`. +2. Return the manifest's values from the factory: `provider` stays `provider`, `credentialVariables` becomes `credentials: { variables: [...] }`, and the manifest's `connection` becomes `connection.capabilities`, with the `resolve` and `verify` the v1 entry returned for `connection` moved into that same `connection` object next to `setup`. +3. Return `apiVersion: 2` and keep the default export a function; the host calls it with the selection's options and `setup` receives the `ProviderPluginHost` the v1 entry used to receive first. + +```diff +-{"agentDevicePlugin": {"apiVersion": 1, "provider": "example", "entry": "./dist/plugin.mjs"}} ++{"exports": {"./agent-device": { "import": "./dist/plugin.mjs" }}} +``` + +```diff +-export default async (host) => ({ runtime, platformModule }); ++export default () => ({ ++ apiVersion: 2, ++ provider: 'example', ++ credentials: { variables: ['EXAMPLE_API_KEY'] }, ++ setup: async (host) => ({ runtime, platformModule }), ++}); +``` + +A package that still ships the old manifest loads when it also exports `./agent-device`, and the manifest is then ignored. A plugin object with an `apiVersion` other than 2 is listed as `failed` with `incompatible_plugin`, and a default export that is not a plugin factory with `invalid_plugin`; the daemon starts without either. + +## Create a replay backend plugin + +A replay engine uses the same managed `./agent-device` factory entry and `apiVersion: 2`. Return a `ReplayEnginePlugin` from the type-only `agent-device/plugins` contract with `kind: 'replay-backend'`, a `backend` id, and `setup(host)`. Keep setup engine-free; `create` may asynchronously import the engine when a replay capability is selected. + +For a format backend such as `maestro`, setup returns `{ replayBackend: { create(host) }, dispose? }`. The backend implements source collection, source inspection, replay execution, and export. Its `ReplayBackendHost` supplies dispatch-related services and request cancellation; each replay command supplies its host environment, session access, and `invoke`. + +For the native `ad` backend, setup returns `{ execution: { create() }, dispose? }`. The object returned by `create()` implements `inspectAdReplay`, `runAdReplay`, and `runReplayTestSuite`. Return only the factory for your backend: the host rejects a native setup that provides `replayBackend`, or a format setup that provides `execution`. + +The daemon owns sessions, policy, selector/ref authority, and device cleanup. `dispose` runs once after requests drain. Client-side source collection and export dispose their scoped plugin registry when the operation ends. + + +## Install a local plugin artifact + +On each host that needs the plugin, install its `.tgz` file. Use `./` or `../` for a relative path, or provide an absolute path: + +```sh +agent-device plugins add ./provider-plugin.tgz --json +agent-device plugins list --json ``` -A package that exports `./agent-device` is loaded as a version 2 plugin even if it also keeps the manifest, so one package can serve both old and new hosts. +The archive must contain an npm package with a name, an exact version, and an `./agent-device` export. Installation does not run package lifecycle scripts or load the plugin factory. The list command loads the factory to check compatibility. The installation returns an `artifact` receipt with compatibility marked `unchecked`. Run `plugins list --json` for the checked `plugins` inventory, including the artifact's installation ID and SHA-512 integrity. If the package is already selected, remove it before adding the artifact. `plugins update` does not update artifacts from the registry; remove the selection and add the replacement artifact. Finish active sessions and restart the daemon after changing the selection. + +A Node.js host can call the same manager with an explicit environment and working directory: + +```js +import { addPluginArtifact } from 'agent-device/plugins'; +await addPluginArtifact('./provider-plugin.tgz', { env: process.env, cwd: process.cwd() }); +``` diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 44cd873478..fec49ac784 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -46,6 +46,8 @@ agent-device disconnect Every command on a proxy connection must name its session, with `AGENT_DEVICE_SESSION`, `--session `, or a `session` in your config. The same applies to every device-cloud connection. A command that names none fails with `INVALID_ARGS` and `details.reason: "REMOTE_SESSION_REQUIRED"`, and sends nothing to the proxy. It never falls back to the connection that another agent on the same machine saved last. This includes `connect proxy` and `open --remote-config ` with a proxy profile. The client and run that the proxy leases under come from the session name, so two agents with different names never share a lease. +The daemon enforces the same rule for direct RPC callers. An `agent_device.command`, `agent_device.install_from_source`, or `agent_device.lease.*` request that would allocate, use, or release a lease from a lease provider fails with the same reason before anything is allocated or dispatched if it names no session. A request names no session when its `session` param is missing or blank. An `agent_device.command` request also names none when `meta.sessionExplicit` is `false` and no `flags.session` is set, and an `agent_device.lease.*` request when its `sessionExplicit` param is `false`. `agent_device.install_from_source` reads only `session`. `createAgentDeviceClient` sends that fact when you do not pass `session`. Requests with no lease provider keep their default session. + `--daemon-auth-token ` works instead of the environment variable, but it authenticates only the command you pass it to. Later commands need the token again through the environment variable, a `daemonAuthToken` entry in your remote config profile, or the flag on each command. `connect proxy` stores the proxy profile and client identity. `open` leases the device for you, and the lease expires after five minutes without commands. A lease allocated directly over the RPC without `ttlMs` gets the daemon's one-minute inactivity default instead. Either window starts when allocation completes, not when it was requested. `close` releases the active session and its device lease, unless the lease was allocated with `retainOnClose`; only `leases.release`, expiry, or daemon shutdown ends that one. The reply to any request that closed a session lists the leases it ended in `endedLeases`, as `{ leaseId, outcome: 'released' }`. This covers `close`, a `batch` with a close step, and a `replay` or `test` script that closes, as well as the session cleanup `test` runs after each script. A successful reply has the field in `data`, and a failed one has it in `error.details`. A gateway in front of the daemon reads the lease end from that reply. When the reply names the stored lease, the CLI forgets it, so the next `open` leases a device again. `disconnect` clears local connection state. diff --git a/website/docs/docs/replay-e2e.md b/website/docs/docs/replay-e2e.md index d34e6eb31c..a065d0d3c9 100644 --- a/website/docs/docs/replay-e2e.md +++ b/website/docs/docs/replay-e2e.md @@ -40,6 +40,18 @@ and the same original-input guidance. To run Maestro YAML flows or export `.ad` scripts to Maestro YAML, see [Run Maestro flows](/docs/run-maestro-flows). +## Install replay support + +Install the replay plugin on the daemon host to run native `.ad` scripts and `test` suites. + +```bash +agent-device plugins add @agent-device/replay +``` + +Finish your sessions and restart that daemon, then retry your original command with all its arguments. Existing scripts, variables, resume and repair syntax stay the same. A local installation does not install the plugin on a remote daemon. Ordinary `open`/`close --save-script` recording stays available in core. + +For Maestro YAML, install `@agent-device/maestro` on the client and daemon host as well. `replay export` uses the client-side Maestro plugin. See [plugin installation and recovery](./plugins.md). + ## How it works You work in two passes: diff --git a/website/docs/docs/revyl.md b/website/docs/docs/revyl.md index 46d0c84f88..49258f2f39 100644 --- a/website/docs/docs/revyl.md +++ b/website/docs/docs/revyl.md @@ -134,6 +134,7 @@ const host = await startAgentDevice({ }); const scope = { + session: 'checkout-ios', tenant: 'revyl', runId: process.env.GITHUB_RUN_ID ?? 'local-run', leaseBackend: 'ios-instance', diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index ca3d4d080a..21e16d2692 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -10,6 +10,18 @@ title: Run Maestro flows For recording and replaying native `.ad` scripts, see [Replay and E2E testing](/docs/replay-e2e). +## Install Maestro support + +Install the Maestro plugin to replay Maestro flows or export scripts to Maestro YAML. + +```bash +agent-device plugins add @agent-device/maestro +``` + +Install it on the client machine for source collection and export. When you use a remote daemon, install it on that daemon's host too. An embedded daemon uses the plugins supplied by its host application. Close your sessions and restart the daemon after changing its plugins, then retry your original command with all its arguments. Your flow syntax stays the same. + +If the plugin is missing, the error includes `plugin-not-installed` and the installation command. A selected package that fails loading or setup reports its own failure; agent-device does not install a replacement or switch engines. For a store-backed daemon, run `agent-device plugins list --json` on the relevant host. Run `agent-device daemon status --json --state-dir ` on the daemon host with its state directory. That command reads a local record; it cannot inspect a remote daemon from your client machine. + ## Run a Maestro flow Pass `--maestro` to `replay` or `test`: diff --git a/website/docs/docs/testmu.md b/website/docs/docs/testmu.md index 1aa95a632b..cdc59a0260 100644 --- a/website/docs/docs/testmu.md +++ b/website/docs/docs/testmu.md @@ -155,9 +155,11 @@ and releases the lease when a command fails first. Add `providerDeviceType: 'rea The daemon reads `LT_USERNAME` and `LT_ACCESS_KEY` from its environment, unless a JavaScript host passes the plugin `testmu({ credentials })` instead. If you change credentials while the daemon runs, see [Change credentials while the daemon runs](/docs/device-clouds#change-credentials-while-the-daemon-runs). ```ts -import { createAgentDeviceClient } from 'agent-device'; +import { createAgentDeviceClient, ensureDaemon } from 'agent-device'; +await ensureDaemon(); const scope = { + session: 'checkout-ios', tenant: 'testmu', runId: process.env.GITHUB_RUN_ID ?? 'local-run', leaseBackend: 'ios-instance', diff --git a/website/src/site/content.ts b/website/src/site/content.ts index 1bdf878e0b..768e154acb 100644 --- a/website/src/site/content.ts +++ b/website/src/site/content.ts @@ -475,7 +475,7 @@ export const cloud = { icon: 'cube', label: 'Device clouds', title: 'On hosted devices', - body: 'The same commands drive BrowserStack, AWS Device Farm and Limrun devices built in, TestMu AI through its provider plugin, and Expo Simulators on EAS.', + body: 'The same commands drive Limrun devices with built-in support, AWS Device Farm, BrowserStack, and TestMu AI through their provider plugins, and Expo Simulators on EAS.', cmd: 'agent-device connect limrun --platform ios', href: docs.clouds, },