From 47d365c5242265419269ddd81f5c839bda848fd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 13 Nov 2026 22:30:05 +0100 Subject: [PATCH 1/3] refactor(sdk): require explicit host dependencies in 0.22 --- .changeset/explicit-sdk-hosts.md | 11 +++ docs/agents/code-ownership.md | 8 +- .../capture/runtime/diff-screenshot.test.ts | 12 +-- .../presented-surface-carriage.test.ts | 2 +- .../capture/runtime/screenshot.test.ts | 6 +- .../runtime/snapshot-app-identity.test.ts | 4 +- .../runtime/snapshot-freshness.test.ts | 2 +- .../commands/capture/runtime/snapshot.test.ts | 20 ++--- .../__tests__/settle-device-fixtures.ts | 2 +- .../runtime/__tests__/test-utils/index.ts | 4 +- .../interactions-find-carried-target.test.ts | 2 +- .../interactions-preresolved-target.test.ts | 2 +- .../interaction/runtime/interactions.test.ts | 6 +- .../runtime/moving-target-gate.test.ts | 4 +- .../runtime/pre-dispatch-admission.test.ts | 2 +- .../interaction/runtime/selector-is.test.ts | 12 +-- .../interaction/runtime/selector-read.test.ts | 20 ++--- .../selector-wait-cancellation.test.ts | 2 +- .../runtime/settle-capture-deadline.test.ts | 2 +- .../settle-transition-baseline.test.ts | 6 +- .../interaction/runtime/settle.test.ts | 2 +- .../runtime/stable-capture.test.ts | 6 +- .../interaction/runtime/wait-absent.test.ts | 4 +- .../runtime/wait-capture-options.test.ts | 2 +- .../interaction/runtime/wait-selector.test.ts | 6 +- .../interaction/runtime/wait-stable.test.ts | 20 ++--- .../interaction/runtime/wait-text.test.ts | 4 +- packages/contracts/src/artifact-adapter.ts | 2 +- .../src/local-artifact-adapter.test.ts | 2 +- .../host-kit/src/local-artifact-adapter.ts | 7 +- packages/platform-android/src/manifest.ts | 7 -- packages/remote/src/remote-config-core.ts | 14 +-- packages/remote/src/remote-config-schema.ts | 2 +- .../snapshot-presentation-transitions.test.ts | 2 +- src/__tests__/limrun-runtime.test.ts | 85 +++++++++++++------ src/commands/schema/cli-help.ts | 1 + src/platform-runtime-android-adb-host.ts | 2 + src/provider-limrun-runtime.ts | 9 +- src/sdk/android-adb.test.ts | 40 +++++---- src/sdk/android-adb.ts | 19 ++++- src/sdk/artifacts.test.ts | 74 +++++++--------- src/sdk/artifacts.ts | 10 ++- src/sdk/host.ts | 10 +-- src/sdk/limrun-runtime-dependencies.test.ts | 5 +- src/sdk/metro-public.test.ts | 41 ++++++++- src/sdk/metro.ts | 11 +-- src/sdk/remote-config.test.ts | 25 +++--- src/sdk/remote-config.ts | 18 +--- .../installed-package-metro.test.ts | 2 +- .../interaction-contract/runtime-harness.ts | 2 +- test/integration/limrun-public-types.test.ts | 35 +++++++- website/docs/docs/build-an-integration.md | 32 +++++-- 52 files changed, 362 insertions(+), 268 deletions(-) create mode 100644 .changeset/explicit-sdk-hosts.md 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/docs/agents/code-ownership.md b/docs/agents/code-ownership.md index e9b65ea372..e11166bb03 100644 --- a/docs/agents/code-ownership.md +++ b/docs/agents/code-ownership.md @@ -15,11 +15,13 @@ 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 entries `android-adb`, `artifacts`, `limrun`, and `metro`, require an explicit host. +For `resolveRemoteConfigProfile`, require `env`. +For `createLocalArtifactAdapter`, require `cwd`. +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/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 a2320dc896..e844d008f6 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: () => {}, @@ -928,7 +928,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 1621abe83f..79400dd6dd 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/interactions.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/interactions.test.ts @@ -309,7 +309,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(), }); @@ -333,7 +333,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, }); @@ -784,7 +784,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.test.ts b/packages/command-runtime/src/commands/interaction/runtime/pre-dispatch-admission.test.ts index 43ab918789..94e4e6f322 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/pre-dispatch-admission.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/pre-dispatch-admission.test.ts @@ -84,7 +84,7 @@ function createAdmissionDevice(params: { const stored = params.trees[0]!; const device = createAgentDevice({ backend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([ { name: 'default', diff --git a/packages/command-runtime/src/commands/interaction/runtime/selector-is.test.ts b/packages/command-runtime/src/commands/interaction/runtime/selector-is.test.ts index 0e8594daa7..04d95fdfd6 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/selector-is.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/selector-is.test.ts @@ -20,7 +20,7 @@ test('runtime selectors forward public snapshot options to backend capture', asy return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), }); @@ -54,7 +54,7 @@ test('runtime visibility predicates request snapshot rects', async () => { 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.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 0d1c8bfd06..de4c147f95 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 @@ -20,7 +20,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, @@ -64,7 +64,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(), @@ -117,7 +117,7 @@ function createStableCaptureDevice(clock: { return { snapshot }; }, } satisfies AgentDeviceBackend, - artifacts: createLocalArtifactAdapter(), + artifacts: createLocalArtifactAdapter({ cwd: process.cwd() }), sessions: createMemorySessionStore([{ name: 'default', snapshot }]), policy: localCommandPolicy(), clock, @@ -237,7 +237,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(), @@ -273,7 +273,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(), @@ -315,7 +315,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, @@ -352,7 +352,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, @@ -382,7 +382,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(), @@ -426,7 +426,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, @@ -463,7 +463,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/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/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/platform-android/src/manifest.ts b/packages/platform-android/src/manifest.ts index a07e21468b..e05bc79696 100644 --- a/packages/platform-android/src/manifest.ts +++ b/packages/platform-android/src/manifest.ts @@ -24,7 +24,6 @@ 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, @@ -339,10 +338,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 +352,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 +363,5 @@ async function resolveAaptPath(): Promise { // Ignore SDK lookup failures and fall back to undefined. } - aaptPathCache = null; return undefined; } 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/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__/limrun-runtime.test.ts b/src/__tests__/limrun-runtime.test.ts index 8e8d4c9a5c..57312584cc 100644 --- a/src/__tests__/limrun-runtime.test.ts +++ b/src/__tests__/limrun-runtime.test.ts @@ -5,14 +5,18 @@ 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 { LimrunRuntime, type LimrunRuntimeOptions } from '../sdk/limrun.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 { commandHostEnvironment, withCommandHost, runCmd } from '@agent-device/host-kit/command'; import { readVersion } from '@agent-device/host-kit/version'; import { mkdtempForTestSync } from '@agent-device/test-kit'; +function createTestRuntime(options: LimrunRuntimeOptions): LimrunRuntime { + return new LimrunRuntime(options, { env: process.env, cwd: process.cwd() }); +} + type LimrunInstancePage = { getPaginatedItems: () => Array<{ metadata: { id: string } }>; }; @@ -147,7 +151,7 @@ afterEach(() => { }); test('Limrun runtime identifies direct CLI usage when creating an instance', async () => { - const runtime = new LimrunRuntime({ + const runtime = createTestRuntime({ apiKey: 'lim_test_key', }); @@ -193,7 +197,7 @@ 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 runtime = createTestRuntime({ apiKey: 'lim_test_key' }); const lease: DeviceLease = { leaseId: 'lease-repeat', tenantId: 'team-a', @@ -222,7 +226,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,7 +285,7 @@ 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 runtime = createTestRuntime({ apiKey: 'lim_test_key' }); const lease: DeviceLease = { leaseId: 'lease-recovered-ios', tenantId: 'team-a', @@ -313,7 +317,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 +344,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 +361,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 +377,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); @@ -452,7 +456,7 @@ 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 = { @@ -498,7 +502,7 @@ 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()); @@ -527,7 +531,7 @@ 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 = { @@ -588,7 +592,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, { @@ -610,7 +614,7 @@ 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 = { @@ -656,7 +660,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()); @@ -691,7 +695,7 @@ 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 = { @@ -723,7 +727,7 @@ 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 = { @@ -748,7 +752,7 @@ 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 = { @@ -805,7 +809,7 @@ function iosLease(leaseId: string): DeviceLease { } 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 +849,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') @@ -875,7 +879,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') @@ -917,7 +921,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 +937,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 +947,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 +968,32 @@ test('Limrun attaches an existing instance under a consumed field and refuses a await runtime.shutdown(); } }); + +test('public 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) => new LimrunRuntime({ 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/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index c9b6fad1d1..4f52073adc 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -598,6 +598,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, Metro preparation, and LimrunRuntime. 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. 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/provider-limrun-runtime.ts b/src/provider-limrun-runtime.ts index 793e28d213..97b610890f 100644 --- a/src/provider-limrun-runtime.ts +++ b/src/provider-limrun-runtime.ts @@ -1,4 +1,4 @@ -import { captureSdkHost } from './sdk/host.ts'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { DeviceInventoryProvider, LeaseLifecycleProvider, @@ -24,11 +24,8 @@ export class LimrunRuntime implements ProviderDeviceRuntime { // Called through ProviderDeviceRuntime composition and the public Limrun SDK. readonly provider = LIMRUN_PROVIDER; - constructor(options: LimrunRuntimeOptions) { - this.implementation = createLimrunRuntime( - options, - createLimrunRuntimeDependencies(captureSdkHost()), - ); + constructor(options: LimrunRuntimeOptions, host: HostEnvironment) { + this.implementation = createLimrunRuntime(options, createLimrunRuntimeDependencies(host)); } get leaseLifecycle(): LeaseLifecycleProvider { diff --git a/src/sdk/android-adb.test.ts b/src/sdk/android-adb.test.ts index 7472c2fcee..9f0f8bb64d 100644 --- a/src/sdk/android-adb.test.ts +++ b/src/sdk/android-adb.test.ts @@ -39,29 +39,37 @@ 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 shell helpers retain explicit hosts across concurrent foreign scopes', 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), + }); } }, ); 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..ea3352517f 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, writeFileSync } from 'node:fs'; import path from 'node:path'; import { test } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; @@ -8,53 +8,39 @@ 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-'); - const sdk = path.join(root, 'sdk'); - const tools = path.join(sdk, 'build-tools', '99.0.0'); - mkdirSync(tools, { recursive: true }); - const manifest = path.join(root, 'AndroidManifest.xml'); - writeFileSync(manifest, ''); + writeFileSync(path.join(root, 'AndroidManifest.xml'), ''); const archive = path.join(root, 'fallback.apk'); execFileSync('zip', ['-q', archive, 'AndroidManifest.xml'], { cwd: root }); - const calls = path.join(root, 'aapt-calls.jsonl'); - const aapt = path.join(tools, 'aapt'); - 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`, - ); - 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], - ], + 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");`, ); - } finally { - for (const [key, value] of Object.entries(previous)) { - if (value === undefined) delete process.env[key]; - else process.env[key] = value; - } - } + 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']); }, ); diff --git a/src/sdk/artifacts.ts b/src/sdk/artifacts.ts index 379bfd87bc..408f4cceef 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); }); } diff --git a/src/sdk/host.ts b/src/sdk/host.ts index a91f70e955..6da1a9b5c8 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: {} }, task); } diff --git a/src/sdk/limrun-runtime-dependencies.test.ts b/src/sdk/limrun-runtime-dependencies.test.ts index 07e05ce4cb..c3113eac7f 100644 --- a/src/sdk/limrun-runtime-dependencies.test.ts +++ b/src/sdk/limrun-runtime-dependencies.test.ts @@ -36,7 +36,10 @@ 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 runtime = new LimrunRuntime( + { apiKey: 'lim_test_key' }, + { env: process.env, cwd: process.cwd() }, + ); assert.deepEqual(moduleLoads, { androidAppHelpers: 0, 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/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/integration/installed-package-metro.test.ts b/test/integration/installed-package-metro.test.ts index af30a389c7..d1e079ff32 100644 --- a/test/integration/installed-package-metro.test.ts +++ b/test/integration/installed-package-metro.test.ts @@ -645,7 +645,7 @@ assert.equal(fs.existsSync(path.join(cwd, 'host-a', 'daemon.json')), false); './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' }); + const runtime = new mod.LimrunRuntime({ apiKey: 'lim_test_key' }, { env: process.env, cwd: process.cwd() }); await runtime.shutdown(); return runtime.provider; }, 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 index 6accf62a49..a7146a93fa 100644 --- a/test/integration/limrun-public-types.test.ts +++ b/test/integration/limrun-public-types.test.ts @@ -19,7 +19,7 @@ function ensureBuiltPackage(): void { }); } -test('compiled Limrun subpath preserves its downstream type surface', () => { +test('compiled SDK subpaths require explicit hosts and preserve Limrun types', () => { ensureBuiltPackage(); // Keep the fixture under the package root so TypeScript resolves the @@ -49,9 +49,14 @@ test('compiled Limrun subpath preserves its downstream type surface', () => { LimrunDeviceSession, LimrunIosCommandExecution, LimrunIosDeviceSession, - LimrunRuntime, LimrunRuntimeOptions, } from 'agent-device/limrun'; +import { LimrunRuntime } from 'agent-device/limrun'; +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'; declare const runtime: LimrunRuntime; declare const options: LimrunRuntimeOptions; @@ -59,6 +64,32 @@ declare const session: LimrunDeviceSession; declare const iosSession: LimrunIosDeviceSession; declare const execution: LimrunIosCommandExecution; void [runtime, options, session, iosSession, execution]; +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 }); +new LimrunRuntime(options, host); +// @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; +// @ts-expect-error Limrun requires a host. +new LimrunRuntime(options); `, ); diff --git a/website/docs/docs/build-an-integration.md b/website/docs/docs/build-an-integration.md index 6118f6b90a..cd76b59f8e 100644 --- a/website/docs/docs/build-an-integration.md +++ b/website/docs/docs/build-an-integration.md @@ -35,9 +35,11 @@ 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/io` + - `createLocalArtifactAdapter({ cwd, rootDir?, tempDir? })` - `agent-device/batch` - `runBatch(req, sessionName, invoke)` - `agent-device/remote-config` @@ -47,7 +49,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,9 +76,9 @@ Entry points for integrations: - `validateDownloadSourceUrl(url)` - types: `MaterializeInstallSource` - `agent-device/artifacts` - - `resolveAndroidArchivePackageName(archivePath)` + - `resolveAndroidArchivePackageName(archivePath, host, signal?)` - `agent-device/limrun` - - `new LimrunRuntime(options)` + - `new LimrunRuntime(options, host)` - `runtime.getDeviceSession(device)` - types: `LimrunRuntimeOptions`, `LimrunDeviceSession`, `LimrunAndroidDeviceSession`, `LimrunIosDeviceSession`, `LimrunIosCommandExecution` @@ -85,6 +87,21 @@ Entry points for integrations: - `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, Metro preparation, and `LimrunRuntime` 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 +129,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 +160,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 +177,7 @@ const prepared = await prepareMetroRuntime({ leaseId: remoteConfig.profile.leaseId!, }, companionProfileKey: remoteConfig.resolvedPath, -}); +}, host); console.log(prepared.iosRuntime, prepared.androidRuntime); From 7af51db34b1c68bf2775427e6638aeac8295f552 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 13 Nov 2026 22:30:05 +0100 Subject: [PATCH 2/3] chore(gates): remove ambient SDK process entry waivers --- scripts/layering/process-globals-policy.test.ts | 11 +++++++---- scripts/layering/process-globals-policy.ts | 3 --- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/scripts/layering/process-globals-policy.test.ts b/scripts/layering/process-globals-policy.test.ts index 2b416afc6e..374caf2415 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,11 +122,16 @@ 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', 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', From 74af35d752189384ca25437ef026f7c6733ca455 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 13 Nov 2026 22:48:46 +0100 Subject: [PATCH 3/3] fix(sdk): preserve request overlays and archive working directories --- docs/agents/code-ownership.md | 3 -- packages/platform-android/src/manifest.ts | 9 ++++- src/sdk/android-adb.test.ts | 12 +++++- src/sdk/artifacts.test.ts | 40 ++++++++++++++++++- src/sdk/artifacts.ts | 2 +- src/sdk/host.ts | 2 +- .../installed-package-metro.test.ts | 1 + website/docs/docs/build-an-integration.md | 2 - website/docs/docs/client-api.md | 4 +- website/docs/docs/limrun.md | 9 +++-- 10 files changed, 67 insertions(+), 17 deletions(-) diff --git a/docs/agents/code-ownership.md b/docs/agents/code-ownership.md index e11166bb03..30674c687c 100644 --- a/docs/agents/code-ownership.md +++ b/docs/agents/code-ownership.md @@ -18,9 +18,6 @@ Before you edit a module with many callers, run `pnpm depgraph affected `. | 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`, and `metro`, require an explicit host. -For `resolveRemoteConfigProfile`, require `env`. -For `createLocalArtifactAdapter`, require `cwd`. 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`. diff --git a/packages/platform-android/src/manifest.ts b/packages/platform-android/src/manifest.ts index e05bc79696..ffeb25a94c 100644 --- a/packages/platform-android/src/manifest.ts +++ b/packages/platform-android/src/manifest.ts @@ -28,23 +28,26 @@ const utf16Decoder = new TextDecoder('utf-16le'); 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, @@ -323,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, diff --git a/src/sdk/android-adb.test.ts b/src/sdk/android-adb.test.ts index 9f0f8bb64d..72d0422b42 100644 --- a/src/sdk/android-adb.test.ts +++ b/src/sdk/android-adb.test.ts @@ -39,7 +39,7 @@ test('getAndroidAppStateWithAdb falls back to activity focus and settles empty', }); test.skipIf(process.platform === 'win32')( - 'public Android shell helpers retain explicit hosts across concurrent foreign scopes', + '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'); @@ -71,5 +71,15 @@ test.skipIf(process.platform === 'win32')( 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/artifacts.test.ts b/src/sdk/artifacts.test.ts index ea3352517f..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, 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'; @@ -44,3 +44,41 @@ test.skipIf(process.platform === 'win32')( 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 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${cwdGuard}process.stdout.write("package: name='com.example.aapt' versionCode='1'\\n");`, + ); + chmodSync(unzip, 0o755); + chmodSync(aapt, 0o755); + 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 408f4cceef..61090690bd 100644 --- a/src/sdk/artifacts.ts +++ b/src/sdk/artifacts.ts @@ -13,6 +13,6 @@ export async function resolveAndroidArchivePackageName( ): Promise>> { return await withSdkHost(host, async () => { const { resolveAndroidArchivePackageName: resolve } = await loadAndroidMechanics(); - return await resolve(path.resolve(host.cwd, archivePath), signal); + return await resolve(path.resolve(host.cwd, archivePath), signal, host.cwd); }); } diff --git a/src/sdk/host.ts b/src/sdk/host.ts index 6da1a9b5c8..f7b2a20496 100644 --- a/src/sdk/host.ts +++ b/src/sdk/host.ts @@ -2,5 +2,5 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { withCommandHost } from '@agent-device/host-kit/command'; export async function withSdkHost(host: HostEnvironment, task: () => Promise): Promise { - return await withCommandHost({ host, requestEnv: {} }, task); + return await withCommandHost({ host, requestEnv: undefined }, task); } diff --git a/test/integration/installed-package-metro.test.ts b/test/integration/installed-package-metro.test.ts index d1e079ff32..f69ac28a1a 100644 --- a/test/integration/installed-package-metro.test.ts +++ b/test/integration/installed-package-metro.test.ts @@ -627,6 +627,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); }, diff --git a/website/docs/docs/build-an-integration.md b/website/docs/docs/build-an-integration.md index cd76b59f8e..c62354685e 100644 --- a/website/docs/docs/build-an-integration.md +++ b/website/docs/docs/build-an-integration.md @@ -38,8 +38,6 @@ Entry points for integrations: - `runAndroidShell(device, words, host, options?)` / `runAndroidExecOut(device, words, host, options?)` - types: `AndroidAdbExecutor`, `AndroidAdbExecutorOptions`, `AndroidAdbProvider`, `AndroidKeyboardState`, `AndroidKeyboardDismissResult`, `AndroidPortReverseEndpoint` -- `agent-device/io` - - `createLocalArtifactAdapter({ cwd, rootDir?, tempDir? })` - `agent-device/batch` - `runBatch(req, sessionName, invoke)` - `agent-device/remote-config` diff --git a/website/docs/docs/client-api.md b/website/docs/docs/client-api.md index 1e3134065a..d5870559c4 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` diff --git a/website/docs/docs/limrun.md b/website/docs/docs/limrun.md index 33e88da83a..52599813a9 100644 --- a/website/docs/docs/limrun.md +++ b/website/docs/docs/limrun.md @@ -214,10 +214,11 @@ import { LimrunRuntime } from 'agent-device/limrun'; const apiKey = process.env.LIMRUN_API_KEY; if (!apiKey) throw new Error('LIMRUN_API_KEY is required'); -const runtime = new LimrunRuntime({ - apiKey, - region: process.env.LIMRUN_REGION, -}); +const host = { env: { ...process.env }, cwd: process.cwd() }; +const runtime = new LimrunRuntime( + { apiKey, region: process.env.LIMRUN_REGION }, + host, +); ``` 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.