agent-device 0.21.24 → 0.21.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.25.apk +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.25.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.24.manifest.json → agent-device-android-ime-helper-0.21.25.manifest.json} +4 -4
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.25.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.25.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.25.manifest.json +16 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +159 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerHttpRequestFraming.swift +139 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerListenerPeer.swift +41 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerListenerToken.swift +25 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +18 -11
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +25 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +0 -3
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +1 -3
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryConfirmation.swift +59 -26
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +47 -103
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +142 -54
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift +4 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +21 -19
- package/dist/src/absence-observation-errors.js +1 -0
- package/dist/src/adapter.js +1 -1
- package/dist/src/adb-executor.js +2 -2
- package/dist/src/adb-failure.js +2 -2
- package/dist/src/agent-browser-lifecycle.js +1 -1
- package/dist/src/agent-browser-process-record.js +1 -1
- package/dist/src/agent-browser-provider.js +1 -1
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android-input-ownership.js +1 -1
- package/dist/src/android-system-surface-disclosure.js +1 -0
- package/dist/src/android-text-entry.js +1 -0
- package/dist/src/android.js +1 -1
- package/dist/src/app-backend.js +1 -1
- package/dist/src/app-helpers.js +1 -1
- package/dist/src/app-launch.js +1 -1
- package/dist/src/app-lifecycle.js +4 -3
- package/dist/src/app-lifecycle2.js +2 -2
- package/dist/src/app-log-files.js +1 -1
- package/dist/src/app-log-reconnect.js +1 -1
- package/dist/src/app-log-runtime2.js +3 -3
- package/dist/src/app-resolution-facade.js +1 -1
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/apple-runner-platform.js +1 -1
- package/dist/src/artifact-download.js +1 -1
- package/dist/src/auth.js +1 -1
- package/dist/src/aws-device-farm-connection.js +1 -1
- package/dist/src/back-mode.js +1 -1
- package/dist/src/boot-diagnostics.js +1 -1
- package/dist/src/browserstack-connection.js +1 -1
- package/dist/src/capture-disclosure.js +1 -0
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +17 -14
- package/dist/src/cli-output.js +1 -1
- package/dist/src/cli-runner.js +3 -1
- package/dist/src/cli.js +3 -3
- package/dist/src/client-companion-tunnel.js +1 -1
- package/dist/src/client-metro.js +1 -1
- package/dist/src/client-types.d.ts +8 -2
- package/dist/src/code-signature-cache.js +1 -1
- package/dist/src/code-signature.js +1 -1
- package/dist/src/command-metadata.js +73 -1
- package/dist/src/command-policy.js +1 -0
- package/dist/src/command-schema.js +3 -3
- package/dist/src/command-surface.js +1 -1
- package/dist/src/command-tools.js +2 -2
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection-verification.js +1 -1
- package/dist/src/connection.js +3 -3
- package/dist/src/contracts.js +1 -1
- package/dist/src/daemon-client-lease-beat.js +1 -1
- package/dist/src/daemon-client-lifecycle.js +1 -1
- package/dist/src/daemon-client-liveness-probe.js +1 -1
- package/dist/src/daemon-policy-file.js +1 -1
- package/dist/src/daemon-registration-owner.js +1 -1
- package/dist/src/daemon-registration.js +1 -1
- package/dist/src/daemon-resolution.js +3 -1
- package/dist/src/debug-symbols-facade.js +1 -1
- package/dist/src/device-claim-inspection.js +1 -1
- package/dist/src/device-input-state.d.ts +5 -3
- package/dist/src/device-inventory-context.js +1 -1
- package/dist/src/device-readiness-runtime.js +1 -1
- package/dist/src/device-release.js +1 -1
- package/dist/src/device-shell.js +1 -1
- package/dist/src/device.js +3 -1
- package/dist/src/devicectl.js +1 -1
- package/dist/src/diagnostics.js +1 -1
- package/dist/src/doctor-facade.js +1 -1
- package/dist/src/durable-capture-resource.js +1 -1
- package/dist/src/durable-resource.js +1 -1
- package/dist/src/engine-eval-script.js +1 -1
- package/dist/src/error.js +1 -1
- package/dist/src/exec.js +1 -1
- package/dist/src/expo-dev-client-launch.js +1 -0
- package/dist/src/file.js +3 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/generic-settle.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/gesture-plan.js +1 -1
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/harmonyos.js +1 -1
- package/dist/src/hdc.js +1 -1
- package/dist/src/helper.js +2 -2
- package/dist/src/human-control.js +1 -1
- package/dist/src/ime-rebind.js +1 -1
- package/dist/src/ime-state.js +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions2.js +2 -2
- package/dist/src/install-source-network-transport.js +1 -1
- package/dist/src/install-source2.js +1 -1
- package/dist/src/interaction-error.js +1 -0
- package/dist/src/interaction-positionals.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -1
- package/dist/src/interactor-operation-catalog.js +1 -1
- package/dist/src/interactor.js +5 -5
- package/dist/src/interactor2.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +5 -1
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/inventory.js +2 -2
- package/dist/src/inventory6.js +1 -1
- package/dist/src/io.d.ts +2 -2
- package/dist/src/ios-client.js +1 -1
- package/dist/src/ios-settings.js +1 -1
- package/dist/src/ios-snapshot-acquisition.js +1 -1
- package/dist/src/ios-snapshot-adapter.js +1 -1
- package/dist/src/ios-snapshot-engine.js +1 -1
- package/dist/src/ios-snapshot-runtime.js +1 -1
- package/dist/src/keyed-lock.js +1 -1
- package/dist/src/launch-confirmation.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun-runtime-dependencies.js +1 -1
- package/dist/src/limrun.d.ts +2 -10
- package/dist/src/limrun.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/load.js +1 -1
- package/dist/src/local-interactor-operation-set.js +1 -1
- package/dist/src/log-stream.js +9 -9
- package/dist/src/mechanics.js +16 -16
- package/dist/src/metro.js +1 -1
- package/dist/src/metro2.js +1 -1
- package/dist/src/mobile-snapshot-semantics.js +1 -1
- package/dist/src/observability.js +1 -1
- package/dist/src/open-target-resolution.js +1 -1
- package/dist/src/output-path.js +1 -1
- package/dist/src/overlay.js +1 -3
- package/dist/src/perf-facade.js +1 -1
- package/dist/src/perf-runtime-operation-builder.js +1 -1
- package/dist/src/perf-runtime.js +1 -1
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/platform-request-scope.js +1 -1
- package/dist/src/platform-runtime-android-adb-host.js +1 -1
- package/dist/src/platform-runtime-app-log-android-transport.js +1 -1
- package/dist/src/platform-runtime-apple-resources.js +1 -0
- package/dist/src/platform-runtime-claim-recovery.js +1 -0
- package/dist/src/platform-runtime-daemon-services.js +1 -0
- package/dist/src/platform-runtime-host.js +1 -1
- package/dist/src/platform-runtime-network-web-transport.js +1 -1
- package/dist/src/platform-runtime-open-target.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +4 -4
- package/dist/src/platform-runtime-runtime-hints.js +2 -2
- package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-harmony-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-web-host.js +1 -1
- package/dist/src/platform-runtime-unavailable.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -1
- package/dist/src/plugin.js +1 -1
- package/dist/src/png-crop-bytes.js +1 -1
- package/dist/src/png-resize.js +1 -0
- package/dist/src/png-worker-client.js +1 -1
- package/dist/src/png-worker-contract.js +1 -1
- package/dist/src/process-entry.js +1 -1
- package/dist/src/process.js +1 -1
- package/dist/src/provider-credential-fingerprint.js +1 -1
- package/dist/src/provider-device-admission.js +1 -1
- package/dist/src/provider-policy.js +1 -1
- package/dist/src/provider-webdriver.js +1 -1
- package/dist/src/proxy.js +2 -2
- package/dist/src/quality-warnings.js +1 -1
- package/dist/src/react-native-overlay2.js +3 -0
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/recording.js +2 -2
- package/dist/src/register-builtins.js +1 -1
- package/dist/src/remote-config-core.js +1 -1
- package/dist/src/replay-backend-registry.js +1 -0
- package/dist/src/replay-divergence.js +1 -1
- package/dist/src/replay-maestro-backend.js +117 -0
- package/dist/src/replay-script-selection.js +1 -0
- package/dist/src/replay.js +1 -3
- package/dist/src/replay2.js +1 -0
- package/dist/src/reporting.js +3 -3
- package/dist/src/request-cancel.js +1 -1
- package/dist/src/request-providers.js +1 -1
- package/dist/src/request-runtime-binding.js +1 -1
- package/dist/src/result-serialization.js +1 -1
- package/dist/src/retry.js +1 -1
- package/dist/src/runner-cache-retention.js +1 -1
- package/dist/src/runner-cache-trim.js +1 -1
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-dev-tools-security.js +1 -1
- package/dist/src/runner-device-readiness.js +1 -1
- package/dist/src/runner-device-set.js +1 -1
- package/dist/src/runner-error-classification.js +3 -3
- package/dist/src/runner-exchange.js +1 -1
- package/dist/src/runner-lease.js +1 -1
- package/dist/src/runner-operations-facade.js +1 -1
- package/dist/src/runner-retention.js +1 -0
- package/dist/src/runner-start-budget.js +1 -1
- package/dist/src/runner-startup-transport.js +1 -0
- package/dist/src/runner-toolchain-probe.js +1 -1
- package/dist/src/runner.js +2 -1
- package/dist/src/runtime-command-surface.js +1 -0
- package/dist/src/runtime-deployment.js +1 -1
- package/dist/src/runtime-factory.js +1 -0
- package/dist/src/runtime-session.js +1 -0
- package/dist/src/runtime-transport-hints.js +1 -1
- package/dist/src/runtime.js +2 -1
- package/dist/src/runtime10.js +2 -1
- package/dist/src/runtime2.js +5 -2
- package/dist/src/runtime3.js +1 -5
- package/dist/src/runtime4.js +5 -1
- package/dist/src/runtime5.js +1 -5
- package/dist/src/runtime6.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/runtime8.js +1 -1
- package/dist/src/runtime9.js +1 -1
- package/dist/src/screenshot-image.js +1 -1
- package/dist/src/screenshot-runtime.js +1 -0
- package/dist/src/screenshot3.js +5 -5
- package/dist/src/sdk-batch-runner.js +2 -2
- package/dist/src/sdk-batch.js +1 -1
- package/dist/src/sdk-contracts.js +2 -2
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-io.d.ts +4 -2
- package/dist/src/sdk-selectors.d.ts +4 -5
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selection.js +0 -0
- package/dist/src/selector-pipeline-policy.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session-allocation.js +1 -1
- package/dist/src/session-replay-runtime-failure-response.js +1 -0
- package/dist/src/session-runtime-admission.js +1 -0
- package/dist/src/session.js +1 -1
- package/dist/src/session2.js +5 -5
- package/dist/src/settings.js +1 -1
- package/dist/src/settings2.js +1 -1
- package/dist/src/simctl-settings.js +1 -1
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-chrome.js +1 -0
- package/dist/src/snapshot-desktop-projection.js +1 -1
- package/dist/src/snapshot-evidence.js +1 -0
- package/dist/src/snapshot-node-lookup.js +1 -0
- package/dist/src/snapshot-occlusion.js +1 -0
- package/dist/src/snapshot-quality-verdict.js +1 -0
- package/dist/src/snapshot-runtime-binding.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-state.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/snapshot3.js +1 -1
- package/dist/src/src.js +5 -1
- package/dist/src/src2.js +1 -1
- package/dist/src/src3.js +2 -1
- package/dist/src/store.js +1 -1
- package/dist/src/surface-snapshot2.js +1 -1
- package/dist/src/target-evidence-tree.js +1 -0
- package/dist/src/target-evidence.js +1 -1
- package/dist/src/text-entry-focus.js +1 -1
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/touch-runtime.js +1 -1
- package/dist/src/touch-runtime2.js +1 -1
- package/dist/src/tree.js +1 -1
- package/dist/src/tv-remote.js +1 -1
- package/dist/src/type-text-runtime.js +1 -1
- package/dist/src/undici.js +8 -8
- package/dist/src/update-check.js +1 -1
- package/dist/src/vars.js +2 -0
- package/dist/src/version.js +1 -1
- package/dist/src/video.js +2 -2
- package/dist/src/wait.js +1 -0
- package/dist/src/web.js +1 -1
- package/dist/src/web2.js +1 -1
- package/package.json +9 -11
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.24.apk +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.24.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.24.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.24.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.24.manifest.json +0 -16
- package/dist/src/adb-transport.js +0 -1
- package/dist/src/alert-runtime.js +0 -1
- package/dist/src/app-deployment-resolution.js +0 -2
- package/dist/src/app-inventory-contract.js +0 -1
- package/dist/src/app-log-session-resource.js +0 -1
- package/dist/src/application-lifecycle-runtime.js +0 -1
- package/dist/src/auth-session.js +0 -1
- package/dist/src/browserstack-device-features.js +0 -1
- package/dist/src/browserstack.js +0 -1
- package/dist/src/cache.js +0 -1
- package/dist/src/capture.js +0 -1
- package/dist/src/catalog.js +0 -1
- package/dist/src/click-button.js +0 -1
- package/dist/src/client-metro-companion.js +0 -1
- package/dist/src/client-options.js +0 -3
- package/dist/src/daemon-client-transport.js +0 -1
- package/dist/src/daemon-http.js +0 -1
- package/dist/src/device-rotation.js +0 -1
- package/dist/src/device-session.js +0 -3
- package/dist/src/device2.js +0 -1
- package/dist/src/device3.js +0 -3
- package/dist/src/dispatch-resolve.js +0 -4
- package/dist/src/format.js +0 -2
- package/dist/src/gesture-plan-types.js +0 -1
- package/dist/src/host.js +0 -1
- package/dist/src/ime-settings-record.js +0 -1
- package/dist/src/interaction-ref-policy.js +0 -1
- package/dist/src/interactor-operation-binding.js +0 -1
- package/dist/src/keyboard-actions.js +0 -1
- package/dist/src/lease-context.js +0 -1
- package/dist/src/lease-registry-scope.js +0 -1
- package/dist/src/lease-scope.js +0 -1
- package/dist/src/managed-device-scope.js +0 -1
- package/dist/src/manifest.js +0 -1
- package/dist/src/observe-until.js +0 -1
- package/dist/src/output-common.js +0 -5
- package/dist/src/owner-identity.js +0 -3
- package/dist/src/path-resolution.js +0 -1
- package/dist/src/perf-runtime-plan.js +0 -1
- package/dist/src/platform-runtime-app-log-process.js +0 -1
- package/dist/src/platform-runtime-managed-owner.js +0 -1
- package/dist/src/platform-runtime-screen-recording-process-host.js +0 -1
- package/dist/src/png.js +0 -1
- package/dist/src/provider-session-ownership.js +0 -2
- package/dist/src/providers.js +0 -1
- package/dist/src/registry.js +0 -68
- package/dist/src/remote-connection-state.js +0 -1
- package/dist/src/request-admission.js +0 -1
- package/dist/src/request-cancellation.js +0 -1
- package/dist/src/request-progress-protocol.js +0 -1
- package/dist/src/runner-cache-metadata.js +0 -2
- package/dist/src/runner-disposal.js +0 -1
- package/dist/src/runner-session-types.js +0 -1
- package/dist/src/runtime-admission.js +0 -1
- package/dist/src/runtime11.js +0 -2
- package/dist/src/screen-recording-resource-recovery.js +0 -1
- package/dist/src/screenshot-result.js +0 -1
- package/dist/src/script.js +0 -1
- package/dist/src/scroll-command.js +0 -1
- package/dist/src/scroll-gesture.js +0 -1
- package/dist/src/scroll-indicator.js +0 -1
- package/dist/src/session-artifact-paths.js +0 -1
- package/dist/src/session-paths.js +0 -1
- package/dist/src/session-repair-tombstone.js +0 -1
- package/dist/src/session-snapshot.js +0 -1
- package/dist/src/snapshot-private-evidence.js +0 -1
- package/dist/src/snapshot4.js +0 -1
- package/dist/src/src4.js +0 -1
- package/dist/src/src5.js +0 -1
- package/dist/src/src6.js +0 -1
- package/dist/src/src7.js +0 -2
- package/dist/src/src8.js +0 -115
- package/dist/src/string-enum.js +0 -1
- package/dist/src/success-text.js +0 -1
- package/dist/src/transport.js +0 -3
- package/dist/src/ttl-memo.js +0 -1
- package/dist/src/verified-file.js +0 -1
- package/dist/src/window-state.js +0 -1
- /package/dist/src/{doctor-output.js → doctor-lines.js} +0 -0
package/dist/src/runtime2.js
CHANGED
|
@@ -1,2 +1,5 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime.js";import{H as t,P as n}from"./sdk-contracts.js";import{o as r}from"./sdk-device.js";import{$t as i}from"./sdk-batch.js";import{d as a}from"./scroll-gesture.js";import{c as o}from"./sdk-remote-config.js";import"./device.js";import{c as s,l as c}from"./device-rotation.js";import{a as l,i as u,o as d,r as f,s as ee,t as te}from"./runtime-deployment.js";import{t as p}from"./webdriver-source.js";import m from"node:fs";import h from"node:path";import ne,{readFile as re,stat as g}from"node:fs/promises";import{setTimeout as _}from"node:timers/promises";function v(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:e.artifacts.length>0?`ready`:`pending`,cloudArtifacts:e.artifacts,...e.artifacts.length>0?{}:{message:e.pendingMessage}}}function y(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function b(e,t,n,r,i,a){let o=n[r],s=typeof o==`string`?o.trim():``;if(s.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:s,availability:`ready`}}function x(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function S(e,r){try{await r()}catch(r){e instanceof n&&(e.details={...e.details,cleanupError:t(r)})}}function C(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function ie(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function ae(e){let t=e.length-1;for(;t>=0&&e.charCodeAt(t)===47;)--t;return t===e.length-1?e:e.slice(0,t+1)}function oe(e,t){let n=new URL(e);return n.pathname=`${ae(n.pathname)}/${t}`,n}function se(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}async function ce(e,t,r){if(!(await g(e).catch(()=>void 0))?.isFile())throw new n(`INVALID_ARGS`,`${r.service} can only upload a regular app file: ${e}`,{provider:r.provider,appPath:e,hint:`Use an existing .ipa, .apk, or .aab file, or a .zip of the iOS simulator .app bundle.`});let i=new FormData;return i.set(t,new Blob([await re(e)]),h.basename(e)),i}async function le(e,t,r){let i=await fetch(t.endpoint,{method:`POST`,headers:{...x(t.clientVersion),Authorization:C(t.auth)},body:e,signal:r}),a=await T(i),o=t.readAppReference(a)?.trim();if(!i.ok||!o)throw new n(`COMMAND_FAILED`,`${t.service} app upload failed.`,{status:i.status,response:a});return o}function ue(e){return async({appPath:t,options:n,signal:r})=>({appReference:await e(t,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}async function de(e){let{app:t}=e,r=e.parseReference(t);if(r!==void 0)return r;if(/^https?:\/\//i.test(t))return t;let i=h.resolve(e.cwd??process.cwd(),t);if(!m.existsSync(i))throw new n(`INVALID_ARGS`,`${e.service} --provider-app must be ${e.referenceLabel}, URL, or existing local app path.`,{providerApp:t});return await e.uploadFile(i,e.signal)}const w=15e3;async function fe(e,t){let{service:r,unauthorizedHint:i,networkHint:a}=t.hints,o=`Retry connect or check the ${r} service status.`;try{let a=await fetch(e,{headers:{...x(t.clientVersion),...t.auth?{Authorization:C(t.auth)}:{}},signal:AbortSignal.timeout(w)});if(!a.ok){let e=a.status===401||a.status===403;throw new n(e?`UNAUTHORIZED`:`COMMAND_FAILED`,`${r} rejected connection verification.`,{status:a.status,hint:e?i:o})}let s=await T(a);if(s===void 0)throw new n(`COMMAND_FAILED`,`${r} connection verification answer was not JSON.`,{status:a.status,hint:o});return s}catch(e){throw e instanceof n?e:new n(`COMMAND_FAILED`,`${r} connection verification failed.`,{hint:a},e)}}async function pe(e,t){let r,i;try{r=await fetch(e,{headers:{...x(t.clientVersion),Authorization:C(t.auth)},signal:AbortSignal.timeout(w)}),i=await T(r)}catch(e){throw new n(`COMMAND_FAILED`,`${t.service} session details lookup failed.`,{hint:`Check network access to the ${t.service} API, then retry.`},e)}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:void 0;if(!r.ok||!a)throw new n(`COMMAND_FAILED`,`${t.service} session details lookup failed.`,{status:r.status,response:i});return a}async function T(e){let t=await e.text();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function me(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function he(e,t){let r=o.find(e=>e===t);if(r)return r;throw new n(`INVALID_ARGS`,`Invalid ${e.flag} value: ${t}.`,{hint:`Use ${o.join(`|`)}.`,flag:e.flag,capability:e.capability})}function ge(e,t){if(e)return e;throw new n(`INVALID_ARGS`,`${t} lease allocation requires provider profile flags on the request.`)}function _e(e,t){let r=e.flags?.platform;if(r===`android`||r===`ios`)return r;throw new n(`INVALID_ARGS`,`${t} requires --platform ios|android.`)}function ve(e,t,r){let i=E(e,t);if(i)return i;throw new n(`INVALID_ARGS`,r)}function E(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function D(e,t,r){let i=e[t];if(i?.trim())return i;throw new n(`INVALID_ARGS`,`${r} requires ${t} in the environment.`)}function O(e,t){if(e.platform===`android`||e.platform===`ios`)return e.platform;throw new n(`INVALID_ARGS`,`connect ${t} requires --platform ios|android.`)}function k(e,t,r){if(e?.trim())return e;throw new n(`INVALID_ARGS`,`connect ${t} requires ${r}.`)}function A(e,t,r){let i=h.resolve(t,e);if(m.statSync(i,{throwIfNoEntry:!1})?.isFile())return i;throw new n(`INVALID_ARGS`,`${r} app file not found: ${i}`)}const j=`webdriver_request_timeout`;function M(e){return e instanceof n&&e.details?.reason===j}function N(e){return{dispatched:e}}const P=`webdriver_connect_refused`,F=`webdriver_request_interrupted`,ye=new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`EHOSTUNREACH`,`ENETUNREACH`,`UND_ERR_CONNECT_TIMEOUT`]);function be(e){return e instanceof n&&e.details?.reason===P}const xe=new Set([`GET`,`HEAD`]),Se=Object.freeze({});var Ce=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=se(new URL(e.endpoint)),this.headers={...x(e.clientVersion),...e.auth?{Authorization:C(e.auth)}:{},...e.headers},this.requestPolicy={timeoutMs:e.requestPolicy?.timeoutMs??3e4,retryAttempts:e.requestPolicy?.retryAttempts??1,retryDelayMs:e.requestPolicy?.retryDelayMs??250}}async requestValue(e,t,n,r){return(await this.request(e,t,n,r)).value}async request(e,t,n,r){let i=r?.idempotent??xe.has(e);return await this.requestWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??(i?this.requestPolicy.retryAttempts:0),timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!Te(e,a,r.retryAttempts,r.signal))throw e;await _(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i),c=s?De(s):{};if(a)return{status:o,value:Ee(c)};let l=Oe(o,c);throw H(l)&&V(R,{method:e,path:t,status:o,code:B(c)??null}),l}async fetchWebDriver(e,t,n,r,i){let a=new URL(ie(t),this.endpoint),o=n===void 0&&e===`POST`?Se:n,s=AbortSignal.timeout(r),c=i?AbortSignal.any([i,s]):s,l={method:e,path:t,timeoutMs:r,timeoutSignal:s,requestSignal:i},u;try{u=await fetch(a,{method:e,headers:{Accept:`application/json`,...o===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:o===void 0?void 0:JSON.stringify(o),signal:c})}catch(e){throw I(e,l,`request`)}try{return{ok:u.ok,status:u.status,text:await u.text()}}catch(e){throw I(e,l,`response`)}}};function I(e,t,n){let{method:r,path:i,timeoutMs:a,timeoutSignal:o,requestSignal:s}=t;return s?.aborted?e:o.aborted?Me(r,i,a,e):n===`request`&&we(e)?Ne(r,i,e):n===`response`||e instanceof TypeError?Pe(r,i,e):e}function we(e){let t=L(e,0);return t.length>0&&t.every(e=>ye.has(e))}function L(e,t){if(t>4||!e||typeof e!=`object`)return[];let{code:n,cause:r}=e,i=e instanceof AggregateError?e.errors:[];return[...typeof n==`string`?[n]:[],...L(r,t+1),...i.flatMap(e=>L(e,t+1))]}function Te(e,t,n,r){return!r?.aborted&&Fe(e)&&t<n}function Ee(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function De(e){try{return JSON.parse(e)}catch(t){throw new n(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:e},t)}}function Oe(e,t){let r=t&&typeof t==`object`&&`value`in t?t.value:t,i=r&&typeof r==`object`&&typeof r.message==`string`?r.message:`WebDriver request failed with HTTP ${e}.`;return je(e,t)?new n(`COMMAND_FAILED`,i,{...z(),status:e,response:t}):new n(`COMMAND_FAILED`,i,{status:e,response:t,...e>=500?N(`unknown`):{}})}const R=`webdriver_route_unsupported`;function z(){return{reason:R,...N(`no`)}}const ke=new Set([`unknown command`,`unknown method`]),Ae=new Set([404,405,501]);function je(e,t){let n=B(t);return n===void 0?Ae.has(e):ke.has(n.toLowerCase())}function B(e){let t=e&&typeof e==`object`&&`value`in e?e.value:void 0,n=t&&typeof t==`object`?t.error:void 0;return typeof n==`string`?n:void 0}function V(e,t){import(`./diagnostics2.js`).then(e=>e.t).then(({emitDiagnostic:n})=>n({level:`debug`,phase:e,data:t})).catch(()=>void 0)}function H(e){return e instanceof n&&e.details?.reason===R}function Me(e,t,r,i){return new n(`COMMAND_FAILED`,`WebDriver ${e} ${t} timed out after ${r}ms.`,{reason:j,method:e,path:t,timeoutMs:r,...N(`unknown`)},i instanceof Error?i:void 0)}function Ne(e,t,r){return new n(`COMMAND_FAILED`,`WebDriver ${e} ${t} could not reach the driver.`,{reason:P,method:e,path:t,...N(`no`)},r instanceof Error?r:void 0)}function Pe(e,t,r){return new n(`COMMAND_FAILED`,`WebDriver ${e} ${t} lost its connection to the driver.`,{reason:F,method:e,path:t,...N(`unknown`)},r instanceof Error?r:void 0)}function Fe(e){if(M(e)||be(e)||e instanceof n&&e.details?.reason===F)return!0;if(e instanceof n){let t=e.details?.status;return typeof t==`number`&&t>=500}return!1}var Ie=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new Ce(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=Re(await this.requestValue(`POST`,`/session`,{capabilities:Le(e)},{timeoutMs:Be(this.sessionCreateTimeoutMs,t?.deadline)}));return this.sessionId=n.sessionId,n}async deleteSession(){let e=this.requireSessionId();await this.requestValue(`DELETE`,`/session/${e}`),this.sessionId=void 0}async installApp(e,t){await this.sessionRequest(`POST`,`/appium/device/install_app`,{appPath:e},{signal:t})}async activateApp(e){await this.appRouteWithSibling(`/appium/device/activate_app`,`mobile: activateApp`,e)}async terminateApp(e){await this.appRouteWithSibling(`/appium/device/terminate_app`,`mobile: terminateApp`,e)}async appRouteWithSibling(e,t,n){try{await this.sessionRequest(`POST`,e,{appId:n})}catch(r){if(!H(r))throw r;let{status:i}=await this.transport.request(`POST`,`/session/${this.requireSessionId()}/execute/sync`,{script:t,args:[{appId:n,bundleId:n}]});V(`webdriver_route_fallback`,{from:e,to:t,status:i})}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`)}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`)}async isKeyboardShown(e){let t;try{t=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e}})}catch(e){if(H(e))return`unsupported`;throw e}return typeof t==`boolean`?t:`unsupported`}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n;try{n=ze(await this.sessionRequest(`GET`,`/element/active`,void 0,G(t)))}catch(e){if(H(e))return`unsupported`;if(q(e))return`none`;throw e}if(n===void 0)return`unsupported`;try{let e=await this.sessionRequest(`GET`,`/element/${encodeURIComponent(n)}/rect`,void 0,G(t));return{id:n,rect:U(e)}}catch(e){if(H(e))return`unsupported`;if(q(e))return`none`;throw e}}async back(){await this.sessionRequest(`POST`,`/back`)}async setRotation(e){await this.sessionRequest(`POST`,`/rotation`,{x:0,y:0,z:e})}async setOrientation(e){await this.sessionRequest(`POST`,`/orientation`,{orientation:e})}async source(e){let t=await this.sessionRequest(`GET`,`/source`,void 0,e);if(typeof t!=`string`)throw new n(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof t});return t}async screenshot(e){let t=await this.sessionRequest(`GET`,`/screenshot`);if(typeof t!=`string`)throw new n(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof t});await ne.writeFile(e,Buffer.from(t,`base64`))}async windowRect(){return U(await this.sessionRequest(`GET`,`/window/rect`))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async executeReadScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t},{idempotent:!0})}async sessionRequest(e,t,n,r){let i=this.requireSessionId();return await this.requestValue(e,`/session/${i}${t}`,n,r)}requireSessionId(){if(!this.sessionId)throw new n(`SESSION_NOT_FOUND`,`WebDriver session has not been created yet.`);return this.sessionId}async requestValue(e,t,n,r){return await this.transport.requestValue(e,t,n,r)}};function U(e){if(!e||typeof e!=`object`)throw new n(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let t=e,r={x:W(t,`x`),y:W(t,`y`),width:W(t,`width`),height:W(t,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new n(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:t});return r}function W(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Le(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function Re(e){if(!e||typeof e!=`object`)throw new n(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let t=e,r=typeof t.sessionId==`string`?t.sessionId:typeof t.session_id==`string`?t.session_id:void 0;if(!r)throw new n(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:t});return{sessionId:r,capabilities:t.capabilities&&typeof t.capabilities==`object`?t.capabilities:{}}}function ze(e){if(!e||typeof e!=`object`)return;let t=e,n=t[`element-6066-11e4-a52e-4f735466cecf`]??t.ELEMENT;return typeof n==`string`&&n.length>0?n:void 0}function G(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:K(e)}}function Be(e,t){return t===void 0?e:Math.min(e,K(t))}function K(e){return Math.max(0,e-Date.now())}function q(e){return e instanceof n&&Ve(e).toLowerCase()===`no such element`}function Ve(e){let t=e.details?.response,n=t&&typeof t==`object`?t.value:void 0,r=n&&typeof n==`object`?n.error:void 0;return typeof r==`string`?r:``}function J(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function He(e){return Y(p(e,`android`).nodes)}function Ue(e){return Y(p(e).nodes)}function Y(e){let t=e.flatMap(e=>We(e)&&Ge(e.rect)?[e.rect]:[]).sort((e,t)=>t.width*t.height-e.width*e.height)[0];return t?{x:t.x,y:t.y,width:t.width,height:t.height}:void 0}function We(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Ge(e){return!!e&&e.width>=50&&e.height>=50}async function Ke(e,t,r){let i=[];for(let n of t===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await qe(e,n,r);return}catch(e){if(!H(e))throw e;i.push({transport:n,error:e instanceof Error?e.message:String(e)})}throw new n(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{...z(),hint:`The provider driver rejected both orientation endpoints. Set the orientation as a session capability instead, for example connect --provider-device-orientation portrait.`,rotation:r,attempts:i})}async function qe(e,t,n){if(t===`rotation`){await e.setRotation(c(n));return}await e.setOrientation(s(n))}const X=1500;function Je(e){return new Promise(t=>setTimeout(t,e))}function Z(e,t,r){return new n(`COMMAND_FAILED`,`fill tapped (${e}, ${t}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:e,y:t,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function Ye(e,t){return new n(`COMMAND_FAILED`,`fill tapped (${e}, ${t}) but this driver reports neither the focused element nor keyboard state, so the text was not sent`,{reason:`text_entry_focus_unobservable`,x:e,y:t,hint:`This provider cannot confirm a field took focus. Use press <target> followed by type <text> to enter it anyway, accepting that nothing witnesses which field receives the keys.`})}function Xe(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function Ze(e){return new Qe(e.client,e.backend,e.capabilities,e.targetId)}var Qe=class{client;backend;capabilities;targetId;constructor(e,t,n,r){this.client=e,this.backend=t,this.capabilities=n,this.targetId=r}async open(e,t){if(t?.url){await this.client.executeScript(`mobile: deepLink`,[{url:t.url,package:e}]);return}let n=t?.appBundleId??e;n&&await this.client.activateApp(n)}async openDevice(){await this.client.executeScript(`mobile: activateApp`,[{}])}async close(e){e&&await this.client.terminateApp(e)}async tap(e,t){return this.requireSupport(`tap`),await this.pointerGesture(`tap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async doubleTap(e,t){return this.requireSupport(`doubleTap`),await this.pointerGesture(`doubleTap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0},{type:`pause`,duration:80},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async swipe(e,t,n,r,i=400){return this.requireSupport(`swipe`),await this.pointerGesture(`swipe`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerMove`,duration:i,x:n,y:r},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x1:e,y1:t,x2:n,y2:r,durationMs:i}}async longPress(e,t,n=600){return this.requireSupport(`longPress`),await this.pointerGesture(`longPress`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pause`,duration:n},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t,durationMs:n}}async focus(e,t){return await this.tap(e,t)}async type(e){this.requireSupport(`type`),await this.client.sendKeys(e)}async fill(e,t,r,i){if(this.requireSupport(`fill`),r.length===0)throw new n(`UNSUPPORTED_OPERATION`,`fill with empty text (clear field) is not supported on the webdriver backend`,{hint:`Use a visible clear/reset control in the app, or fill the field with the intended replacement text directly.`});let a=await this.readTextEntryState();await this.tap(e,t);let o=await this.awaitTextEntryReadiness(a,e,t);return await this.type(r),{backend:`webdriver`,x:e,y:t,text:r,textEntryReadiness:o}}async scroll(e,t){this.requireSupport(`scroll`);let n=t?.durationMs??350;await this.client.hideKeyboard().catch(()=>void 0);let r=await this.scrollGestureFrame(),i=a({direction:e,amount:t?.amount,pixels:t?.pixels,referenceWidth:r.width,referenceHeight:r.height}),o={...i,x1:i.x1+r.x,y1:i.y1+r.y,x2:i.x2+r.x,y2:i.y2+r.y};return await this.swipe(o.x1,o.y1,o.x2,o.y2,n),{backend:`webdriver`,...o,distance:i.pixels,durationMs:n}}async gestureViewport(){return await this.scrollGestureFrame()}async performGesture(e){return this.requireSupport($e(e)),await this.client.performActions(e.pointers.map(e=>J(`gesture-pointer-${e.pointerId}`,Q(e.samples)))),await this.client.releaseActions().catch(()=>void 0),{backend:`webdriver-w3c-actions`}}async screenshot(e,t){this.requireSupport(`screenshot`),await this.client.screenshot(e)}async snapshot(e){return this.requireSupport(`snapshot`),await this.captureSource(e?.signal)}async captureSource(e){let t=await this.readSource(e);if(this.backend===`xctest`){let{acquireWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return e(t,this.targetId)}let{parseWebDriverSourceFacts:n}=await import(`./webdriver-source.js`).then(e=>e.n);return{backend:`android`,producer:`appium-source`,nodes:n(t,`android`).nodes}}async readSource(e){try{return await this.client.source(e===void 0?{}:{signal:e})}catch(e){throw M(e)?et(e):e}}async back(e){this.requireSupport(`back`),await this.client.back()}async home(){this.requireSupport(`home`),await this.client.executeScript(`mobile: pressButton`,[{name:`home`}])}async setOrientation(e){this.requireSupport(`orientation`),await Ke(this.client,this.backend,e)}async appSwitcher(){this.requireSupport(`appSwitcher`),await this.client.executeScript(`mobile: pressButton`,[{name:`appSwitch`}])}async tvRemote(e,t){this.unsupported(`tvRemote`)}async keyboardStatus(){return this.requireSupport(`keyboard`),{kind:`ime-probe`,visible:await this.keyboardVisible()}}async keyboardDismiss(){this.requireSupport(`keyboard`);let e=await this.keyboardVisibility();if(e===!1)return this.dismissResult({wasVisible:e,visible:!1,dismissed:!1});await this.client.hideKeyboard();let t=await this.keyboardVisibilityAfterMutation();return this.dismissResult({...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t,dismissed:e===!0&&!t}})}dismissResult(e){return this.backend===`android`?{kind:`ime-probe`,...e}:{kind:`mechanism`,mechanism:`appium-hide-keyboard`,...e}}async keyboardEnter(){if(this.requireSupport(`keyboard`),this.backend===`android`)return await this.client.executeScript(`mobile: pressKey`,[{keycode:66}]),{kind:`android-acknowledged`};let e=await this.keyboardVisibility();await this.client.sendKeys(`
|
|
2
|
-
`);let t=await this.keyboardVisibilityAfterMutation();return{kind:`visibility-echo`,...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t}}}async keyboardVisibilityAfterMutation(){try{return await this.keyboardVisibility()}catch{return}}async keyboardVisibility(){let e=await this.client.isKeyboardShown(X);return e===`unsupported`?void 0:e}async keyboardVisible(){let e=await this.keyboardVisibility();if(e===void 0)throw new n(`UNSUPPORTED_OPERATION`,`This driver does not implement the keyboard visibility route.`,{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:`keyboard`});return e}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeReadScript(`mobile: getClipboard`,[{}]);return typeof e==`string`?e:``}async writeClipboard(e){this.requireSupport(`clipboard.write`),await this.client.executeScript(`mobile: setClipboard`,[{content:e}])}async setSetting(e,t,n,r){this.unsupported(`settings`)}async awaitTextEntryReadiness(e,t,n){let r=e.keyboard,i=Date.now()+2e3,a=e.focusedElementId,o=await this.pollWithinBudget(i,async e=>{let r=await this.client.activeElement(e);return r===`unsupported`?`abandon`:r===`none`?`retry`:r.id!==a||Xe(r.rect,t,n)?`satisfied`:`retry`});if(o===`satisfied`)return`focused-element`;if(o===`expired`)throw Z(t,n,`nothing there took text-entry focus, so the text was not sent`);if(r===`unsupported`)throw Ye(t,n);if(r)throw Z(t,n,`the keyboard was already up and this driver cannot report which field holds focus, so the text was not sent`);if(await this.pollWithinBudget(i,async e=>await this.client.isKeyboardShown(e)===!0?`satisfied`:`retry`)===`satisfied`)return`keyboard-shown`;throw Z(t,n,`no keyboard appeared, so the text was not sent`)}async readTextEntryState(){let[e,t]=await Promise.all([this.client.isKeyboardShown(X),this.client.activeElement(X)]);return{keyboard:e,focusedElementId:t===`none`||t===`unsupported`?void 0:t.id}}async pollWithinBudget(e,t){let n=!1,r;for(;;){let i=e-Date.now();if(i<=0)break;try{let e=await t(Math.min(X,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await Je(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([J(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>this.backend===`xctest`?Ue(e):He(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){l(this.capabilities,e)||this.unsupported(e)}unsupported(e){throw new n(`UNSUPPORTED_OPERATION`,ee(this.capabilities,e),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:e})}};function Q(e){let t=e[0];if(!t)throw new n(`INVALID_ARGS`,`WebDriver gesture pointer requires samples`);let r=[{type:`pointerMove`,duration:0,x:t.point.x,y:t.point.y},{type:`pointerDown`,button:0}];for(let t=1;t<e.length;t+=1){let n=e[t-1],i=e[t];r.push({type:`pointerMove`,duration:i.offsetMs-n.offsetMs,x:i.point.x,y:i.point.y})}return r.push({type:`pointerUp`,button:0}),r}function $e(e){if(e.topology===`single`)return`swipe`;switch(e.intent){case`pan`:case`transform`:return`transformGesture`;case`pinch`:return`pinch`;case`rotate`:return`rotateGesture`}}function et(e){return new n(`COMMAND_FAILED`,`The cloud driver did not finish reading the screen in its budget.`,{...e.details,hint:`A screen that never goes idle (looping video, live ticker, continuous animation) gives the driver no moment to read the UI tree. This read has the transport's own budget and does not grow with --timeout; take a screenshot, or drive the screen from refs an earlier snapshot already captured.`},e)}var tt=class{sessionsByLeaseId=new Map;ownedDeviceIds=new Set;releasedProviderSessionIdsByLeaseId=new Map;options;constructor(e){this.options=e}ownsDevice(e){return this.ownedDeviceIds.has(e.id)}findSessionForDevice(e){return[...this.sessionsByLeaseId.values()].find(t=>t.device.id===e.id)}findSessionForLease(e){return this.sessionsByLeaseId.get(e)}getInteractor(e){return this.findSessionForDevice(e)?.interactor}heartbeat(e){if(e.leaseProvider===this.options.provider&&this.sessionsByLeaseId.has(e.leaseId))return{provider:this.options.provider}}async allocate(e,t){if(e.leaseProvider!==this.options.provider)return;let{rejectRefusedProviderProfileFields:n}=await import(`./provider-profile-fields.js`).then(e=>e.t);if(n(t?.flags,this.options.profileFields),this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let r=await this.prepareSession(e,t),i=new Ie({clientVersion:this.options.clientVersion,endpoint:r.endpoint,auth:r.auth,headers:r.headers,requestPolicy:this.options.requestPolicy}),a=await this.createSessionWithPreparedCleanup(i,r,e,t),o=this.deviceForLease(e,r),s=r.providerSessionId??a.sessionId,c=d({provider:this.options.provider,platform:r.platform,overrides:this.options.capabilityOverrides});return this.sessionsByLeaseId.set(e.leaseId,Object.freeze({lease:e,device:o,client:i,prepared:r,capabilities:c,webDriverSessionId:a.sessionId,providerSessionId:s,interactor:Ze({client:i,backend:f(r.platform),capabilities:c,targetId:o.id})})),this.ownedDeviceIds.add(o.id),{provider:this.options.provider,deviceId:o.id,sessionId:a.sessionId,providerSessionId:s,capabilities:c,...r.providerData}}async release(e){if(e.leaseProvider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId);if(!t)return;this.sessionsByLeaseId.delete(e.leaseId),this.releasedProviderSessionIdsByLeaseId.set(e.leaseId,t.providerSessionId);let n=await this.closeSession(t),r=await this.safeListArtifacts(t);return{provider:this.options.provider,providerSessionId:t.providerSessionId,...n.cleanup,...n.warnings.length>0?{warnings:n.warnings}:{},...r?{cloudArtifacts:r}:{}}}async listCloudArtifacts(e){if(e.provider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId??``);return t?await this.listActiveCloudArtifacts(t,e.providerSessionId):await this.listReleasedCloudArtifacts(e)}async listActiveCloudArtifacts(e,t){if(!(t&&t!==e.providerSessionId))return await this.safeListArtifacts(e)}async listReleasedCloudArtifacts(e){let t=this.releasedProviderSessionIdsByLeaseId.get(e.leaseId??``);if(!(!t||!this.options.listArtifacts)&&!(e.providerSessionId&&e.providerSessionId!==t))return await this.options.listArtifacts({provider:this.options.provider,providerSessionId:t})}async shutdown(){await Promise.allSettled([...this.sessionsByLeaseId.values()].map(async e=>await this.closeSession(e))),this.sessionsByLeaseId.clear(),this.ownedDeviceIds.clear()}async createSessionWithPreparedCleanup(e,t,n,r){try{return await e.createSession(t.webdriverCapabilities,{deadline:r?.deadline})}catch(e){let r=M(e)?nt(e,this.options.provider,n,t):e;throw await S(r,()=>t.cleanup?.()),r}}async prepareSession(e,t){let n=this.baseSessionForLease(e);return this.options.prepareSession?await this.options.prepareSession({lease:e,req:t,base:n}):n}baseSessionForLease(e){let t=typeof this.options.webdriverCapabilities==`function`?this.options.webdriverCapabilities(e):this.options.webdriverCapabilities??{};return{provider:this.options.provider,endpoint:this.options.endpoint,platform:this.options.platform,deviceName:this.options.deviceName,auth:this.options.auth,headers:this.options.headers,webdriverCapabilities:u(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...r(t.platform),...t.platform===`ios`?{appleOs:`ios`}:{},id:t.deviceId??this.options.deviceId?.(e)??`${this.options.provider}:${t.platform}:${e.leaseId}`,name:t.deviceName,kind:`device`,target:`mobile`,booted:!0}}async closeSession(e){let n=[],r;try{await e.client.deleteSession()}catch(e){n.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:t(e)})}try{r=await e.prepared.cleanup?.()}catch(e){n.push({code:`PROVIDER_CLEANUP_FAILED`,message:t(e)})}return{cleanup:r,warnings:n}}async safeListArtifacts(e){let t=e.prepared.listArtifacts??this.options.listArtifacts;if(t)try{return await t({provider:this.options.provider,lease:e.lease,device:e.device,webDriverSessionId:e.webDriverSessionId,providerSessionId:e.providerSessionId})}catch(t){return y({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function nt(e,t,r,i){let a=e.details?.timeoutMs;return new n(`COMMAND_FAILED`,`${t} did not create the WebDriver session within ${String(a)}ms.`,{reason:`provider_session_create_timeout`,provider:t,leaseId:r.leaseId,runId:r.runId,timeoutMs:a,...i.providerSessionId?{providerSessionId:i.providerSessionId}:{},hint:`${t} may still finish creating the session after agent-device stopped waiting, and that session would keep billing until the provider reaps it. Before retrying, check ${t} for a running session created for lease ${r.leaseId} (run ${r.runId}) and stop it.`},e)}var rt=e({createCloudWebDriverRuntime:()=>$});function $(e){return new it(e)}var it=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=i(e.provider,e.platform),this.capabilities=d({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new tt(e),this.deployment=te({provider:e.provider,uploadApp:e.uploadApp,findSessionForDevice:e=>this.sessions.findSessionForDevice(e)}),this.platformRuntimeModule=Object.freeze({owner:this.owner,loadRuntime:async e=>await this.loadRuntime(e)}),this.leaseLifecycle={allocate:async(e,t)=>await this.sessions.allocate(e,t),heartbeat:async e=>this.sessions.heartbeat(e),release:async e=>await this.sessions.release(e)},this.cloudArtifacts={listCloudArtifacts:async e=>await this.sessions.listCloudArtifacts(e)},this.deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider)return null;if(!e.leaseId)return[];let t=this.sessions.findSessionForLease(e.leaseId);return t?[t.device]:[]}}async loadRuntime(e){let{createWebDriverPlatformRuntimeOwner:t}=await import(`./platform-runtime2.js`);return t({host:e,owner:this.owner,ownsDevice:e=>this.ownsDevice(e),isSessionActive:e=>this.sessions.findSessionForDevice(e)!==void 0,deployment:this.deployment,capabilities:this.capabilities,snapshotAvailable:this.capabilities.operations.snapshot.support!==`unsupported`,screenshotAvailable:this.capabilities.operations.screenshot.support!==`unsupported`,getInteractor:e=>this.getInteractor(e)})}ownsDevice(e){return this.sessions.ownsDevice(e)}getInteractor(e){return this.sessions.getInteractor(e)}async installApp(e,t,n,r){return await this.deployment.installApp(e,t,n,r)}async installInstallablePath(e,t,n){return await this.deployment.installInstallablePath(e,t,n)}async shutdown(){await this.sessions.shutdown()}};export{b as S,_e as _,ue as a,me as b,le as c,k as d,O as f,ge as g,he as h,oe as i,E as l,ve as m,rt as n,pe as o,D as p,ce as r,fe as s,$ as t,S as u,de as v,v as x,A as y};
|
|
1
|
+
import{P as e,Y as t}from"./sdk-contracts.js";import{i as n}from"./sdk-batch-runner.js";import{r}from"./diagnostics.js";import"./diagnostics2.js";import{N as i}from"./sdk-device.js";import{Yt as a,en as o,tn as s}from"./sdk-batch.js";import{i as c}from"./retry.js";import"./retry2.js";import{n as l}from"./device-shell.js";import{n as u}from"./adb-failure.js";import{i as d,o as f}from"./adb.js";import{n as p,t as m}from"./android-snapshot-quality.js";import{i as h,n as g}from"./recording-stop-observation.js";import{$ as ee,C as te,E as ne,F as re,H as ie,M as ae,Q as oe,R as se,T as ce,U as le,V as ue,W as de,X as fe,Z as pe,_ as me,b as he,c as ge,i as _e,k as ve,l as ye,n as be,p as xe,q as Se}from"./perf-runtime.js";import{i as Ce}from"./touch-runtime.js";import{n as we}from"./audio-probe-runtime.js";import{a as Te,n as Ee}from"./durable-resource.js";import{n as De}from"./async-lifecycle.js";import{i as Oe,l as ke,n as Ae,r as je,t as Me}from"./src3.js";import{n as Ne}from"./screen-recording-completion.js";import{a as _,c as Pe,l as Fe,n as Ie,o as Le,s as Re,t as ze}from"./device-readiness-runtime.js";import{n as Be}from"./screen-recording-runtime.js";import{readAndroidAppStateWithExecutor as Ve}from"./app-state.js";import{ANDROID_CLIPBOARD_SHELL_COMMAND_UNAVAILABLE_HINT as He}from"./clipboard-shell-response.js";import{i as Ue,t as We}from"./gesture-admission.js";import{t as Ge}from"./local-interactor-operation-set.js";import{a as Ke,i as v,n as y,r as qe,t as Je}from"./perf-runtime-operation-builder.js";import{t as Ye}from"./app-log-runtime.js";import{t as Xe}from"./mp4-duration.js";import{a as Ze,n as Qe,o as $e,s as et}from"./application-lifecycle-interaction.js";import b from"node:path";const x=Object.freeze({closed:{id:`1`,state:`CLOSED`},"half-open":{id:`2`,state:`HALF_OPENED`},open:{id:`3`,state:`OPENED`}});async function tt(e,t,n={}){let{signal:i}=n;i?.throwIfAborted();let a=rt(e,t),o=await it(e,i),s=x[a],c=nt(e,a,o),l=a===`closed`&&await S(e,i);return await at(e,a,s.id,i),r({level:`info`,phase:`android_fold_pose_dispatched`,data:{deviceId:e.id,pose:a}}),await ot(e,a,c,o,i),a===`closed`&&!l&&await ct(e,i),{pose:a,hingeAngleDegrees:await lt(e,i)}}function nt(t,n,r){let i=x[n],a=r.get(i.state);if(a!==void 0)return a;let o=Object.keys(x).filter(e=>r.has(x[e].state)),s=o.map(e=>x[e].state);throw s.length===0?new e(`UNSUPPORTED_OPERATION`,`${t.name} is not a foldable emulator: it lists no CLOSED, HALF_OPENED, or OPENED device state`,{deviceId:t.id,reason:`single-panel-device`,hint:`fold poses the hinge of a foldable emulator such as the Pixel 9 Pro Fold; this emulator lists no CLOSED, HALF_OPENED, or OPENED device state, so it has no hinge to pose.`}):new e(`UNSUPPORTED_OPERATION`,`${t.name} has no ${i.state} device state to commit for the ${n} pose; it lists ${s.join(`, `)}`,{deviceId:t.id,reason:`fold-posture-unsupported`,requestedPose:n,supportedPoses:o,deviceStates:s,hint:`This profile poses only ${o.join(` and `)}; request one of those.`})}function rt(t,n){if(n.pose===void 0)throw new e(`UNSUPPORTED_OPERATION`,`fold keyframes are not supported on Android`,{deviceId:t.id,reason:`fold-keyframes-unsupported`,hint:`The emulator console poses the hinge at fixed angles only; request closed, half-open, or open.`});return n.pose}async function it(e,t){let{stdout:n}=await C(e,[`cmd`,`device_state`,`print-states`],t),r=new Map;for(let e of n.matchAll(/identifier=(\d+), name='([A-Z_]+)'/g))r.set(e[2],e[1]);return r}async function at(t,n,r,i){let a=await ut(t,[`emu`,`posture`,r],i);if(/^KO\b/m.test(a.stdout))throw new e(`COMMAND_FAILED`,`Unable to set the emulator posture for ${n}`,{deviceId:t.id,reason:`fold-posture-dispatch-failed`,stdout:a.stdout.trim(),hint:`The emulator console refused the posture. Check that the AVD is a foldable profile (hw.sensor.hinge=yes), then retry.`})}async function ot(t,n,r,i,a){let o;for(let e=1;e<=60;e+=1)if(a?.throwIfAborted(),e>1&&await c(250,a),o=await st(t,a),o===r)return;let s=[...i].find(([,e])=>e===o)?.[0];throw new e(`COMMAND_FAILED`,`${t.name} did not reach the ${n} pose: the emulator still reports device state ${s??o}`,{deviceId:t.id,requestedPose:n,observedDeviceState:s??o,reason:`fold-pose-unverified`,hint:"The emulator console accepted the posture, but the guest did not commit the matching device state. Read it directly with `adb shell cmd device_state print-state` to see which state the emulator holds."})}async function st(e,t){let{stdout:n}=await C(e,[`cmd`,`device_state`,`print-state`],t);return/\d+/.exec(n)?.[0]}async function ct(t,n){let i=0,a=!1;for(let e=1;e<=60;e+=1)if(await c(250,n),await S(t,n))i=0,a=!0,await C(t,[`wm`,`dismiss-keyguard`],n);else if(i+=1,i>=3)break;if(i<3)throw new e(`COMMAND_FAILED`,`${t.name} stays locked after the fold`,{deviceId:t.id,reason:`fold-lock-screen-persists`,hint:"The fold lit a panel Android keeps locked and `wm dismiss-keyguard` did not clear it; a keyguard with a PIN or password has to be unlocked by hand."});a&&r({level:`info`,phase:`android_fold_lock_screen_dismissed`,data:{deviceId:t.id}})}async function S(e,t){let{stdout:n}=await C(e,[`dumpsys`,`window`],t);return n.includes(`isKeyguardShowing=true`)}async function lt(t,n){let{stdout:r}=await ut(t,[`emu`,`sensor`,`get`,`hinge-angle0`],n),i=/hinge-angle0\s*=\s*(-?\d+(?:\.\d+)?)/.exec(r);if(!i)throw new e(`COMMAND_FAILED`,`${t.name} reports no hinge angle`,{deviceId:t.id,reason:`fold-hinge-angle-unreadable`,stdout:r.trim(),hint:"The emulator console answered the posture but exposes no hinge-angle0 sensor to read back; check that the AVD is a foldable profile (hw.sensor.hinge=yes) and that the emulator build supports `sensor get hinge-angle0`."});return Number(i[1])}async function C(e,t,n){let r=await f(e,t,{signal:n,allowFailure:!0});if(r.exitCode!==0)throw u(`adb shell ${t.join(` `)} exited with code ${r.exitCode}`,r,{deviceId:e.id});return r}async function ut(e,t,n){let r=await d(e,t,{signal:n,allowFailure:!0});if(r.exitCode!==0)throw u(`adb ${t.join(` `)} exited with code ${r.exitCode}`,r,{deviceId:e.id});return r}const dt=Object.freeze({available:!0}),ft=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`fold poses the hinge of a foldable Android emulator through the emulator console; a physical device is folded by hand.`});function pt(e){return e.kind===`emulator`?dt:ft}function mt(e){return Re({fold:pt(e)})}function ht(e){let{device:t,signal:n}=e;return s(mt(t).setFoldPose,()=>({setFoldPose:async e=>(n.throwIfAborted(),await tt(t,e,{signal:n}))}))}function gt(e){return Le(e)?Object.freeze({available:!0}):e.kind===`emulator`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`audio probe capture requires a macOS host.`}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`audio probe capture is supported for Android emulators on macOS hosts.`})}function _t(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...Je({platform:`Android`,expectedProfileKind:`simpleperf`,start:async e=>await t().start(n,r,e),reattach:async e=>await t().reattach(n,e),cleanup:async e=>await t().cleanup(n,e),writeProfileReport:async e=>await t().writeProfileReport(n,e)}),perfFrames:async({appId:e})=>({metric:e?await v(t().sampleFrames(n,e)):y(`Android`,`package`),sampling:{method:`adb-shell-dumpsys-gfxinfo-framestats`,description:`Rendered-frame health from the current adb shell dumpsys gfxinfo <package> framestats window. Dropped frames use Android gfxinfo janky-frame/frame-deadline data when available; this is not video recording FPS.`,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}}),perfMemorySample:async({appId:e})=>({metric:e?await v(t().sampleMemory(n,e)):y(`Android`,`package`),sampling:{method:`adb-shell-dumpsys-meminfo`,description:`Memory snapshot from adb shell dumpsys meminfo <package>. Values are reported in kilobytes.`,unit:`kB`,topConsumerLimit:5}}),perfMemorySnapshot:async({appId:e,kind:r,outPath:i,artifactsDir:a})=>{let o=r??`android-hprof`,s=vt();if(o!==`android-hprof`)return Ke(`Android`,o,s,`Use perf memory snapshot --kind android-hprof for Android Java heap artifacts.`);if(!e)throw qe();let c=i??b.join(a,`memory-android-hprof-${yt()}.hprof`);return{artifact:await t().captureMemorySnapshot(n,e,c),support:s,sampling:{method:`adb-shell-am-dumpheap`,description:`Java heap dump captured with adb shell am dumpheap, pulled to a local artifact path.`,defaultKind:`android-hprof`,artifactOnly:!0}}}})}function vt(){return{platform:`android`,defaultKind:`android-hprof`,androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:`Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice.`}}function yt(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}function bt(t){if(!/^[a-zA-Z0-9._:-]+$/.test(t))throw new e(`INVALID_ARGS`,`Invalid Android package name for logs: ${t}`)}const w=Object.freeze({resourceKind:Ye,version:1,encode:e=>({...e}),decode:e=>e.transport!==`android-logcat-local`&&e.transport!==`android-logcat-transport-composed`||!St(e.outputPath)||!St(e.pidPath)?{status:`invalid`,message:`Invalid Android app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:e.transport,outputPath:e.outputPath,pidPath:e.pidPath})}});function xt(e){let t=w.decode(e.descriptor);if(t.status!==`decoded`)throw TypeError(t.message);return Ee({resourceKind:Ye,sessionId:e.sessionId,device:{id:e.device.id,family:`android`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:Te(w,t.descriptor)})}function St(e){return typeof e==`string`&&e.trim().length>0}function Ct(e){return je(e,{family:`android`,backend:`android`,label:`Android`,codec:w,startUnavailableHint:`The selected Android transport cannot start a background adb logcat stream.`,cleanupFailureMessage:`Android app-log cleanup did not settle every owned resource`,doctor:async({host:e,device:t,signal:n},r)=>await wt(e,t.id,r,n),validateStart:({input:e})=>bt(e.appBundleId),process:async({host:e,device:t,input:n})=>({resolvePid:async r=>await Oe(e,Tt(t.id,n.appBundleId),r),command:e=>({kind:`android-adb`,serial:t.id,args:[`logcat`,`-v`,`time`,`--pid`,e],options:{allowFailure:!0}})}),descriptor:({artifacts:e,transport:t})=>({transport:t.mode===`transport-composed`?`android-logcat-transport-composed`:`android-logcat-local`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>xt({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function wt(e,t,n,r){let i={};return i.adbAvailable=await Fe(async()=>Pe(await e.commands.run({executable:`adb`,args:l(`adb`,`shell`,[`echo`,`ok`],[`-s`,t]),allowFailure:!0,timeoutMs:1e3},r)),r),n&&(i.androidPidVisible=await Fe(async()=>!!await Oe(e,Tt(t,n),r),r)),{backend:`android`,checks:i,notes:n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}}function Tt(e,t){return{executable:`adb`,args:l(`adb`,`shell`,[`pidof`,t],[`-s`,e]),allowFailure:!0,timeoutMs:5e3}}async function Et(e,t,n,r){let i=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),a=Ae(i.text,{...n,path:i.path,exists:i.exists,lineNumberOffset:i.skippedLines,backend:`android`}),o=[],s=await Ot(e,t,n,r);if(s&&n.appBundleId){bt(n.appBundleId);let c=await At(e,t,n.appBundleId,r);if(c){let e=Ae(c.text,{...n,path:`${i.path} (adb logcat recovery)`,exists:!0,backend:`android`});e.dump.entries.length>0&&(a=Me(e,a,n.maxEntries),o.push(s.reason===`stale-active`?`Session app log stream was still bound to prior Android PID ${s.trackedPid}. Recovered recent Android HTTP entries from adb logcat for PID set ${c.pids.join(`, `)}.`:`Session app log stream was inactive. Recovered recent Android HTTP entries from adb logcat for PID set ${c.pids.join(`, `)}.`))}}return n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&o.length===0&&o.push(`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):o.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`),a.dump.entries.length===0&&o.push(`No HTTP(s) entries were found in recent session app logs.`),Object.freeze({source:`app-log`,backend:`android`,dump:a.dump,notes:Object.freeze(o)})}async function Dt(e,t,n){n.throwIfAborted();try{let r=await e.commands.run(t,n);return n.throwIfAborted(),r}catch{n.throwIfAborted();return}}async function Ot(e,t,n,r){if(!n.appBundleId||n.appLogSnapshot?.state===void 0)return;if(n.appLogSnapshot.state!==`active`)return{reason:`inactive`};let i=kt(await e.appLogs.readProcessMarker(n.sessionId));if(!i)return;let a=await jt(e,t.id,n.appBundleId,r);if(!(!a||a===i))return{reason:`stale-active`,trackedPid:i}}function kt(e){if(e.status===`decoded`)return/(?:^|\s)--pid\s+(\d+)(?:\s|$)/.exec(e.marker.command)?.[1]}async function At(e,t,n,r){let i=await jt(e,t.id,n,r),a=await Dt(e,{executable:`adb`,args:[`-s`,t.id,`logcat`,`-d`,`-v`,`time`,`-t`,`4000`],allowFailure:!0,timeoutMs:3e3},r);if(!a||a.exitCode!==0||!a.stdout.trim())return;let o=Mt(a.stdout,n,i);if(o.length===0)return;let s=new Set(o),c=a.stdout.split(`
|
|
2
|
+
`).filter(e=>{if(!e.trim())return!1;if(e.includes(n))return!0;let t=/\(\s*(\d+)\)\s*:/.exec(e)?.[1];return!!(t&&s.has(t))}).join(`
|
|
3
|
+
`);return c.trim()?{text:c,pids:o}:void 0}async function jt(e,t,n,r){let i=await Dt(e,{executable:`adb`,args:l(`adb`,`shell`,[`pidof`,n],[`-s`,t]),allowFailure:!0},r);if(!i)return;let a=i.stdout.trim().split(/\s+/)[0];return a&&/^\d+$/.test(a)?a:void 0}function Mt(e,t,n){let r=new Set(n?[n]:[]),i=t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),a=[RegExp(`\\bStart proc\\s+(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`\\b(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`${i}.*?\\bpid\\s*[=:]?\\s*(\\d+)\\b`,`i`),RegExp(`\\bpid\\s*[=:]?\\s*(\\d+)\\b.*${i}`,`i`)];for(let n of e.split(`
|
|
4
|
+
`))if(n.includes(t))for(let e of a){let t=e.exec(n)?.[1];t&&/^\d+$/.test(t)&&r.add(t)}return Object.freeze([...r])}function T(e,t){if(t===1)return e;let n=b.parse(e);return b.join(n.dir,`${n.name}.part-${String(t).padStart(3,`0`)}${n.ext||`.mp4`}`)}const Nt=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-\d{1,20}\.mp4$/,Pt=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-active\.json$/;function Ft(e){return Rt(e)&&zt(e)&&Bt(e)}function It(e){if(!E(e))return!1;let t=e;return Vt(t)&&Ht(t)&&Ut(t)&&Wt(t)&&(t.completion===void 0||Zt(t))}function Lt(e,t){return Qt(e,t)&&$t(e,t.outputPath,t.clientOutputPath)}function Rt(e){return e.backend===`adb-screenrecord`&&typeof e.manifestPath==`string`&&Pt.test(e.manifestPath)&&typeof e.outputPath==`string`}function zt(e){return tn(e.clientOutputPath)&&_(e)}function Bt(e){return en(e.transportMode)}function Vt(e){return e.version===1&&e.resourceKind===`screen-recording`&&typeof e.fenceToken==`string`&&Number.isInteger(e.fenceGeneration)&&typeof e.sessionId==`string`&&typeof e.deviceId==`string`&&Number.isFinite(e.startedAt)}function Ht(e){return typeof e.outputPath==`string`&&tn(e.clientOutputPath)&&_(e)}function Ut(e){return en(e.transportMode)&&(e.pendingRemotePath===void 0||nn(e.pendingRemotePath))}function Wt(e){return Array.isArray(e.chunks)&&e.chunks.every(Gt)&&(e.chunks.length>0||e.pendingRemotePath!==void 0)&&(e.completion===void 0||Kt(e.completion))}function Gt(e,t){if(!E(e))return!1;let n=e;return n.index===t+1&&nn(n.remotePath)&&rn(n.remotePid)&&rn(n.remoteStartTime)}function Kt(e){if(!E(e))return!1;let t=e;return Jt(t)&&Yt(t)&&qt(t)&&(t.chunks===void 0||t.chunks.every(Xt))}function qt(e){return(e.stopObservation===void 0||g(e.stopObservation))&&(e.nativePathDisposition===void 0||h(e.nativePathDisposition))}function Jt(e){return typeof e.backend==`string`&&typeof e.outPath==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)&&Number.isFinite(e.startedAt)&&Number.isFinite(e.completedAt)&&(e.capturedDurationMs===void 0||Number.isFinite(e.capturedDurationMs))}function Yt(e){return _(e)}function Xt(e,t){return e.index===t+1&&typeof e.path==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)}function Zt(e){let t=e.completion;return t!==void 0&&Qt(t,e)&&t.startedAt===e.startedAt&&$t(t,e.outputPath,e.clientOutputPath,e.chunks.length)}function Qt(e,t){return e.backend===`adb screenrecord`&&e.outPath===t.outputPath&&e.clientOutPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&an(e.activeSessionApp,t.activeSessionApp)}function $t(e,t,n,r=e.chunks===void 0?1:e.chunks.length){return r===1?e.chunks===void 0:e.chunks?.length===r&&e.chunks.every((e,r)=>e.path===T(t,r+1)&&e.clientOutPath===(n===void 0?void 0:T(n,r+1)))}function E(e){return typeof e==`object`&&!!e}function en(e){return e===`local`||e===`transport-composed`}function tn(e){return e===void 0||typeof e==`string`}function nn(e){return typeof e==`string`&&Nt.test(e)}function rn(e){return typeof e==`string`&&/^\d+$/.test(e)}function an(e,t){return JSON.stringify(e)===JSON.stringify(t)}const D=Object.freeze({resourceKind:Be,version:1,encode:e=>({...e}),decode:e=>Ft(e)?{status:`decoded`,descriptor:Object.freeze({backend:`adb-screenrecord`,manifestPath:e.manifestPath,outputPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutputPath:e.clientOutputPath},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,transportMode:e.transportMode,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},...e.fps===void 0?{}:{fps:e.fps}})}:{status:`invalid`,message:`Invalid Android screen-recording descriptor`}});function O(e,t,n,r,i,a=`local`){return Object.freeze({version:1,resourceKind:`screen-recording`,fenceToken:t.fence.token,fenceGeneration:t.fence.generation,sessionId:t.sessionId,deviceId:e.id,startedAt:n,outputPath:t.outputPath,...t.clientOutputPath===void 0?{}:{clientOutputPath:t.clientOutputPath},scope:t.scope,showTouches:t.showTouches,recordOnlySession:t.recordOnlySession,...t.activeSessionApp===void 0?{}:{activeSessionApp:t.activeSessionApp},...t.exportQuality===void 0?{}:{exportQuality:t.exportQuality},...t.fps===void 0?{}:{fps:t.fps},chunks:r,...i===void 0?{}:{pendingRemotePath:i},transportMode:a})}function on(e,t){return Object.freeze({...e,completion:t})}function k(e){try{let t=e&&JSON.parse(e);return It(t)?t:void 0}catch{return}}function sn(e,t,n){return e.deviceId===t.id&&e.deviceId===n.device.id&&e.fenceToken===n.fence.token&&e.fenceGeneration===n.fence.generation&&e.sessionId===n.sessionId}function cn(e,t){return e.outputPath===t.outputPath&&e.clientOutputPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&JSON.stringify(e.activeSessionApp)===JSON.stringify(t.activeSessionApp)&&e.exportQuality===t.exportQuality&&e.fps===t.fps&&e.transportMode===t.transportMode&&(e.completion===void 0||Lt(e.completion,t))}function A(e){switch(e){case`missing`:case`ownership-lost`:case`foreign-writer`:return!0;case`owned-alive`:case`uncertain`:return!1}}function ln(e){switch(e){case`missing`:case`ownership-lost`:return!0;case`foreign-writer`:case`owned-alive`:case`uncertain`:return!1}}const un=1e4,dn=1e3;var j=class extends Error{constructor(e){super(`Android screenrecord launch rollback could not be confirmed`,{cause:e})}};function M(e,t=Date.now()){return[...new Set(e?[e,`/sdcard`,`/data/local/tmp`]:[`/sdcard`,`/data/local/tmp`])].map(e=>`${e}/agent-device-recording-${t}.mp4`)}async function fn(e,t,n,r){let i;try{if(i=(await e.start({remotePath:t,quality:n.exportQuality??`medium`},r)).process,!/^\d+$/.test(i.pid)||!/^\d+$/.test(i.startTime)||i.remotePath!==t)throw Error(`Android screenrecord returned an invalid process identity`);if(!await vn(e,t,i,r))throw Error(`Android screenrecord did not begin producing frames`);return{index:1,remotePath:t,remotePid:i.pid,remoteStartTime:i.startTime}}catch(t){throw i&&pn(i)&&!await yn(e,i)?new j(t):r?.aborted?r.reason:t}}function pn(e){return/^\d+$/.test(e.pid)&&/^\d+$/.test(e.startTime)&&e.remotePath.length>0}async function N(e,t){let n=t.at(-1),r=!1,i;for(let a of[...t].reverse())try{let t=await F(e,a);a===n&&(r=t)}catch(e){i??=e}if(i)throw i;return r}async function mn(e,t){for(let n of t){let t;for(let r=0;r<3;r+=1){let i=await e.size(n.remotePath);if(typeof i==`number`&&i>0&&i===t)break;if(t=typeof i==`number`&&i>0?i:void 0,r===2)throw Error(`Android recording artifact is not stable: ${n.remotePath}`);await new Promise(e=>setTimeout(e,250))}}}async function hn(e,t,n){for(let[r,i]of t.entries())await bn(e,i.remotePath,T(n,r+1))}async function P(e,t){let n;for(let r of t)try{if(!await e.remove(r.remotePath))throw Error(`failed to remove Android recording artifact: ${r.remotePath}`)}catch(e){n??=e}if(n)throw n}async function gn(e,t){for(let n of t)if(await e.exists(n.remotePath)!==!1)return`retirable`;return`retired`}async function _n(e,t){try{await N(e,t)}finally{await P(e,t)}}async function vn(e,t,n,r){for(let i=0;i<3;i+=1){if(r?.throwIfAborted(),await e.exists(t,r)===!0)return!0;if(await e.inspect(n,r)!==`owned-alive`)return!1;i<2&&await new Promise(e=>setTimeout(e,250))}return!0}async function yn(e,t){try{let n=await e.stop(t,{force:!0});return(n===`stopped`||n===`already-missing`)&&await e.remove(t.remotePath)}catch{return!1}}async function F(e,t){if(!t)return!1;let n={pid:t.remotePid,remotePath:t.remotePath,startTime:t.remoteStartTime},r=await e.stop(n);if(r===`already-missing`)return!0;if(r===`ownership-lost`)throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.remotePid}`);if(await xn(e,n))return!1;let i=await e.stop(n,{force:!0});if(i===`stopped`||i===`already-missing`)return!1;throw Error(`failed to stop Android screenrecord pid ${t.remotePid}`)}async function bn(e,t,n){for(let r=0;r<3;r+=1){let i=await e.pullPlayable({remotePath:t,outputPath:n});if(i.exitCode===0&&i.playable)return;r+1<3&&await Sn(1e3)}throw Error(`failed to retrieve playable Android recording`)}async function xn(e,t){for(let n=0;n<=un;n+=dn){let r=await e.inspect(t);if(r===`missing`)return!0;if(A(r))throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.pid}`);n<un&&await Sn(dn)}return!1}function Sn(e){return new Promise(t=>setTimeout(t,e))}async function I(e,t,n,r){await e.writeManifest({manifestPath:t,contents:JSON.stringify(n)},r)}async function L(e,t){if(!await e.removeManifest(t))throw Error(`failed to remove Android recording manifest: ${t}`)}async function Cn(e,t){let n=(await wn(e)).flatMap(n=>Tn(n,t,e.mode));for(let t of n)await Dn(e,t.evidence,t.manifestPath)}async function wn(e){return await Promise.all(M(void 0).map(async t=>{let n=e.manifestPathFor(t);return{manifestPath:n,read:await e.readManifest(n)}}))}function Tn(e,t,n){if(e.read.status===`missing`)return[];if(e.read.status!==`read`)throw An(e.manifestPath,e.read.message);let r=k(e.read.contents);if(r===void 0)throw jn(e.manifestPath);if(r.transportMode!==n)throw Mn(e.manifestPath,r,n);if(!En(r,t))throw Nn(e.manifestPath,r,t);return[{manifestPath:e.manifestPath,evidence:r}]}function En(e,t){return e.completion!==void 0||e.deviceId!==t.id}async function Dn(e,t,n){if(await On(e,t),await P(e,t.chunks),await kn(e,t),await L(e,n),(await e.readManifest(n)).status!==`missing`)throw In(n)}async function On(e,t){for(let n of t.chunks){let t=await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime});if(!ln(t))throw t===`uncertain`?Ln(n.remotePath):Pn(n.remotePath,t===`owned-alive`?`named-recorder`:`other-recorder`)}let n=t.pendingRemotePath;if(n===void 0)return;let r=await e.probeRunningWriters(n);if(r.writers.length>0)throw Pn(n,`other-recorder`);if(!r.conclusive)throw Ln(n)}async function kn(e,t){let n=t.pendingRemotePath;if(n!==void 0&&!await e.remove(n))throw Fn(n)}function An(t,n){return new e(`COMMAND_FAILED`,`Android screenrecord native recovery evidence is unavailable: ${t}`,{reason:`native_recovery_evidence_unavailable`,manifestPath:t,hint:`Confirm the device is online and its storage readable, then run record start again.`},Error(n))}function jn(t){return new e(`COMMAND_FAILED`,`Android screenrecord native recovery evidence is unreadable: ${t}`,{reason:`native_recovery_evidence_unreadable`,manifestPath:t,hint:R(t)})}function Mn(t,n,r){return new e(`COMMAND_FAILED`,`Android screenrecord native recovery evidence was written by the ${n.transportMode} transport, not this ${r} one: ${t}`,{reason:`native_recovery_evidence_transport_mismatch`,manifestPath:t,evidenceTransportMode:n.transportMode,hint:R(t)})}function Nn(t,n,r){return new e(`DEVICE_IN_USE`,`Android screenrecord native recovery evidence already exists: ${t} (open recording of session "${n.sessionId}" on ${r.id})`,{reason:`native_recovery_evidence_open`,manifestPath:t,sessionId:n.sessionId,retriable:!1,hint:`Run record stop --session ${n.sessionId} to retire it, or close that session. If it is already closed, ${R(t)}`})}function Pn(t,n){let r=n===`named-recorder`;return new e(`DEVICE_IN_USE`,`Android screenrecord recovery evidence is retained: ${r?`its recorder`:`another recorder`} is writing ${t}`,{reason:`native_recording_artifact_claimed`,remotePath:t,writer:n,...r?{retriable:!1}:{},hint:r?`Run record stop for the session that owns that recording before starting another.`:`Android ends any recorder after 180 seconds. Run record start again once that recorder has stopped.`})}function Fn(t){return new e(`COMMAND_FAILED`,`Android screenrecord recovery evidence could not remove ${t}`,{reason:`native_recording_artifact_removal_failed`,remotePath:t,hint:`Confirm the device is online and run record start again.`})}function In(t){return new e(`COMMAND_FAILED`,`Android screenrecord recovery evidence removal could not be confirmed: ${t}`,{reason:`native_recovery_evidence_retirement_unconfirmed`,manifestPath:t,hint:`Run record start again; the marker is retired from the beginning.`})}function Ln(t){return new e(`COMMAND_FAILED`,`Android screenrecord recovery evidence cannot be safely retired: ${t}`,{reason:`native_recording_recorder_unproven`,remotePath:t,hint:`Confirm the device is online and run record start again.`})}function R(e){return`no recording session can retire this marker; remove it on the device with \`adb shell rm -f ${e}\`.`}async function Rn(e){let{transport:t,device:n,input:r,startedAt:i,signal:a,prepareOutput:o}=e;await Cn(t,n),await o();let s;for(let e of M(void 0)){let o=t.manifestPathFor(e);await I(t,o,O(n,r,i,[],e,t.mode),a);let c,l;try{l=Date.now(),c=await fn(t,e,r,a)}catch(e){if(a.aborted)throw await zn(t,o,e),a.reason;await Hn(t,o,e),s=e;continue}try{await I(t,o,O(n,r,i,[c],void 0,t.mode),a)}catch(e){throw await Bn(t,o,c),e}return{chunk:c,manifestPath:o,startedAtMs:l}}throw s??Error(`Android screenrecord did not begin producing frames`)}async function zn(e,t,n){n instanceof j||await L(e,t).catch(()=>{})}async function Bn(e,t,n){try{await _n(e,[n])}catch{return}await L(e,t).catch(()=>{})}async function Vn(e){let{transport:t,device:n,input:r,startedAt:i,chunks:a,manifestPath:o,preferredDir:s}=e,c;for(let e of M(s)){await I(t,o,O(n,r,i,a,e,t.mode));try{return await fn(t,e,r)}catch(e){if(e instanceof j)throw e;try{await I(t,o,O(n,r,i,a,void 0,t.mode))}catch{throw new j(e)}c=e}}throw c??Error(`failed to start next Android recording chunk`)}async function Hn(e,t,n){if(n instanceof j)throw n;try{await L(e,t)}catch{throw new j(n)}}function Un(e,t){return Object.freeze({backend:`adb screenrecord`,outPath:e.outputPath,...e.clientOutputPath?{clientOutPath:e.clientOutputPath}:{},startedAt:t,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp?{activeSessionApp:e.activeSessionApp}:{},...e.exportQuality?{exportQuality:e.exportQuality}:{},...e.fps===void 0?{}:{fps:e.fps},gestureEvents:[]})}function Wn(e){let t=Gn(e.chunkPaths);if(t===void 0)return{};let n=e.stoppedAtMs-e.startedAtMs;return n-t<2e3?{capturedDurationMs:t}:{capturedDurationMs:t,idleTailWarning:`Android screenrecord encodes a frame only when the screen changes, so this video ends at the last frame it encoded: it covers ${Kn(t)}s of the ${Kn(n)}s recording window.`}}function Gn(e){let t=0;for(let n of e){let e=Xe(n);if(e===void 0)return;t+=e}return t}function Kn(e){return(e/1e3).toFixed(1)}async function qn(e){let{host:t,transport:n,evidence:r,recording:i,startedAtMs:a,progress:o}=e,s=e.reachedLimit===!0;return await Qn(e,await Ie({snapshot:i,progress:o,steps:{stop:async()=>(s=await N(n,r.chunks)||s,await mn(n,r.chunks),{observation:{recorder:`confirmed`},...s?{warning:`Android adb screenrecord stopped before record stop, likely after reaching the 180s platform limit. The MP4 may be truncated; final interactions after the limit are not in the video.`}:{}}),collect:e=>hn(n,r.chunks,e),finalize:({collectedPath:e,exportPath:n,stoppedAtMs:o})=>Jn({host:t,evidence:r,recording:i,startedAtMs:a,stoppedAtMs:o,collectedPath:e,exportPath:n}),discard:e=>Xn(t,e,r.chunks.length)}}))}async function Jn(e){let{host:t,evidence:n,recording:r,collectedPath:i,exportPath:a}=e,o=$n({collectedPath:i,exportPath:a,exportClientPath:r.clientOutPath,count:n.chunks.length}),s=o.length>1,c;try{await Yn(t,o),c=await t.screenRecording.finalize.complete({outputPath:a,showTouches:!s&&r.showTouches,gestureEvents:r.gestureEvents,exportQuality:r.exportQuality??`medium`,...r.fps===void 0?{}:{fps:r.fps},targetLabel:`Android recording`})}catch(e){for(let{served:e}of o)await t.screenRecording.outputs.remove(e.path);throw e}let l=Wn({chunkPaths:o.map(({collected:e})=>e.path),startedAtMs:e.startedAtMs,stoppedAtMs:e.stoppedAtMs});return Zn({finalization:c,captured:l,recording:r,chunked:s,files:o})}async function Yn(e,t){for(let{collected:n,served:r}of t)await e.screenRecording.outputs.copy({from:n.path,to:r.path})}async function Xn(e,t,n){for(let r=1;r<=n;r+=1)await e.screenRecording.outputs.remove(T(t,r))}function Zn(e){let{finalization:t,captured:n,recording:r,chunked:i,files:a}=e,o=[t.warning,...i?[`Android adb screenrecord is capped at 180s, so this recording was split into multiple MP4 chunks.`]:[],n.idleTailWarning].filter(e=>e!==void 0&&e.length>0);return{...t.telemetryPath===void 0?{}:{telemetryPath:t.telemetryPath},...o.length===0?{}:{warning:o.join(` `)},...i&&r.showTouches&&r.gestureEvents.length>0?{overlayWarning:`touch overlay burn-in is skipped for chunked Android recordings; returning raw chunks plus gesture telemetry`}:{},...n.capturedDurationMs===void 0?{}:{capturedDurationMs:n.capturedDurationMs},...i?{chunks:a.map(e=>e.served)}:{},nativePathDisposition:`retirable`}}async function Qn(e,t){let{transport:n,evidence:r,manifestPath:i}=e;return await I(n,i,on(r,t.result)),await P(n,r.chunks),{status:`completed`,result:{...t.result,nativePathDisposition:await gn(n,r.chunks)}}}function $n(e){return Object.freeze(Array.from({length:e.count},(t,n)=>({collected:Object.freeze({index:n+1,path:T(e.collectedPath,n+1)}),served:Object.freeze({index:n+1,path:T(e.exportPath,n+1),...e.exportClientPath===void 0?{}:{clientOutPath:T(e.exportClientPath,n+1)}})})))}async function er(e,t,n){try{let r=t.pendingRemotePath;if(await N(e,[...t.chunks,...await tr(e,t)]),await P(e,t.chunks),r!==void 0&&!await e.remove(r))throw Error(`failed to remove Android recording artifact: ${r}`);return await L(e,n),{status:`cleaned`}}catch(e){return nr(e)}}async function tr(e,t){let n=t.pendingRemotePath;if(n===void 0)return[];let r=await e.probeRunningWriters(n);if(!r.conclusive)throw Error(`cannot list every recorder writing Android artifact: ${n}`);return r.writers.map((e,r)=>({index:t.chunks.length+1+r,remotePath:n,remotePid:e.pid,remoteStartTime:e.startTime}))}function nr(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:String(e)}}async function rr(e){let{transport:t,device:n,envelope:r,descriptor:i}=e;if(i.transportMode!==t.mode)return{status:`transport-unavailable`};let a=await t.readManifest(i.manifestPath);if(a.status===`unavailable`)return{status:`transport-unavailable`};let o=a.status===`read`?k(a.contents):void 0;return o&&sn(o,n,r)&&cn(o,i)?{status:`matched`,evidence:o}:{status:`ownership-lost`}}async function ir(e){let t=await e.transport.readManifest(e.manifestPath);if(t.status!==`read`)return;let n=k(t.contents);return n&&ar(n,e)?n:void 0}function ar(e,t){return e.deviceId===t.deviceId&&e.sessionId===t.sessionId&&e.fenceToken===t.fence.token&&e.fenceGeneration===t.fence.generation}async function or(e){let{host:t,transport:n,device:r,input:i}=e,a=D.decode(i.envelope.descriptor.body);if(a.status!==`decoded`)return z(`descriptor-invalid`);let o=await rr({transport:n,device:r,envelope:i.envelope,descriptor:a.descriptor});return o.status===`matched`?await cr({host:t,transport:n,device:r,input:i,descriptor:a.descriptor,evidence:o.evidence}):z(o.status===`transport-unavailable`?`transport-not-reattachable`:`ownership-fence-lost`)}async function sr(e){let t=D.decode(e.input.envelope.descriptor.body);if(t.status!==`decoded`)return{status:`cleanup-pending`,reason:`manual-recovery-required`};let n=await rr({transport:e.transport,device:e.device,envelope:e.input.envelope,descriptor:t.descriptor});return n.status===`matched`?await er(e.transport,n.evidence,t.descriptor.manifestPath):n.status===`transport-unavailable`?{status:`cleanup-pending`,reason:`owner-unavailable`}:{status:`cleanup-pending`,reason:`ownership-fence-lost`}}async function cr(e){let{host:t,transport:n,device:r,input:i,descriptor:a,evidence:o}=e;if(o.completion!==void 0){let e=await lr(n,o);return e.status===`terminal`?{status:`completed`,result:{...o.completion,nativePathDisposition:e.nativePathDisposition}}:z(`ownership-fence-lost`,`Android recording completed evidence still names a live or unverifiable recorder.`)}if(o.pendingRemotePath!==void 0)return z(`transport-not-reattachable`,`Android recording launch was interrupted before its process identity was committed.`);let s=o.chunks.at(-1);if(!s)return{status:`missing`};let c=await n.inspect({pid:s.remotePid,remotePath:s.remotePath,startTime:s.remoteStartTime});if(c!==`owned-alive`&&await n.exists(s.remotePath)===!1)return z(`transport-not-reattachable`,`Android recording process ended before its artifact could be recovered.`);let l=ur(i.envelope.sessionId,i.envelope.fence,a),u=!1;return{status:`active`,handle:Ne(Un(l,o.startedAt),{finish:async(e,r)=>{let i=await qn({host:t,transport:n,evidence:o,manifestPath:a.manifestPath,recording:e,startedAtMs:o.startedAt,reachedLimit:A(c),progress:r});return u=!0,i},forceCleanup:async()=>u?{status:`cleaned`}:await sr({transport:n,device:r,input:i})})}}async function lr(e,t){try{for(let n of t.chunks)if(!A(await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime})))return{status:`retained`};return{status:`terminal`,nativePathDisposition:await gn(e,t.chunks)}}catch{return{status:`retained`}}}function ur(e,t,n){return{sessionId:e,outputPath:n.outputPath,...n.clientOutputPath===void 0?{}:{clientOutputPath:n.clientOutputPath},scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:!1,recordOnlySession:n.recordOnlySession,...n.activeSessionApp===void 0?{}:{activeSessionApp:n.activeSessionApp},...n.exportQuality===void 0?{}:{exportQuality:n.exportQuality},...n.fps===void 0?{}:{fps:n.fps},fence:t}}function z(e,t){return{status:`unreattachable`,reason:e,...t===void 0?{}:{message:t}}}async function dr(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.android.resolve(n);return Object.freeze({screenRecordingStart:async e=>await fr({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await or({host:t,transport:a,device:n,input:e}),screenRecordingCleanup:async e=>await sr({transport:a,device:n,input:e})})}async function fr(e){let{host:t,transport:n,device:r,owner:a,input:o,signal:s}=e;s.throwIfAborted();let c=Date.now(),l=await Rn({transport:n,device:r,input:o,startedAt:c,signal:s,prepareOutput:async()=>await t.screenRecording.outputs.prepare(o.outputPath)}),u=l.manifestPath,d=[l.chunk],f,p,m,h=!1,g=()=>{f=setTimeout(()=>{p=ee().catch(e=>{m=e})},17e4),f.unref?.()},ee=async()=>{let e=d.at(-1);if(!e)throw Error(`Android recording has no active chunk`);let t=!1,i;try{i=await Vn({transport:n,device:r,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:b.posix.dirname(e.remotePath)})}catch(a){await F(n,e),t=!0;try{i=await Vn({transport:n,device:r,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:b.posix.dirname(e.remotePath)})}catch(e){throw e instanceof Error?e:a}}let a=[...d,{...i,index:d.length+1}];try{await I(n,u,O(r,o,c,a,void 0,n.mode))}catch(a){if(await _n(n,[i]).catch(()=>{}),t)await I(n,u,O(r,o,c,d,i.remotePath,n.mode)).catch(()=>{});else try{await I(n,u,O(r,o,c,d,void 0,n.mode))}catch{await F(n,e).catch(()=>{}),await I(n,u,O(r,o,c,d,i.remotePath,n.mode)).catch(()=>{})}throw a}d=a,t||await F(n,e),g()};g();let te=Ne(Un(o,c),{finish:async(e,i)=>{if(f&&clearTimeout(f),await p,m)throw m;let a=await qn({host:t,transport:n,evidence:O(r,o,c,d,void 0,n.mode),manifestPath:u,recording:e,startedAtMs:l.startedAtMs,progress:i});return h=!0,a},forceCleanup:async()=>{if(f&&clearTimeout(f),h)return{status:`cleaned`};try{await p}catch(e){m=e}let e=await ir({transport:n,deviceId:r.id,sessionId:o.sessionId,fence:o.fence,manifestPath:u});return e?await er(n,e,u):{status:`cleanup-pending`,reason:`ownership-fence-lost`}}});return Object.freeze({pendingHandle:new De(te),envelope:Ee({resourceKind:Be,sessionId:o.sessionId,device:i(r),owner:a,fence:o.fence,lifecycle:`open`,descriptor:Te(D,{backend:`adb-screenrecord`,manifestPath:u,outputPath:o.outputPath,...o.clientOutputPath===void 0?{}:{clientOutputPath:o.clientOutputPath},scope:o.scope,showTouches:o.showTouches,recordOnlySession:o.recordOnlySession,...o.activeSessionApp===void 0?{}:{activeSessionApp:o.activeSessionApp},...o.exportQuality===void 0?{}:{exportQuality:o.exportQuality},...o.fps===void 0?{}:{fps:o.fps},transportMode:n.mode})})})}const pr=1e3;async function B(e,t,n,r){return r.throwIfAborted(),t.kind===`emulator`&&(t.booted!==!0||!V(t))?await mr(e,t,n,r):(t.booted!==!0&&await vr(e,t.id,br(e,n),r),{...t,booted:!0})}async function mr(e,t,n,r){await hr(e);let i=xr(n),a=br(e,n),o=gr(await e.deviceReadiness.androidEmulator.discover(i,r),t.name,n.serial),s=V(o)?o:void 0,c=s?void 0:e.deviceReadiness.androidEmulator.launch(o.name,n.headless);try{let t=s??await _r(e,o.name,i,n.serial,a,r);return await vr(e,t.id,a,r),{...(await e.deviceReadiness.androidEmulator.discover(i,r)).find(e=>e.id===t.id)??t,name:o.name,booted:!0}}catch(t){throw c!==void 0&&r.aborted&&await e.deviceReadiness.androidEmulator.terminate(c),r.throwIfAborted(),t}}async function hr(t){if(await t.toolchains.prepare(`android`),!await t.commands.which(`adb`))throw new e(`TOOL_MISSING`,`adb not found in PATH`);if(!await t.commands.which(`emulator`))throw new e(`TOOL_MISSING`,`emulator not found in PATH`)}function gr(t,n,r){let i=Sr(t,n,r);if(i)return i;throw new e(`DEVICE_NOT_FOUND`,`No Android emulator AVD named ${n}`,{requestedAvdName:n,availableAvds:t.map(e=>e.name),hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."})}async function _r(e,t,n,r,i,a){for(;e.clock.now()<i;){let i=Sr(await e.deviceReadiness.androidEmulator.discover(n,a),t,r);if(i&&V(i))return i;await e.clock.sleep(pr,a)}throw yr(`Android emulator did not appear in time`,{avdName:t,serial:r})}async function vr(e,t,n,r){for(;e.clock.now()<n;){if((await e.commands.run({executable:`adb`,args:l(`adb`,`shell`,[`getprop`,`sys.boot_completed`],[`-s`,t]),allowFailure:!0,timeoutMs:Math.min(1e4,Math.max(1e3,n-e.clock.now()))},r)).stdout.trim()===`1`)return;await e.clock.sleep(pr,r)}throw yr(`Android device failed to finish booting`,{serial:t})}function yr(t,n){return new e(`COMMAND_FAILED`,t,{...n,reason:ze,hint:`The emulator keeps booting in the background. Retry once it is up, or pass a larger --timeout.`})}function br(e,t){return t.deadlineAtMs??e.clock.now()+12e4}function xr(e){return{platform:`android`,kind:`emulator`,...e.serial?{serial:e.serial}:{},...e.androidSerialAllowlist?{androidSerialAllowlist:[...e.androidSerialAllowlist]}:{}}}function Sr(e,t,n){let r=Cr(t);return e.find(e=>e.platform===`android`&&e.kind===`emulator`&&Cr(e.name)===r&&(!n||!V(e)||e.id===n))}function V(e){return e.id.startsWith(`emulator-`)}function Cr(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}async function wr(e,t,n){try{let r=await e.snapshot({appBundleId:t,signal:n,transient:{settleBy:Date.now()+6e3}});return{observation:`androidSnapshot`in r&&r.androidSnapshot?.systemSurfaceOnly===!0?`unobservable`:`observable`}}catch(e){return n.throwIfAborted(),m(e)?{observation:`unobservable`}:{observation:`probe-failed`,failure:Tr(e)}}}function Tr(e){let n=t(e),r=p(n)??n.details?.reason,{code:i}=n;return typeof r==`string`?{source:`capture`,code:i,reason:r}:{source:`capture`,code:i}}function Er(e){let{host:t,device:n,signal:r}=e,i=Qe({device:n,signal:r,resolveInteractor:t.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async e=>await t.androidApplications.resolveOpenTarget(n,e),prepareApplicationOpen:async e=>{await B(t,n,{headless:!1,deadlineAtMs:e.execution.startupDeadlineAtMs},r)},openApplication:async e=>await Dr(t,i,e),applyRuntimeHints:async e=>await t.androidApplications.applyRuntimeHints(n,e),clearRuntimeHints:async e=>await t.androidApplications.clearRuntimeHints(n,e),closeApplication:async e=>{e.ensureReady&&await B(t,n,{headless:!1},r),await $e({device:n,interactor:await i.resolveInteractor(e.execution,e.appBundleId),positionals:e.positionals})},finalizeApplicationClose:async e=>{await t.androidApplications.restoreTestIme(n,{stateDir:e.stateDir,shutdownTarget:e.shutdownTarget===!0&&n.kind===`emulator`,signal:r});let i=e.shutdownTarget&&n.kind===`emulator`?await t.deviceShutdown.android.shutdownTarget(n,r):void 0;return i===void 0?{}:{shutdown:i}},prepareAppleRunner:kr,configureProviderPortReverse:kr})}async function Dr(t,n,r){let i={};if(r.relaunch&&r.target){let e=Date.now();await $e({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:[r.appBundleId??r.target]}),i.relaunchCloseDurationMs=H(e)}if(ee(r.runtimeHints)){if(!r.applyRuntimeHints)throw new e(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let t=Date.now();await r.applyRuntimeHints({appId:r.appBundleId,values:r.runtimeHints}),i.runtimeHintsDurationMs=H(t)}let a=Date.now();await et({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:r.positionals,appBundleId:r.appBundleId,execution:r.execution}),i.openDispatchDurationMs=H(a),r.enableTestIme&&await t.androidApplications.activateTestIme(n.device,{stateDir:r.stateDir});let o=Ze(r);if(o){let e=Date.now();await et({device:n.device,interactor:await n.resolveInteractor({...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},r.appBundleId),positionals:[o],appBundleId:r.appBundleId,execution:{...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}}),i.launchUrlDurationMs=H(e)}else i.launchUrlDurationMs=0;let s=await t.androidApplications.inferOpenedAppBundleId(n.device,r.target,r.appBundleId);s&&await t.androidApplications.resetFramePerfStats(n.device,s);let c=Date.now();return Object.assign(i,await Or(n,r,s)),i.postOpenSettleDurationMs=H(c),{appBundleId:s,timing:i}}async function Or(e,t,r){if(!t.target||n(t.target))return{};if(!r)return{postOpenObservation:`app-unidentified`};let i=await wr(await e.resolveInteractor(t.execution,r),r,e.signal);return i.observation===`probe-failed`?{postOpenObservation:`probe-failed`,postOpenObservationFailure:i.failure}:{postOpenObservation:i.observation}}function H(e){return Math.max(0,Date.now()-e)}async function kr(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Android.`)}async function U(e,t,n,r,i){let a=r?void 0:await Pr(e,t,i);if(b.extname(n).toLowerCase()===`.aab`?await Nr(e,t,n,i):G(await e.androidTools.installPackage(t,n,{replace:!0},i),`adb install failed`),r)return r;let o=[...await Pr(e,t,i)].filter(e=>!a?.has(e));return o.length===1?o[0]:void 0}async function Ar(e,t,n,r){let i=await W(e,t,[`uninstall`,n],r);if(i.exitCode===0)return;let a=`${i.stdout}\n${i.stderr}`.toLowerCase();a.includes(`unknown package`)||a.includes(`not installed`)||G(i,`adb uninstall failed for ${n}`)}async function jr(t,n,r,i){let a=r.payload,o=typeof a.action==`string`&&a.action.trim()?a.action.trim():`${r.appId}.TEST_PUSH`,s=[`am`,`broadcast`,`-a`,o,`-p`,r.appId];typeof a.receiver==`string`&&a.receiver.trim()&&s.push(`-n`,a.receiver.trim());let c=a.extras??{};if(typeof c!=`object`||!c||Array.isArray(c))throw new e(`INVALID_ARGS`,`Android push payload extras must be an object`);let u=0;for(let[e,t]of Object.entries(c))e&&(Fr(s,e,t),u+=1);return G(await W(t,n,l(`adb`,`shell`,s),i),`adb push broadcast failed`),{action:o,extrasCount:u}}function Mr(e){let t=new Set([`com`,`android`,`google`,`app`,`apps`,`service`,`services`,`mobile`,`client`]),n=e.split(/[._-]+/).map(e=>e.trim().toLowerCase()).filter(Boolean),r=[...n].reverse().find(e=>!t.has(e))??n.at(-1)??e;return r.charAt(0).toUpperCase()+r.slice(1)}async function Nr(t,n,r,i){if(await t.androidTools.installBundle(n,r,`universal`,i))return;let a=await t.commands.which(`bundletool`),o=t.androidDeployment.bundletoolJar;if(!a&&!o)throw new e(`TOOL_MISSING`,`bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR.`);let s=a?`bundletool`:`java`,c=a?[]:[`-jar`,o],l=await t.temporaryFiles.create({prefix:`agent-device-aab-`,suffix:`.apks`}),u=l.path;try{G(await t.commands.run({executable:s,args:[...c,`build-apks`,`--bundle`,r,`--output`,u,`--mode`,`universal`]},i),`bundletool build-apks failed`),G(await t.commands.run({executable:s,args:[...c,`install-apks`,`--apks`,u,`--device-id`,n.id]},i),`bundletool install-apks failed`)}finally{await l[Symbol.asyncDispose]()}}async function Pr(e,t,n){let r=await W(e,t,l(`adb`,`shell`,[`pm`,`list`,`packages`]),n);return G(r,`adb package inventory failed`),new Set(r.stdout.split(`
|
|
5
|
+
`).map(e=>e.replace(`package:`,``).trim()).filter(Boolean))}function Fr(t,n,r){if(typeof r==`string`)t.push(`--es`,n,r);else if(typeof r==`boolean`)t.push(`--ez`,n,String(r));else if(typeof r==`number`&&Number.isFinite(r))t.push(Number.isInteger(r)?`--ei`:`--ef`,n,String(r));else throw new e(`INVALID_ARGS`,`Unsupported Android broadcast extra type for "${n}". Use string, boolean, or number.`)}async function W(e,t,n,r,i=15e3){return await e.androidTools.runAdb(t,n,{timeoutMs:i,allowFailure:!0},r)}function G(t,n){if(t.exitCode===0)return;let r={stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode};throw new e(`COMMAND_FAILED`,n,r)}const Ir=Object.freeze({available:!0});function Lr(e){let t=Vr(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:t})}function Rr(e){let{host:t,device:n,signal:r}=e;return Lr(n).deployApp.available?Object.freeze({deployApp:async e=>await zr(t,n,e,r),materializeAppSource:async e=>await t.androidDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await Br(t,n,e,r),sendPushNotification:async e=>await jr(t,n,e,r)}):Object.freeze({})}async function zr(e,t,n,r){if(n.replaceExisting)return await e.androidDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i;try{t.booted!==!0&&await B(e,t,{headless:!1},r);let a=await e.androidDeployment.resolveAppPackage(t,n.app);return await Ar(e,t,a,r),i=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!1,signal:r}),await U(e,t,i.installablePath,void 0,r),{packageName:a,launchTarget:a}}finally{await i?.cleanup()}});let i;try{t.booted!==!0&&await B(e,t,{headless:!1},r),i=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!0,signal:r});let a=await U(e,t,i.installablePath,i.packageName,r);return a?{packageName:a,appName:Mr(a),launchTarget:a}:{}}finally{await i?.cleanup()}}async function Br(t,n,r,i){let a=await U(t,n,r.artifact.installablePath,r.artifact.packageName,i);if(!a)throw new e(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return{packageName:a,appName:Mr(a),launchTarget:a}}function Vr(e){return e.kind===`emulator`||e.kind===`device`?Ir:Object.freeze({available:!1,reason:`unsupported-device-kind`})}const K=a(`android`),q=Object.freeze({available:!0}),Hr=o(`unsupported-device-kind`),J=o(`unsupported-device-kind`,`focus is supported on Android emulators and physical devices.`),Ur=o(`unsupported-device-kind`,`keyboard actions are supported on Android emulators and physical devices.`),Wr=o(`unsupported-platform-leaf`),Gr=o(`unsupported-platform-leaf`,`Android has no key event for this system button.`),Kr=o(`unsupported-device-kind`,`Headless boot is supported only for Android emulators.`),qr=o(`unsupported-device-kind`,`Android appstate is supported only for Android emulators and devices.`),Jr=o(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),Yr=o(`unsupported-device-kind`,`open is supported only for Android emulators and devices.`),Xr=o(`unsupported-device-kind`,`close is supported only for Android emulators and devices.`),Zr=o(`unsupported-device-kind`,`Runtime hints are supported only for Android emulators and devices.`),Qr=o(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),$r=o(`unsupported-device-kind`,`shutdown is supported only for Apple simulators and Android emulators.`),ei=o(`unsupported-device-kind`,`screenshot is supported only for Android emulators and devices.`),Y=o(`unsupported-device-kind`,`snapshot is supported only for Android emulators and devices.`),ti=o(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),ni=o(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web).`),ri=o(`unsupported-platform-leaf`,`the stateless audio page probe is a web-session operation; Android targets use the host capture.`);function ii(e){let t=ai(e),n=oi(e),r=si(e);return pe({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:r,clearRuntimeHints:r,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:Jr,configureProviderPortReverse:Qr})}function ai(e){return e.kind===`emulator`||e.kind===`device`?q:Yr}function oi(e){return e.kind===`emulator`||e.kind===`device`?q:Xr}function si(e){return e.kind===`emulator`||e.kind===`device`?q:Zr}const X=o(`unsupported-device-kind`,`Gestures are supported on Android emulators and physical devices.`),ci=o(`unsupported-platform-leaf`,We),li=o(`unsupported-platform-leaf`,Ue);function ui(e,t){return e.kind===`simulator`?X:e.target===`tv`?t:q}function Z(e){return e.kind===`simulator`?X:q}function Q(e){return e.kind===`simulator`?J:q}const $=o(`owner-capability-missing`,He),di=o(`owner-capability-missing`,`Could not determine whether this Android build supports a shell clipboard: the adb probe did not complete. Retry once the device is reachable.`);async function fi(e,t){let n=e.androidTools?.probeClipboardShellSupport;return n?await n.call(e.androidTools,t):`probe-failed`}const pi=o(`unsupported-device-kind`,`tv-remote is supported only on Android TV targets.`);function mi(e){return e.kind!==`simulator`&&e.target===`tv`?q:pi}function hi(e){let t=Ct(e),n=new Map,r=async t=>{if(t.kind===`simulator`)return $;let r=n.get(t.id)??await fi(e,t);return r!==`probe-failed`&&n.set(t.id,r),r===`supported`?q:r===`unsupported`?$:di},i=async e=>{let n=await t.inspectFacts(e),i=Lr(e),a=await r(e);return Object.freeze({device:n.device,operations:{...n.operations,...i,appState:e.kind===`simulator`?qr:q,networkDump:q,screenRecordingStart:q,screenRecordingReattach:q,screenRecordingCleanup:q,...Se({capture:e.kind===`simulator`?Y:q,customActions:ti,withoutActiveApp:e.kind===`simulator`?Y:q}),...fe({capture:e.kind===`simulator`?ei:q}),...le({findText:Y}),...ie({setViewport:ni}),...ue({focus:Q(e)}),...se({unsupported:X,plan:Z(e),directionalFling:Z(e),multiTouch:ui(e,ci),targetAuthoredDrag:ui(e,li),viewport:Z(e)}),...re({scroll:Z(e)}),...ae({type:Q(e)}),...Ce({unsupported:J,tap:Q(e),longPress:Q(e),hover:Wr,fill:Q(e)}),...ve({readTextAtPoint:e.kind===`simulator`?Hr:q}),...ne({back:Q(e)}),...xe({unsupported:Gr,home:Q(e),appSwitcher:Q(e)}),...mt(e),...ye({triggerAppEvent:Q(e)}),...ge({setSetting:Q(e),readSetting:Q(e)}),..._e({read:Q(e),wait:Q(e),accept:Q(e),dismiss:Q(e)}),...ce({orientation:Q(e)}),...te({tvRemote:mi(e)}),...he({unsupported:Ur,status:Q(e),dismiss:Q(e),enter:Q(e)}),...me({unsupported:a.available?$:a,read:a,write:a}),...we({capture:gt(e),query:ri}),...be({frames:Q(e),memorySample:Q(e),memorySnapshot:Q(e),nativeCapture:Q(e),profileReport:Q(e)}),ensureReady:q,bootTarget:q,bootTargetHeadless:e.kind===`emulator`?q:Kr,listApps:q,...ii(e),shutdownTarget:e.kind===`emulator`?q:$r}})};return Object.freeze({owner:K,ownsDevice:e=>e.platform===`android`,inspectFacts:i,bind:async n=>{let r=await t.bind(n),a=await i(n.device),o=await dr({host:e,device:n.device,owner:K,signal:n.scope.signal});return Object.freeze({device:r.device,owner:K,facts:a,operations:Object.freeze({...r.operations,...Rr({host:e,device:n.device,signal:n.scope.signal}),...a.operations.appState.available?{appState:async()=>{n.scope.signal.throwIfAborted();let{runAndroidAdb:e}=await import(`./adb.js`).then(e=>e.t);return await Ve(async(t,r)=>await e(n.device,t,{...r,signal:n.scope.signal}),n.scope.signal)}}:{},networkDump:async t=>await Et(e,n.device,t,n.scope.signal),...o,...s(a.operations.audioProbeStart,()=>ke({host:e.audioProbe.hostCapture,device:n.device,owner:K})),...s(a.operations.perfFrames,()=>_t({resolveHost:()=>e.perf.android,device:n.device,owner:K})),...gi(e,n,a),...ht({device:n.device,signal:n.scope.signal}),ensureReady:async t=>await B(e,n.device,{...t,headless:!1},n.scope.signal),bootTarget:async t=>await B(e,n.device,{...t,headless:!1},n.scope.signal),...a.operations.bootTargetHeadless.available?{bootTargetHeadless:async t=>await B(e,n.device,{...t,headless:!0},n.scope.signal)}:{},listApps:async e=>{n.scope.signal.throwIfAborted();let{listAndroidApps:t}=await import(`./app-lifecycle.js`).then(e=>e.n);return(await t(e.device,e.filter)).map(e=>({id:e.package,name:e.name}))},...oe(Er({host:e,device:n.device,signal:n.scope.signal}),a.operations),...a.operations.shutdownTarget.available?{shutdownTarget:async()=>await e.deviceShutdown.android.shutdownTarget(n.device,n.scope.signal)}:{}}),[Symbol.asyncDispose]:async()=>await r[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}function gi(e,t,n){let r={device:t.device,signal:t.scope.signal,resolveInteractor:e.localInteractors.resolve};return{...n.operations.captureSnapshot.available?de(r):{},...Ge({...r,facts:n.operations,pause:async n=>await e.clock.sleep(n,t.scope.signal)})}}export{hi as createAndroidPlatformRuntime};
|
package/dist/src/runtime3.js
CHANGED
|
@@ -1,5 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`).filter(e=>{if(!e.trim())return!1;if(e.includes(n))return!0;let t=/\(\s*(\d+)\)\s*:/.exec(e)?.[1];return!!(t&&s.has(t))}).join(`
|
|
3
|
-
`);return c.trim()?{text:c,pids:o}:void 0}async function ut(e,t,n,r){let i=await ot(e,{executable:`adb`,args:s(`adb`,`shell`,[`pidof`,n],[`-s`,t]),allowFailure:!0},r);if(!i)return;let a=i.stdout.trim().split(/\s+/)[0];return a&&/^\d+$/.test(a)?a:void 0}function dt(e,t,n){let r=new Set(n?[n]:[]),i=t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),a=[RegExp(`\\bStart proc\\s+(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`\\b(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`${i}.*?\\bpid\\s*[=:]?\\s*(\\d+)\\b`,`i`),RegExp(`\\bpid\\s*[=:]?\\s*(\\d+)\\b.*${i}`,`i`)];for(let n of e.split(`
|
|
4
|
-
`))if(n.includes(t))for(let e of a){let t=e.exec(n)?.[1];t&&/^\d+$/.test(t)&&r.add(t)}return Object.freeze([...r])}function w(e,t){if(t===1)return e;let n=S.parse(e);return S.join(n.dir,`${n.name}.part-${String(t).padStart(3,`0`)}${n.ext||`.mp4`}`)}const ft=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-\d{1,20}\.mp4$/,pt=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-active\.json$/;function mt(e){return _t(e)&&vt(e)&&yt(e)}function ht(e){if(!T(e))return!1;let t=e;return bt(t)&&xt(t)&&St(t)&&Ct(t)&&(t.completion===void 0||At(t))}function gt(e,t){return jt(e,t)&&Mt(e,t.outputPath,t.clientOutputPath)}function _t(e){return e.backend===`adb-screenrecord`&&typeof e.manifestPath==`string`&&pt.test(e.manifestPath)&&typeof e.outputPath==`string`}function vt(e){return Pt(e.clientOutputPath)&&_(e)}function yt(e){return Nt(e.transportMode)}function bt(e){return e.version===1&&e.resourceKind===`screen-recording`&&typeof e.fenceToken==`string`&&Number.isInteger(e.fenceGeneration)&&typeof e.sessionId==`string`&&typeof e.deviceId==`string`&&Number.isFinite(e.startedAt)}function xt(e){return typeof e.outputPath==`string`&&Pt(e.clientOutputPath)&&_(e)}function St(e){return Nt(e.transportMode)&&(e.pendingRemotePath===void 0||Ft(e.pendingRemotePath))}function Ct(e){return Array.isArray(e.chunks)&&e.chunks.every(wt)&&(e.chunks.length>0||e.pendingRemotePath!==void 0)&&(e.completion===void 0||Tt(e.completion))}function wt(e,t){if(!T(e))return!1;let n=e;return n.index===t+1&&Ft(n.remotePath)&&It(n.remotePid)&&It(n.remoteStartTime)}function Tt(e){if(!T(e))return!1;let t=e;return Dt(t)&&Ot(t)&&Et(t)&&(t.chunks===void 0||t.chunks.every(kt))}function Et(e){return(e.stopObservation===void 0||d(e.stopObservation))&&(e.nativePathDisposition===void 0||u(e.nativePathDisposition))}function Dt(e){return typeof e.backend==`string`&&typeof e.outPath==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)&&Number.isFinite(e.startedAt)&&Number.isFinite(e.completedAt)&&(e.capturedDurationMs===void 0||Number.isFinite(e.capturedDurationMs))}function Ot(e){return _(e)}function kt(e,t){return e.index===t+1&&typeof e.path==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)}function At(e){let t=e.completion;return t!==void 0&&jt(t,e)&&t.startedAt===e.startedAt&&Mt(t,e.outputPath,e.clientOutputPath,e.chunks.length)}function jt(e,t){return e.backend===`adb screenrecord`&&e.outPath===t.outputPath&&e.clientOutPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&Lt(e.activeSessionApp,t.activeSessionApp)}function Mt(e,t,n,r=e.chunks===void 0?1:e.chunks.length){return r===1?e.chunks===void 0:e.chunks?.length===r&&e.chunks.every((e,r)=>e.path===w(t,r+1)&&e.clientOutPath===(n===void 0?void 0:w(n,r+1)))}function T(e){return typeof e==`object`&&!!e}function Nt(e){return e===`local`||e===`transport-composed`}function Pt(e){return e===void 0||typeof e==`string`}function Ft(e){return typeof e==`string`&&ft.test(e)}function It(e){return typeof e==`string`&&/^\d+$/.test(e)}function Lt(e,t){return JSON.stringify(e)===JSON.stringify(t)}const E=Object.freeze({resourceKind:Pe,version:1,encode:e=>({...e}),decode:e=>mt(e)?{status:`decoded`,descriptor:Object.freeze({backend:`adb-screenrecord`,manifestPath:e.manifestPath,outputPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutputPath:e.clientOutputPath},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,transportMode:e.transportMode,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},...e.fps===void 0?{}:{fps:e.fps}})}:{status:`invalid`,message:`Invalid Android screen-recording descriptor`}});function D(e,t,n,r,i,a=`local`){return Object.freeze({version:1,resourceKind:`screen-recording`,fenceToken:t.fence.token,fenceGeneration:t.fence.generation,sessionId:t.sessionId,deviceId:e.id,startedAt:n,outputPath:t.outputPath,...t.clientOutputPath===void 0?{}:{clientOutputPath:t.clientOutputPath},scope:t.scope,showTouches:t.showTouches,recordOnlySession:t.recordOnlySession,...t.activeSessionApp===void 0?{}:{activeSessionApp:t.activeSessionApp},...t.exportQuality===void 0?{}:{exportQuality:t.exportQuality},...t.fps===void 0?{}:{fps:t.fps},chunks:r,...i===void 0?{}:{pendingRemotePath:i},transportMode:a})}function Rt(e,t){return Object.freeze({...e,completion:t})}function O(e){try{let t=e&&JSON.parse(e);return ht(t)?t:void 0}catch{return}}function zt(e,t,n){return e.deviceId===t.id&&e.deviceId===n.device.id&&e.fenceToken===n.fence.token&&e.fenceGeneration===n.fence.generation&&e.sessionId===n.sessionId}function Bt(e,t){return e.outputPath===t.outputPath&&e.clientOutputPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&JSON.stringify(e.activeSessionApp)===JSON.stringify(t.activeSessionApp)&&e.exportQuality===t.exportQuality&&e.fps===t.fps&&e.transportMode===t.transportMode&&(e.completion===void 0||gt(e.completion,t))}function k(e){switch(e){case`missing`:case`ownership-lost`:case`foreign-writer`:return!0;case`owned-alive`:case`uncertain`:return!1}}function Vt(e){switch(e){case`missing`:case`ownership-lost`:return!0;case`foreign-writer`:case`owned-alive`:case`uncertain`:return!1}}const Ht=1e4,Ut=1e3;var A=class extends Error{constructor(e){super(`Android screenrecord launch rollback could not be confirmed`,{cause:e})}};function j(e,t=Date.now()){return[...new Set(e?[e,`/sdcard`,`/data/local/tmp`]:[`/sdcard`,`/data/local/tmp`])].map(e=>`${e}/agent-device-recording-${t}.mp4`)}async function Wt(e,t,n,r){let i;try{if(i=(await e.start({remotePath:t,quality:n.exportQuality??`medium`},r)).process,!/^\d+$/.test(i.pid)||!/^\d+$/.test(i.startTime)||i.remotePath!==t)throw Error(`Android screenrecord returned an invalid process identity`);if(!await Xt(e,t,i,r))throw Error(`Android screenrecord did not begin producing frames`);return{index:1,remotePath:t,remotePid:i.pid,remoteStartTime:i.startTime}}catch(t){throw i&&Gt(i)&&!await Zt(e,i)?new A(t):r?.aborted?r.reason:t}}function Gt(e){return/^\d+$/.test(e.pid)&&/^\d+$/.test(e.startTime)&&e.remotePath.length>0}async function M(e,t){let n=t.at(-1),r=!1,i;for(let a of[...t].reverse())try{let t=await P(e,a);a===n&&(r=t)}catch(e){i??=e}if(i)throw i;return r}async function Kt(e,t){for(let n of t){let t;for(let r=0;r<3;r+=1){let i=await e.size(n.remotePath);if(typeof i==`number`&&i>0&&i===t)break;if(t=typeof i==`number`&&i>0?i:void 0,r===2)throw Error(`Android recording artifact is not stable: ${n.remotePath}`);await new Promise(e=>setTimeout(e,250))}}}async function qt(e,t,n){for(let[r,i]of t.entries())await Qt(e,i.remotePath,w(n,r+1))}async function N(e,t){let n;for(let r of t)try{if(!await e.remove(r.remotePath))throw Error(`failed to remove Android recording artifact: ${r.remotePath}`)}catch(e){n??=e}if(n)throw n}async function Jt(e,t){for(let n of t)if(await e.exists(n.remotePath)!==!1)return`retirable`;return`retired`}async function Yt(e,t){try{await M(e,t)}finally{await N(e,t)}}async function Xt(e,t,n,r){for(let i=0;i<3;i+=1){if(r?.throwIfAborted(),await e.exists(t,r)===!0)return!0;if(await e.inspect(n,r)!==`owned-alive`)return!1;i<2&&await new Promise(e=>setTimeout(e,250))}return!0}async function Zt(e,t){try{let n=await e.stop(t,{force:!0});return(n===`stopped`||n===`already-missing`)&&await e.remove(t.remotePath)}catch{return!1}}async function P(e,t){if(!t)return!1;let n={pid:t.remotePid,remotePath:t.remotePath,startTime:t.remoteStartTime},r=await e.stop(n);if(r===`already-missing`)return!0;if(r===`ownership-lost`)throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.remotePid}`);if(await $t(e,n))return!1;let i=await e.stop(n,{force:!0});if(i===`stopped`||i===`already-missing`)return!1;throw Error(`failed to stop Android screenrecord pid ${t.remotePid}`)}async function Qt(e,t,n){for(let r=0;r<3;r+=1){let i=await e.pullPlayable({remotePath:t,outputPath:n});if(i.exitCode===0&&i.playable)return;r+1<3&&await en(1e3)}throw Error(`failed to retrieve playable Android recording`)}async function $t(e,t){for(let n=0;n<=Ht;n+=Ut){let r=await e.inspect(t);if(r===`missing`)return!0;if(k(r))throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.pid}`);n<Ht&&await en(Ut)}return!1}function en(e){return new Promise(t=>setTimeout(t,e))}async function F(e,t,n,r){await e.writeManifest({manifestPath:t,contents:JSON.stringify(n)},r)}async function I(e,t){if(!await e.removeManifest(t))throw Error(`failed to remove Android recording manifest: ${t}`)}async function tn(e,t){let n=(await nn(e)).flatMap(n=>rn(n,t,e.mode));for(let t of n)await on(e,t.evidence,t.manifestPath)}async function nn(e){return await Promise.all(j(void 0).map(async t=>{let n=e.manifestPathFor(t);return{manifestPath:n,read:await e.readManifest(n)}}))}function rn(e,t,n){if(e.read.status===`missing`)return[];if(e.read.status!==`read`)throw ln(e.manifestPath,e.read.message);let r=O(e.read.contents);if(r===void 0)throw un(e.manifestPath);if(r.transportMode!==n)throw dn(e.manifestPath,r,n);if(!an(r,t))throw fn(e.manifestPath,r,t);return[{manifestPath:e.manifestPath,evidence:r}]}function an(e,t){return e.completion!==void 0||e.deviceId!==t.id}async function on(e,t,n){if(await sn(e,t),await N(e,t.chunks),await cn(e,t),await I(e,n),(await e.readManifest(n)).status!==`missing`)throw hn(n)}async function sn(e,t){for(let n of t.chunks){let t=await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime});if(!Vt(t))throw t===`uncertain`?gn(n.remotePath):pn(n.remotePath,t===`owned-alive`?`named-recorder`:`other-recorder`)}let n=t.pendingRemotePath;if(n===void 0)return;let r=await e.probeRunningWriters(n);if(r.writers.length>0)throw pn(n,`other-recorder`);if(!r.conclusive)throw gn(n)}async function cn(e,t){let n=t.pendingRemotePath;if(n!==void 0&&!await e.remove(n))throw mn(n)}function ln(e,n){return new t(`COMMAND_FAILED`,`Android screenrecord native recovery evidence is unavailable: ${e}`,{reason:`native_recovery_evidence_unavailable`,manifestPath:e,hint:`Confirm the device is online and its storage readable, then run record start again.`},Error(n))}function un(e){return new t(`COMMAND_FAILED`,`Android screenrecord native recovery evidence is unreadable: ${e}`,{reason:`native_recovery_evidence_unreadable`,manifestPath:e,hint:L(e)})}function dn(e,n,r){return new t(`COMMAND_FAILED`,`Android screenrecord native recovery evidence was written by the ${n.transportMode} transport, not this ${r} one: ${e}`,{reason:`native_recovery_evidence_transport_mismatch`,manifestPath:e,evidenceTransportMode:n.transportMode,hint:L(e)})}function fn(e,n,r){return new t(`DEVICE_IN_USE`,`Android screenrecord native recovery evidence already exists: ${e} (open recording of session "${n.sessionId}" on ${r.id})`,{reason:`native_recovery_evidence_open`,manifestPath:e,sessionId:n.sessionId,retriable:!1,hint:`Run record stop --session ${n.sessionId} to retire it, or close that session. If it is already closed, ${L(e)}`})}function pn(e,n){let r=n===`named-recorder`;return new t(`DEVICE_IN_USE`,`Android screenrecord recovery evidence is retained: ${r?`its recorder`:`another recorder`} is writing ${e}`,{reason:`native_recording_artifact_claimed`,remotePath:e,writer:n,...r?{retriable:!1}:{},hint:r?`Run record stop for the session that owns that recording before starting another.`:`Android ends any recorder after 180 seconds. Run record start again once that recorder has stopped.`})}function mn(e){return new t(`COMMAND_FAILED`,`Android screenrecord recovery evidence could not remove ${e}`,{reason:`native_recording_artifact_removal_failed`,remotePath:e,hint:`Confirm the device is online and run record start again.`})}function hn(e){return new t(`COMMAND_FAILED`,`Android screenrecord recovery evidence removal could not be confirmed: ${e}`,{reason:`native_recovery_evidence_retirement_unconfirmed`,manifestPath:e,hint:`Run record start again; the marker is retired from the beginning.`})}function gn(e){return new t(`COMMAND_FAILED`,`Android screenrecord recovery evidence cannot be safely retired: ${e}`,{reason:`native_recording_recorder_unproven`,remotePath:e,hint:`Confirm the device is online and run record start again.`})}function L(e){return`no recording session can retire this marker; remove it on the device with \`adb shell rm -f ${e}\`.`}async function _n(e){let{transport:t,device:n,input:r,startedAt:i,signal:a,prepareOutput:o}=e;await tn(t,n),await o();let s;for(let e of j(void 0)){let o=t.manifestPathFor(e);await F(t,o,D(n,r,i,[],e,t.mode),a);let c,l;try{l=Date.now(),c=await Wt(t,e,r,a)}catch(e){if(a.aborted)throw await vn(t,o,e),a.reason;await xn(t,o,e),s=e;continue}try{await F(t,o,D(n,r,i,[c],void 0,t.mode),a)}catch(e){throw await yn(t,o,c),e}return{chunk:c,manifestPath:o,startedAtMs:l}}throw s??Error(`Android screenrecord did not begin producing frames`)}async function vn(e,t,n){n instanceof A||await I(e,t).catch(()=>{})}async function yn(e,t,n){try{await Yt(e,[n])}catch{return}await I(e,t).catch(()=>{})}async function bn(e){let{transport:t,device:n,input:r,startedAt:i,chunks:a,manifestPath:o,preferredDir:s}=e,c;for(let e of j(s)){await F(t,o,D(n,r,i,a,e,t.mode));try{return await Wt(t,e,r)}catch(e){if(e instanceof A)throw e;try{await F(t,o,D(n,r,i,a,void 0,t.mode))}catch{throw new A(e)}c=e}}throw c??Error(`failed to start next Android recording chunk`)}async function xn(e,t,n){if(n instanceof A)throw n;try{await I(e,t)}catch{throw new A(n)}}function Sn(e,t){return Object.freeze({backend:`adb screenrecord`,outPath:e.outputPath,...e.clientOutputPath?{clientOutPath:e.clientOutputPath}:{},startedAt:t,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp?{activeSessionApp:e.activeSessionApp}:{},...e.exportQuality?{exportQuality:e.exportQuality}:{},...e.fps===void 0?{}:{fps:e.fps},gestureEvents:[]})}function Cn(e){let t=wn(e.chunkPaths);if(t===void 0)return{};let n=e.stoppedAtMs-e.startedAtMs;return n-t<2e3?{capturedDurationMs:t}:{capturedDurationMs:t,idleTailWarning:`Android screenrecord encodes a frame only when the screen changes, so this video ends at the last frame it encoded: it covers ${Tn(t)}s of the ${Tn(n)}s recording window.`}}function wn(e){let t=0;for(let n of e){let e=Ue(n);if(e===void 0)return;t+=e}return t}function Tn(e){return(e/1e3).toFixed(1)}async function En(e){let{host:t,transport:n,evidence:r,recording:i,startedAtMs:a,progress:o}=e,s=e.reachedLimit===!0;return await jn(e,await Ae({snapshot:i,progress:o,steps:{stop:async()=>(s=await M(n,r.chunks)||s,await Kt(n,r.chunks),{observation:{recorder:`confirmed`},...s?{warning:`Android adb screenrecord stopped before record stop, likely after reaching the 180s platform limit. The MP4 may be truncated; final interactions after the limit are not in the video.`}:{}}),collect:e=>qt(n,r.chunks,e),finalize:({collectedPath:e,exportPath:n,stoppedAtMs:o})=>Dn({host:t,evidence:r,recording:i,startedAtMs:a,stoppedAtMs:o,collectedPath:e,exportPath:n}),discard:e=>kn(t,e,r.chunks.length)}}))}async function Dn(e){let{host:t,evidence:n,recording:r,collectedPath:i,exportPath:a}=e,o=Mn({collectedPath:i,exportPath:a,exportClientPath:r.clientOutPath,count:n.chunks.length}),s=o.length>1,c;try{await On(t,o),c=await t.screenRecording.finalize.complete({outputPath:a,showTouches:!s&&r.showTouches,gestureEvents:r.gestureEvents,exportQuality:r.exportQuality??`medium`,...r.fps===void 0?{}:{fps:r.fps},targetLabel:`Android recording`})}catch(e){for(let{served:e}of o)await t.screenRecording.outputs.remove(e.path);throw e}let l=Cn({chunkPaths:o.map(({collected:e})=>e.path),startedAtMs:e.startedAtMs,stoppedAtMs:e.stoppedAtMs});return An({finalization:c,captured:l,recording:r,chunked:s,files:o})}async function On(e,t){for(let{collected:n,served:r}of t)await e.screenRecording.outputs.copy({from:n.path,to:r.path})}async function kn(e,t,n){for(let r=1;r<=n;r+=1)await e.screenRecording.outputs.remove(w(t,r))}function An(e){let{finalization:t,captured:n,recording:r,chunked:i,files:a}=e,o=[t.warning,...i?[`Android adb screenrecord is capped at 180s, so this recording was split into multiple MP4 chunks.`]:[],n.idleTailWarning].filter(e=>e!==void 0&&e.length>0);return{...t.telemetryPath===void 0?{}:{telemetryPath:t.telemetryPath},...o.length===0?{}:{warning:o.join(` `)},...i&&r.showTouches&&r.gestureEvents.length>0?{overlayWarning:`touch overlay burn-in is skipped for chunked Android recordings; returning raw chunks plus gesture telemetry`}:{},...n.capturedDurationMs===void 0?{}:{capturedDurationMs:n.capturedDurationMs},...i?{chunks:a.map(e=>e.served)}:{},nativePathDisposition:`retirable`}}async function jn(e,t){let{transport:n,evidence:r,manifestPath:i}=e;return await F(n,i,Rt(r,t.result)),await N(n,r.chunks),{status:`completed`,result:{...t.result,nativePathDisposition:await Jt(n,r.chunks)}}}function Mn(e){return Object.freeze(Array.from({length:e.count},(t,n)=>({collected:Object.freeze({index:n+1,path:w(e.collectedPath,n+1)}),served:Object.freeze({index:n+1,path:w(e.exportPath,n+1),...e.exportClientPath===void 0?{}:{clientOutPath:w(e.exportClientPath,n+1)}})})))}async function Nn(e,t,n){try{let r=t.pendingRemotePath;if(await M(e,[...t.chunks,...await Pn(e,t)]),await N(e,t.chunks),r!==void 0&&!await e.remove(r))throw Error(`failed to remove Android recording artifact: ${r}`);return await I(e,n),{status:`cleaned`}}catch(e){return Fn(e)}}async function Pn(e,t){let n=t.pendingRemotePath;if(n===void 0)return[];let r=await e.probeRunningWriters(n);if(!r.conclusive)throw Error(`cannot list every recorder writing Android artifact: ${n}`);return r.writers.map((e,r)=>({index:t.chunks.length+1+r,remotePath:n,remotePid:e.pid,remoteStartTime:e.startTime}))}function Fn(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:String(e)}}async function In(e){let{transport:t,device:n,envelope:r,descriptor:i}=e;if(i.transportMode!==t.mode)return{status:`transport-unavailable`};let a=await t.readManifest(i.manifestPath);if(a.status===`unavailable`)return{status:`transport-unavailable`};let o=a.status===`read`?O(a.contents):void 0;return o&&zt(o,n,r)&&Bt(o,i)?{status:`matched`,evidence:o}:{status:`ownership-lost`}}async function Ln(e){let t=await e.transport.readManifest(e.manifestPath);if(t.status!==`read`)return;let n=O(t.contents);return n&&Rn(n,e)?n:void 0}function Rn(e,t){return e.deviceId===t.deviceId&&e.sessionId===t.sessionId&&e.fenceToken===t.fence.token&&e.fenceGeneration===t.fence.generation}async function zn(e){let{host:t,transport:n,device:r,input:i}=e,a=E.decode(i.envelope.descriptor.body);if(a.status!==`decoded`)return R(`descriptor-invalid`);let o=await In({transport:n,device:r,envelope:i.envelope,descriptor:a.descriptor});return o.status===`matched`?await Vn({host:t,transport:n,device:r,input:i,descriptor:a.descriptor,evidence:o.evidence}):R(o.status===`transport-unavailable`?`transport-not-reattachable`:`ownership-fence-lost`)}async function Bn(e){let t=E.decode(e.input.envelope.descriptor.body);if(t.status!==`decoded`)return{status:`cleanup-pending`,reason:`manual-recovery-required`};let n=await In({transport:e.transport,device:e.device,envelope:e.input.envelope,descriptor:t.descriptor});return n.status===`matched`?await Nn(e.transport,n.evidence,t.descriptor.manifestPath):n.status===`transport-unavailable`?{status:`cleanup-pending`,reason:`owner-unavailable`}:{status:`cleanup-pending`,reason:`ownership-fence-lost`}}async function Vn(e){let{host:t,transport:n,device:r,input:i,descriptor:a,evidence:o}=e;if(o.completion!==void 0){let e=await Hn(n,o);return e.status===`terminal`?{status:`completed`,result:{...o.completion,nativePathDisposition:e.nativePathDisposition}}:R(`ownership-fence-lost`,`Android recording completed evidence still names a live or unverifiable recorder.`)}if(o.pendingRemotePath!==void 0)return R(`transport-not-reattachable`,`Android recording launch was interrupted before its process identity was committed.`);let s=o.chunks.at(-1);if(!s)return{status:`missing`};let c=await n.inspect({pid:s.remotePid,remotePath:s.remotePath,startTime:s.remoteStartTime});if(c!==`owned-alive`&&await n.exists(s.remotePath)===!1)return R(`transport-not-reattachable`,`Android recording process ended before its artifact could be recovered.`);let l=Un(i.envelope.sessionId,i.envelope.fence,a),u=!1;return{status:`active`,handle:Oe(Sn(l,o.startedAt),{finish:async(e,r)=>{let i=await En({host:t,transport:n,evidence:o,manifestPath:a.manifestPath,recording:e,startedAtMs:o.startedAt,reachedLimit:k(c),progress:r});return u=!0,i},forceCleanup:async()=>u?{status:`cleaned`}:await Bn({transport:n,device:r,input:i})})}}async function Hn(e,t){try{for(let n of t.chunks)if(!k(await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime})))return{status:`retained`};return{status:`terminal`,nativePathDisposition:await Jt(e,t.chunks)}}catch{return{status:`retained`}}}function Un(e,t,n){return{sessionId:e,outputPath:n.outputPath,...n.clientOutputPath===void 0?{}:{clientOutputPath:n.clientOutputPath},scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:!1,recordOnlySession:n.recordOnlySession,...n.activeSessionApp===void 0?{}:{activeSessionApp:n.activeSessionApp},...n.exportQuality===void 0?{}:{exportQuality:n.exportQuality},...n.fps===void 0?{}:{fps:n.fps},fence:t}}function R(e,t){return{status:`unreattachable`,reason:e,...t===void 0?{}:{message:t}}}async function Wn(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.android.resolve(n);return Object.freeze({screenRecordingStart:async e=>await Gn({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await zn({host:t,transport:a,device:n,input:e}),screenRecordingCleanup:async e=>await Bn({transport:a,device:n,input:e})})}async function Gn(e){let{host:t,transport:n,device:i,owner:a,input:o,signal:s}=e;s.throwIfAborted();let c=Date.now(),l=await _n({transport:n,device:i,input:o,startedAt:c,signal:s,prepareOutput:async()=>await t.screenRecording.outputs.prepare(o.outputPath)}),u=l.manifestPath,d=[l.chunk],f,p,m,h=!1,g=()=>{f=setTimeout(()=>{p=ee().catch(e=>{m=e})},17e4),f.unref?.()},ee=async()=>{let e=d.at(-1);if(!e)throw Error(`Android recording has no active chunk`);let t=!1,r;try{r=await bn({transport:n,device:i,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:S.posix.dirname(e.remotePath)})}catch(a){await P(n,e),t=!0;try{r=await bn({transport:n,device:i,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:S.posix.dirname(e.remotePath)})}catch(e){throw e instanceof Error?e:a}}let a=[...d,{...r,index:d.length+1}];try{await F(n,u,D(i,o,c,a,void 0,n.mode))}catch(a){if(await Yt(n,[r]).catch(()=>{}),t)await F(n,u,D(i,o,c,d,r.remotePath,n.mode)).catch(()=>{});else try{await F(n,u,D(i,o,c,d,void 0,n.mode))}catch{await P(n,e).catch(()=>{}),await F(n,u,D(i,o,c,d,r.remotePath,n.mode)).catch(()=>{})}throw a}d=a,t||await P(n,e),g()};g();let te=Oe(Sn(o,c),{finish:async(e,r)=>{if(f&&clearTimeout(f),await p,m)throw m;let a=await En({host:t,transport:n,evidence:D(i,o,c,d,void 0,n.mode),manifestPath:u,recording:e,startedAtMs:l.startedAtMs,progress:r});return h=!0,a},forceCleanup:async()=>{if(f&&clearTimeout(f),h)return{status:`cleaned`};try{await p}catch(e){m=e}let e=await Ln({transport:n,deviceId:i.id,sessionId:o.sessionId,fence:o.fence,manifestPath:u});return e?await Nn(n,e,u):{status:`cleanup-pending`,reason:`ownership-fence-lost`}}});return Object.freeze({pendingHandle:new Se(te),envelope:xe({resourceKind:Pe,sessionId:o.sessionId,device:r(i),owner:a,fence:o.fence,lifecycle:`open`,descriptor:be(E,{backend:`adb-screenrecord`,manifestPath:u,outputPath:o.outputPath,...o.clientOutputPath===void 0?{}:{clientOutputPath:o.clientOutputPath},scope:o.scope,showTouches:o.showTouches,recordOnlySession:o.recordOnlySession,...o.activeSessionApp===void 0?{}:{activeSessionApp:o.activeSessionApp},...o.exportQuality===void 0?{}:{exportQuality:o.exportQuality},...o.fps===void 0?{}:{fps:o.fps},transportMode:n.mode})})})}const Kn=1e3;async function z(e,t,n,r){return r.throwIfAborted(),await We(t)?{...t,booted:!0}:t.kind===`emulator`&&(t.booted!==!0||!B(t))?await qn(e,t,n,r):(t.booted!==!0&&await Zn(e,t.id,$n(e,n),r),{...t,booted:!0})}async function qn(e,t,n,r){await Jn(e);let i=er(n),a=$n(e,n),o=Yn(await e.deviceReadiness.androidEmulator.discover(i,r),t.name,n.serial),s=B(o)?o:void 0,c=s?void 0:e.deviceReadiness.androidEmulator.launch(o.name,n.headless);try{let t=s??await Xn(e,o.name,i,n.serial,a,r);return await Zn(e,t.id,a,r),{...(await e.deviceReadiness.androidEmulator.discover(i,r)).find(e=>e.id===t.id)??t,name:o.name,booted:!0}}catch(t){throw c!==void 0&&r.aborted&&await e.deviceReadiness.androidEmulator.terminate(c),r.throwIfAborted(),t}}async function Jn(e){if(await e.toolchains.prepare(`android`),!await e.commands.which(`adb`))throw new t(`TOOL_MISSING`,`adb not found in PATH`);if(!await e.commands.which(`emulator`))throw new t(`TOOL_MISSING`,`emulator not found in PATH`)}function Yn(e,n,r){let i=tr(e,n,r);if(i)return i;throw new t(`DEVICE_NOT_FOUND`,`No Android emulator AVD named ${n}`,{requestedAvdName:n,availableAvds:e.map(e=>e.name),hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."})}async function Xn(e,t,n,r,i,a){for(;e.clock.now()<i;){let i=tr(await e.deviceReadiness.androidEmulator.discover(n,a),t,r);if(i&&B(i))return i;await e.clock.sleep(Kn,a)}throw Qn(`Android emulator did not appear in time`,{avdName:t,serial:r})}async function Zn(e,t,n,r){for(;e.clock.now()<n;){if((await e.commands.run({executable:`adb`,args:s(`adb`,`shell`,[`getprop`,`sys.boot_completed`],[`-s`,t]),allowFailure:!0,timeoutMs:Math.min(1e4,Math.max(1e3,n-e.clock.now()))},r)).stdout.trim()===`1`)return;await e.clock.sleep(Kn,r)}throw Qn(`Android device failed to finish booting`,{serial:t})}function Qn(e,n){return new t(`COMMAND_FAILED`,e,{...n,reason:Ne,hint:`The emulator keeps booting in the background. Retry once it is up, or pass a larger --timeout.`})}function $n(e,t){return t.deadlineAtMs??e.clock.now()+12e4}function er(e){return{platform:`android`,kind:`emulator`,...e.serial?{serial:e.serial}:{},...e.androidSerialAllowlist?{androidSerialAllowlist:[...e.androidSerialAllowlist]}:{}}}function tr(e,t,n){let r=nr(t);return e.find(e=>e.platform===`android`&&e.kind===`emulator`&&nr(e.name)===r&&(!n||!B(e)||e.id===n))}function B(e){return e.id.startsWith(`emulator-`)}function nr(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}async function rr(e,t,n){try{let r=await e.snapshot({appBundleId:t,signal:n,transient:{settleBy:Date.now()+6e3}});return{observation:`androidSnapshot`in r&&r.androidSnapshot?.systemSurfaceOnly===!0?`unobservable`:`observable`}}catch(e){return n.throwIfAborted(),l(e)?{observation:`unobservable`}:{observation:`probe-failed`,failure:ir(e)}}}function ir(t){let n=e(t),r=c(n)??n.details?.reason,{code:i}=n;return typeof r==`string`?{source:`capture`,code:i,reason:r}:{source:`capture`,code:i}}function ar(e){let{host:t,device:n,signal:r}=e,i=Ke({device:n,signal:r,resolveInteractor:t.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async e=>await t.androidApplications.resolveOpenTarget(n,e),prepareApplicationOpen:async e=>{await z(t,n,{headless:!1,deadlineAtMs:e.execution.startupDeadlineAtMs},r)},openApplication:async e=>await or(t,i,e),applyRuntimeHints:async e=>await t.androidApplications.applyRuntimeHints(n,e),clearRuntimeHints:async e=>await t.androidApplications.clearRuntimeHints(n,e),closeApplication:async e=>{e.ensureReady&&await z(t,n,{headless:!1},r),await qe({device:n,interactor:await i.resolveInteractor(e.execution,e.appBundleId),positionals:e.positionals})},finalizeApplicationClose:async e=>{await t.androidApplications.restoreTestIme(n,{stateDir:e.stateDir,shutdownTarget:e.shutdownTarget===!0&&n.kind===`emulator`,signal:r});let i=e.shutdownTarget&&n.kind===`emulator`?await t.deviceShutdown.android.shutdownTarget(n,r):void 0;return i===void 0?{}:{shutdown:i}},prepareAppleRunner:cr,configureProviderPortReverse:cr})}async function or(e,n,r){let i={};if(r.relaunch&&r.target){let e=Date.now();await qe({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:[r.appBundleId??r.target]}),i.relaunchCloseDurationMs=V(e)}if(p(r.runtimeHints)){if(!r.applyRuntimeHints)throw new t(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});let e=Date.now();await r.applyRuntimeHints({appId:r.appBundleId,values:r.runtimeHints}),i.runtimeHintsDurationMs=V(e)}let a=Date.now();await Je({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:r.positionals,appBundleId:r.appBundleId,execution:r.execution}),i.openDispatchDurationMs=V(a),r.enableTestIme&&await e.androidApplications.activateTestIme(n.device,{stateDir:r.stateDir});let o=Ge(r);if(o){let e=Date.now();await Je({device:n.device,interactor:await n.resolveInteractor({...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},r.appBundleId),positionals:[o],appBundleId:r.appBundleId,execution:{...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}}),i.launchUrlDurationMs=V(e)}else i.launchUrlDurationMs=0;let s=await e.androidApplications.inferOpenedAppBundleId(n.device,r.target,r.appBundleId);s&&await e.androidApplications.resetFramePerfStats(n.device,s);let c=Date.now();return Object.assign(i,await sr(n,r,s)),i.postOpenSettleDurationMs=V(c),{appBundleId:s,timing:i}}async function sr(e,t,r){if(!t.target||n(t.target))return{};if(!r)return{postOpenObservation:`app-unidentified`};let i=await rr(await e.resolveInteractor(t.execution,r),r,e.signal);return i.observation===`probe-failed`?{postOpenObservation:`probe-failed`,postOpenObservationFailure:i.failure}:{postOpenObservation:i.observation}}function V(e){return Math.max(0,Date.now()-e)}async function cr(){throw new t(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Android.`)}async function H(e,t,n,r,i){U(n);let a=r?void 0:await pr(e,t,i);if(S.extname(n).toLowerCase()===`.aab`?await fr(e,t,n,i):G(await e.androidTools.installPackage(t,n,{replace:!0},i),`adb install failed`),r)return r;let o=[...await pr(e,t,i)].filter(e=>!a?.has(e));return o.length===1?o[0]:void 0}function U(e){if(x()&&S.extname(e).toLowerCase()===`.aab`)throw new t(`UNSUPPORTED_OPERATION`,`Managed Android deployment does not support app bundles.`,{reason:`managed-bundle-install-unavailable`,hint:`Install an APK on this managed device.`})}async function lr(e,t,n,r){let i=await W(e,t,[`uninstall`,n],r);if(i.exitCode===0)return;let a=`${i.stdout}\n${i.stderr}`.toLowerCase();a.includes(`unknown package`)||a.includes(`not installed`)||G(i,`adb uninstall failed for ${n}`)}async function ur(e,n,r,i){let a=r.payload,o=typeof a.action==`string`&&a.action.trim()?a.action.trim():`${r.appId}.TEST_PUSH`,c=[`am`,`broadcast`,`-a`,o,`-p`,r.appId];typeof a.receiver==`string`&&a.receiver.trim()&&c.push(`-n`,a.receiver.trim());let l=a.extras??{};if(typeof l!=`object`||!l||Array.isArray(l))throw new t(`INVALID_ARGS`,`Android push payload extras must be an object`);let u=0;for(let[e,t]of Object.entries(l))e&&(mr(c,e,t),u+=1);return G(await W(e,n,s(`adb`,`shell`,c),i),`adb push broadcast failed`),{action:o,extrasCount:u}}function dr(e){let t=new Set([`com`,`android`,`google`,`app`,`apps`,`service`,`services`,`mobile`,`client`]),n=e.split(/[._-]+/).map(e=>e.trim().toLowerCase()).filter(Boolean),r=[...n].reverse().find(e=>!t.has(e))??n.at(-1)??e;return r.charAt(0).toUpperCase()+r.slice(1)}async function fr(e,n,r,i){if(await e.androidTools.installBundle(n,r,`universal`,i))return;let a=await e.commands.which(`bundletool`),o=e.androidDeployment.bundletoolJar;if(!a&&!o)throw new t(`TOOL_MISSING`,`bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR.`);let s=a?`bundletool`:`java`,c=a?[]:[`-jar`,o],l=await e.temporaryFiles.create({prefix:`agent-device-aab-`,suffix:`.apks`}),u=l.path;try{G(await e.commands.run({executable:s,args:[...c,`build-apks`,`--bundle`,r,`--output`,u,`--mode`,`universal`]},i),`bundletool build-apks failed`),G(await e.commands.run({executable:s,args:[...c,`install-apks`,`--apks`,u,`--device-id`,n.id]},i),`bundletool install-apks failed`)}finally{await l[Symbol.asyncDispose]()}}async function pr(e,t,n){let r=await W(e,t,s(`adb`,`shell`,[`pm`,`list`,`packages`]),n);return G(r,`adb package inventory failed`),new Set(r.stdout.split(`
|
|
5
|
-
`).map(e=>e.replace(`package:`,``).trim()).filter(Boolean))}function mr(e,n,r){if(typeof r==`string`)e.push(`--es`,n,r);else if(typeof r==`boolean`)e.push(`--ez`,n,String(r));else if(typeof r==`number`&&Number.isFinite(r))e.push(Number.isInteger(r)?`--ei`:`--ef`,n,String(r));else throw new t(`INVALID_ARGS`,`Unsupported Android broadcast extra type for "${n}". Use string, boolean, or number.`)}async function W(e,t,n,r,i=15e3){return await e.androidTools.runAdb(t,n,{timeoutMs:i,allowFailure:!0},r)}function G(e,n){if(e.exitCode===0)return;let r={stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode};throw new t(`COMMAND_FAILED`,n,r)}const hr=Object.freeze({available:!0});function gr(e){let t=br(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:t})}function _r(e){let{host:t,device:n,signal:r}=e;return gr(n).deployApp.available?Object.freeze({deployApp:async e=>await vr(t,n,e,r),materializeAppSource:async e=>await t.androidDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await yr(t,n,e,r),sendPushNotification:async e=>await ur(t,n,e,r)}):Object.freeze({})}async function vr(e,t,n,r){if(n.replaceExisting)return await e.androidDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i;try{x()&&(i=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!1,signal:r}),U(i.installablePath)),t.booted!==!0&&await z(e,t,{headless:!1},r);let a=await e.androidDeployment.resolveAppPackage(t,n.app);return await lr(e,t,a,r),i??=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!1,signal:r}),await H(e,t,i.installablePath,void 0,r),{packageName:a,launchTarget:a}}finally{await i?.cleanup()}});let i;try{x()&&(i=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!0,signal:r}),U(i.installablePath)),t.booted!==!0&&await z(e,t,{headless:!1},r),i??=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!0,signal:r});let a=await H(e,t,i.installablePath,i.packageName,r);return a?{packageName:a,appName:dr(a),launchTarget:a}:{}}finally{await i?.cleanup()}}async function yr(e,n,r,i){let a=await H(e,n,r.artifact.installablePath,r.artifact.packageName,i);if(!a)throw new t(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return{packageName:a,appName:dr(a),launchTarget:a}}function br(e){return e.kind===`emulator`||e.kind===`device`?hr:Object.freeze({available:!1,reason:`unsupported-device-kind`})}const K=i(`android`),q=Object.freeze({available:!0}),xr=a(`unsupported-device-kind`),J=a(`unsupported-device-kind`,`focus is supported on Android emulators and physical devices.`),Sr=a(`unsupported-device-kind`,`keyboard actions are supported on Android emulators and physical devices.`),Cr=a(`unsupported-platform-leaf`),wr=a(`unsupported-platform-leaf`,`Android has no key event for this system button.`),Tr=a(`unsupported-platform-leaf`,`fold drives the hinge of a foldable iPhone simulator; the Android emulator posture control is not driven by agent-device yet.`),Er=a(`unsupported-device-kind`,`Headless boot is supported only for Android emulators.`),Dr=a(`unsupported-device-kind`,`Android appstate is supported only for Android emulators and devices.`),Or=a(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),kr=a(`unsupported-device-kind`,`open is supported only for Android emulators and devices.`),Ar=a(`unsupported-device-kind`,`close is supported only for Android emulators and devices.`),jr=a(`unsupported-device-kind`,`Runtime hints are supported only for Android emulators and devices.`),Mr=a(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),Nr=a(`unsupported-device-kind`,`shutdown is supported only for Apple simulators and Android emulators.`),Pr=a(`unsupported-device-kind`,`screenshot is supported only for Android emulators and devices.`),Y=a(`unsupported-device-kind`,`snapshot is supported only for Android emulators and devices.`),Fr=a(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),Ir=a(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web).`),Lr=a(`unsupported-platform-leaf`,`the stateless audio page probe is a web-session operation; Android targets use the host capture.`);function Rr(e){let t=zr(e),n=Br(e),r=Vr(e);return m({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:r,clearRuntimeHints:r,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:Or,configureProviderPortReverse:Mr})}function zr(e){return e.kind===`emulator`||e.kind===`device`?q:kr}function Br(e){return e.kind===`emulator`||e.kind===`device`?q:Ar}function Vr(e){return e.kind===`emulator`||e.kind===`device`?q:jr}const X=a(`unsupported-device-kind`,`Gestures are supported on Android emulators and physical devices.`),Hr=a(`unsupported-platform-leaf`,Re),Ur=a(`unsupported-platform-leaf`,Le);function Wr(e,t){return e.kind===`simulator`?X:e.target===`tv`?t:q}function Z(e){return e.kind===`simulator`?X:q}function Q(e){return e.kind===`simulator`?J:q}const $=a(`owner-capability-missing`,Ie),Gr=a(`owner-capability-missing`,`Could not determine whether this Android build supports a shell clipboard: the adb probe did not complete. Retry once the device is reachable.`);async function Kr(e,t){let n=e.androidTools?.probeClipboardShellSupport;return n?await n.call(e.androidTools,t):`probe-failed`}const qr=a(`unsupported-device-kind`,`tv-remote is supported only on Android TV targets.`);function Jr(e){return e.kind!==`simulator`&&e.target===`tv`?q:qr}function Yr(e){let t=nt(e),n=new Map,r=async t=>{if(t.kind===`simulator`)return $;let r=n.get(t.id)??await Kr(e,t);return r!==`probe-failed`&&n.set(t.id,r),r===`supported`?q:r===`unsupported`?$:Gr},i=async e=>{let n=await t.inspectFacts(e),i=gr(e),a=await r(e);return Object.freeze({device:n.device,operations:{...n.operations,...i,appState:e.kind===`simulator`?Dr:q,networkDump:q,screenRecordingStart:q,screenRecordingReattach:q,screenRecordingCleanup:q,...ne({capture:e.kind===`simulator`?Y:q,customActions:Fr,withoutActiveApp:e.kind===`simulator`?Y:q}),...ae({capture:e.kind===`simulator`?Pr:q}),...se({findText:Y}),...g({setViewport:Ir}),...ge({focus:Q(e)}),...ie({unsupported:X,plan:Z(e),directionalFling:Z(e),multiTouch:Wr(e,Hr),targetAuthoredDrag:Wr(e,Ur),viewport:Z(e)}),...oe({scroll:Z(e)}),...h({type:Q(e)}),...ye({unsupported:J,tap:Q(e),longPress:Q(e),hover:Cr,fill:Q(e)}),...te({readTextAtPoint:e.kind===`simulator`?xr:q}),...me({back:Q(e)}),...ce({unsupported:wr,home:Q(e),appSwitcher:Q(e)}),setFoldPose:Tr,...fe({triggerAppEvent:Q(e)}),...de({setSetting:Q(e),readSetting:Q(e)}),...ue({read:Q(e),wait:Q(e),accept:Q(e),dismiss:Q(e)}),...ee({orientation:Q(e)}),...he({tvRemote:Jr(e)}),...pe({unsupported:Sr,status:Q(e),dismiss:Q(e),enter:Q(e)}),...le({unsupported:a.available?$:a,read:a,write:a}),..._e({capture:Ye(e),query:Lr}),...ve({frames:Q(e),memorySample:Q(e),memorySnapshot:Q(e),nativeCapture:Q(e),profileReport:Q(e)}),ensureReady:q,bootTarget:q,bootTargetHeadless:e.kind===`emulator`?q:Er,listApps:q,...Rr(e),shutdownTarget:e.kind===`emulator`?q:Nr}})};return Object.freeze({owner:K,ownsDevice:e=>e.platform===`android`,inspectFacts:i,bind:async n=>{let r=await t.bind(n),a=await i(n.device),s=await Wn({host:e,device:n.device,owner:K,signal:n.scope.signal});return Object.freeze({device:r.device,owner:K,facts:a,operations:Object.freeze({...r.operations,..._r({host:e,device:n.device,signal:n.scope.signal}),...a.operations.appState.available?{appState:async()=>{n.scope.signal.throwIfAborted();let{runAndroidAdb:e}=await import(`./adb.js`).then(e=>e.t);return await Fe(async(t,r)=>await e(n.device,t,{...r,signal:n.scope.signal}),n.scope.signal)}}:{},networkDump:async t=>await at(e,n.device,t,n.scope.signal),...s,...o(a.operations.audioProbeStart,()=>we({host:e.audioProbe.hostCapture,device:n.device,owner:K})),...o(a.operations.perfFrames,()=>Xe({resolveHost:()=>e.perf.android,device:n.device,owner:K})),...Xr(e,n,a),ensureReady:async t=>await z(e,n.device,{...t,headless:!1},n.scope.signal),bootTarget:async t=>await z(e,n.device,{...t,headless:!1},n.scope.signal),...a.operations.bootTargetHeadless.available?{bootTargetHeadless:async t=>await z(e,n.device,{...t,headless:!0},n.scope.signal)}:{},listApps:async e=>{n.scope.signal.throwIfAborted();let{listAndroidApps:t}=await import(`./app-lifecycle.js`).then(e=>e.t);return(await t(e.device,e.filter)).map(e=>({id:e.package,name:e.name}))},...f(ar({host:e,device:n.device,signal:n.scope.signal}),a.operations),...a.operations.shutdownTarget.available?{shutdownTarget:async()=>await e.deviceShutdown.android.shutdownTarget(n.device,n.scope.signal)}:{}}),[Symbol.asyncDispose]:async()=>await r[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}function Xr(e,t,n){let r={device:t.device,signal:t.scope.signal,resolveInteractor:e.localInteractors.resolve};return{...n.operations.captureSnapshot.available?re(r):{},...ze({...r,facts:n.operations,pause:async n=>await e.clock.sleep(n,t.scope.signal)})}}export{Yr as createAndroidPlatformRuntime};
|
|
1
|
+
import{Y as e}from"./sdk-contracts.js";import{n as t}from"./ime-state.js";function n(e){return Object.freeze({canShutdownTarget:r,shutdownTarget:async(t,n)=>await i(e.commands,t,n)})}function r(e){return e.platform===`android`&&e.kind===`emulator`}async function i(n,r,i){if(r.booted===!1)return a();i.throwIfAborted(),await t(r.id,i),i.throwIfAborted();try{let e=await n.run({executable:`adb`,args:[`-s`,r.id,`emu`,`kill`],allowFailure:!0,timeoutMs:15e3},i);i.throwIfAborted();let t=e.exitCode??-1;return{success:t===0,exitCode:t,stdout:e.stdout,stderr:e.stderr}}catch(t){i.throwIfAborted();let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}function a(){return{success:!0,exitCode:0,stdout:``,stderr:``}}export{n as createAndroidShutdownRuntime};
|
package/dist/src/runtime4.js
CHANGED
|
@@ -1 +1,5 @@
|
|
|
1
|
-
import{J as e}from"./sdk-contracts.js";import{n as t}from"./ime-state.js";function n(e){return Object.freeze({canShutdownTarget:r,shutdownTarget:async(t,n)=>await i(e.commands,t,n)})}function r(e){return e.platform===`android`&&e.kind===`emulator`}async function i(n,r,i){if(r.booted===!1)return a();i.throwIfAborted(),await t(r.id,i),i.throwIfAborted();try{let e=await n.run({executable:`adb`,args:[`-s`,r.id,`emu`,`kill`],allowFailure:!0,timeoutMs:15e3},i);i.throwIfAborted();let t=e.exitCode??-1;return{success:t===0,exitCode:t,stdout:e.stdout,stderr:e.stderr}}catch(t){i.throwIfAborted();let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}function a(){return{success:!0,exitCode:0,stdout:``,stderr:``}}export{n as createAndroidShutdownRuntime};
|
|
1
|
+
import{I as e,L as t,P as n,Y as r,q as i}from"./sdk-contracts.js";import{_ as a,f as o}from"./tv-remote.js";import{a as s,i as c,v as l}from"./sdk-batch-runner.js";import{c as u,r as d}from"./diagnostics.js";import"./diagnostics2.js";import{A as f,N as p,f as m,g as h,h as g,l as ee,m as te,x as ne}from"./sdk-device.js";import{$t as re,Yt as ie,en as _,nn as ae,tn as v}from"./sdk-batch.js";import{n as oe,r as se}from"./session.js";import{C as ce,a as le,k as ue,t as de,v as fe}from"./file.js";import{i as pe,o as me,r as y}from"./exec.js";import{t as he}from"./retry.js";import"./command.js";import"./process.js";import{r as ge}from"./version.js";import"./retry2.js";import{i as _e,n as ve,r as ye}from"./ios-snapshot-planning.js";import{t as be}from"./request.js";import{$ as xe,A as Se,C as Ce,E as we,F as Te,H as Ee,I as De,J as Oe,K as ke,M as Ae,N as je,O as Me,Q as Ne,R as Pe,T as Fe,U as Ie,V as Le,W as Re,X as ze,Z as Be,_ as Ve,b as He,c as Ue,i as We,k as Ge,l as Ke,n as qe,p as Je,q as Ye,z as Xe}from"./perf-runtime.js";import{i as Ze,t as Qe}from"./touch-runtime.js";import{n as $e}from"./audio-probe-runtime.js";import{a as et,n as tt}from"./durable-resource.js";import{n as nt,t as rt}from"./async-lifecycle.js";import{a as it,c as at,d as ot,f as st,l as ct,n as lt,o as ut,s as dt,t as ft,u as pt}from"./src3.js";import{n as mt,t as ht}from"./screen-recording-completion.js";import{a as gt,c as _t,i as vt,l as yt,n as bt,o as xt,r as St,s as Ct,t as wt}from"./device-readiness-runtime.js";import{n as Tt}from"./screen-recording-runtime.js";import{t as Et}from"./ios-system-surface.js";import{i as Dt,r as Ot}from"./gesture-admission.js";import{t as kt}from"./interactor-operation-catalog.js";import{a as At,i as jt,n as Mt,r as Nt,t as Pt}from"./perf-runtime-operation-builder.js";import{t as Ft}from"./app-log-runtime.js";import{n as It}from"./artifact-paths.js";import{n as Lt,o as Rt,s as zt}from"./application-lifecycle-interaction.js";import{C as Bt,D as Vt,c as Ht,f as Ut,h as Wt,n as Gt,o as Kt,w as qt,y as Jt}from"./host-file.js";import{a as Yt,o as Xt,s as Zt}from"./config.js";import{a as Qt,o as $t}from"./tool-provider.js";import{o as en}from"./devicectl.js";import{t as tn}from"./physical-device-apps.js";import{t as nn}from"./apple-runner-platform.js";import{a as rn,c as an,n as on,o as sn,s as b,u as cn}from"./simctl.js";import{r as ln}from"./simulator.js";import{r as un}from"./display-inventory.js";import{n as dn,t as fn}from"./app-backend.js";import{t as pn}from"./simulator-state.js";import{createHash as mn,randomUUID as hn}from"node:crypto";import x from"node:path";function gn(e,t){return Object.freeze({appState:async n=>{if(t.signal.throwIfAborted(),!await e.appleApplications.hasLiveRunnerSession(t.device,{}))return{};let r=await t.resolveInteractor(t.device,{appBundleId:n?.appBundleId,signal:t.signal});if(typeof r.appState!=`function`)throw ae(`Runtime owner advertised appState without an interactor implementation`);return await r.appState()}})}function _n(e){return xt(e)?Object.freeze({available:!0}):h(e)||g(e)&&e.kind===`simulator`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`audio probe capture requires a macOS host.`}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`audio is supported for macOS sessions and iOS simulators on macOS hosts; physical iOS devices expose no host audio tap.`})}function vn(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...Pt({platform:`Apple`,expectedProfileKind:`xctrace`,start:async e=>await t().start(n,r,e),reattach:async e=>await t().reattach(n,e),cleanup:async e=>await t().cleanup(n,e),writeProfileReport:async e=>await t().writeProfileReport(e)}),perfFrames:async({appId:e})=>({metric:e?await jt(t().sampleFrames(n,e)):Mt(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await jt(t().sampleMemory(n,e)):Mt(`Apple`,`bundle ID`),sampling:await t().memorySampling(n)}),perfMemorySnapshot:async({appId:e,kind:r,outPath:i,artifactsDir:a})=>{let o=r??`memgraph`,s={...await t().memorySnapshotSupport(n),androidHprof:!1,heapprofd:!1};if(o!==`memgraph`)return At(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw Nt();let c=i??x.join(a,`memory-memgraph-${yn()}.memgraph`);return{artifact:await t().captureMemorySnapshot(n,e,c),support:s,sampling:{method:`xcrun memgraph`,description:`Native Apple memory graph captured for offline inspection.`,defaultKind:`memgraph`,artifactOnly:!0}}}})}function yn(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const S=Object.freeze({available:!0}),C=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),w=Cn(`Gestures are supported only for Apple simulators and devices.`),bn=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:Ot}),xn=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:Dt}),Sn=Cn(`scroll is supported only for Apple simulators and devices.`);function Cn(e){return Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:e})}function wn(e){return{...Pe({unsupported:Tn(e),plan:En(e),directionalFling:En(e),multiTouch:Dn(e),targetAuthoredDrag:On(e),viewport:kn(e)}),...Te({scroll:An(e)})}}function Tn(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?C:w}function En(e){return e.appleOs===`watchos`||e.appleOs===`visionos`?C:T(e)?S:w}function Dn(e){if(e.appleOs===`watchos`)return C;if(!T(e))return w;let t=f(e);if(t!==`ios`&&t!==`ipados`){let e=dn[t];return Object.freeze({available:!1,reason:`unsupported-platform-leaf`,...e===void 0?{}:{hint:e}})}return e.kind===`simulator`?S:bn}function On(e){return T(e)?(e.appleOs===void 0?e.target!==`desktop`&&e.target!==`tv`:e.appleOs===`ios`||e.appleOs===`ipados`)?S:xn:w}function kn(e){return e.appleOs===`watchos`?C:T(e)?S:w}function An(e){return T(e)?S:Sn}function T(e){return e.kind===`simulator`||e.kind===`device`}const E=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function D(e){return h(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const jn=Object.freeze({resourceKind:Ft,version:1,encode:e=>({...e}),decode:e=>!Nn(e.transport)||!Pn(e.backend)||!Rn(e.outputPath)||!In(e.pidPath)||!Fn(e.transport,e.backend)?Mn():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function Mn(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function Nn(e){return e===`apple-log-stream`||e===`coredevice-console`}function Pn(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function Fn(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function In(e){return e===void 0||Rn(e)}function Ln(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return tt({resourceKind:Ft,sessionId:e.sessionId,device:{id:e.device.id,family:`apple`,appleOs:e.device.appleOs,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:et(jn,e.descriptor)})}function Rn(e){return typeof e==`string`&&e.trim().length>0}const zn={message:`iOS physical-device app console capture is not supported by the installed devicectl.`,hint:`This devicectl does not expose process launch --console. Markers can still be written to app.log, but app output is not being captured. Use an iOS simulator for agent-device app logs or inspect physical-device logs in Console.app/Xcode until this Xcode toolchain exposes scriptable console capture.`},Bn={message:`Could not verify iOS physical-device app console capture support.`,hint:`Retry logs clear --restart. If the probe keeps failing, run logs doctor and inspect the request diagnostics for the devicectl help command.`};async function Vn(e,t){try{let n=await e.appleTools.run({tool:`devicectl`,args:[`device`,`process`,`launch`,`--help`],allowFailure:!0,timeoutMs:5e3},t),r=n.stderr.trim()||void 0;if(n.exitCode!==0)return{supported:!1,reason:`probe-failed`,stderr:r};let i=`${n.stdout}\n${n.stderr}`;return/\bUSAGE:\s+devicectl device process launch\b/i.test(i)&&/--console\b/.test(i)&&/--terminate-existing\b/.test(i)?{supported:!0,...r?{stderr:r}:{}}:{supported:!1,reason:`unsupported`,...r?{stderr:r}:{}}}catch(e){if(t?.aborted)throw t.reason;return{supported:!1,reason:`probe-failed`,...e instanceof Error?{stderr:e.message}:{}}}}async function Hn(e,t,n,r){let i={},a=n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`];if(h(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await yt(async()=>_t(await e.appleTools.run({tool:`simctl`,args:an(),allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(E);else{i.devicectlAvailable=await yt(async()=>_t(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await Vn(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?zn:Bn;a.push(`${e.message} ${e.hint}`)}}return{backend:D(t),checks:i,notes:a}}function Un(e,t){let n=Kn(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=Kn(t);r.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return r.join(` OR `)}function Wn(e,t){return on(e,[`spawn`,e.id,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,Un(t.appBundleId,t.executableName)])}function Gn(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function Kn(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}async function qn(e,t,n,r,i){Jn(t),ut(e,n);let a=D(t),o=await Xn(e,t,n.appBundleId,i),s=new rt,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await Yn(e,t,o,l,n.pidPath,i);s.defer(async()=>{c||await u[Symbol.asyncDispose]()});let d=Qn(e,u,l,a,n.outputPath),f={transport:a===`ios-device`?`coredevice-console`:`apple-log-stream`,backend:a,outputPath:n.outputPath,...n.pidPath===void 0?{}:{pidPath:n.pidPath}},p=st(d,Ln({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:f}));return c=!0,p}finally{await s[Symbol.asyncDispose]()}}function Jn(e){if(e.appleOs===`watchos`)throw new n(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(g(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`)throw new n(`UNSUPPORTED_OPERATION`,E,{hint:E})}async function Yn(e,t,r,i,a,o){if(g(t)&&t.kind===`device`){let t=await Vn(e,o);if(!t.supported){let e=t.reason===`unsupported`?zn:Bn;throw new n(t.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,e.message,{backend:`ios-device`,hint:e.hint,stderr:t.stderr})}}return o?.throwIfAborted(),await e.processes.start({command:{kind:`host`,request:r},output:i,...a?{markerPath:a}:{}})}async function Xn(e,t,n,r){return h(t)?{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,Un(n)],allowFailure:!0}:t.kind===`device`?{executable:`xcrun`,args:Gn(t.id,n),allowFailure:!0}:{executable:`xcrun`,args:Wn(t,{appBundleId:n,executableName:await Zn(e,t,n,r)}),allowFailure:!0}}async function Zn(e,t,n,r){let i=await e.appleTools.run({tool:`simctl`,args:b(t,[`get_app_container`,t.id,n,`app`]),allowFailure:!0,timeoutMs:4e3},r),a=i.exitCode===0?i.stdout.trim():``;if(!a)return;let o=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,x.join(a,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return o.exitCode===0&&o.stdout.trim()||void 0}function Qn(e,t,n,r,i){let a=e.clock.now(),o=`active`;t.wait.then(e=>{o=e.exitCode===0?`ended`:`failed`},()=>{o=`failed`});let s;return pt({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await $n([async()=>await t.terminate(),async()=>await t.wait.then(()=>void 0),async()=>await t[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()])).length>0?(o=`failed`,{status:`cleanup-pending`,reason:`transport-failed`,message:`Apple app-log cleanup did not settle every owned resource`}):(o=`ended`,{status:`completed`,result:{backend:r,outputPath:i,completedAt:e.clock.now()}}))()})}async function $n(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const O=ie(`apple`),er=Object.freeze({available:!0});function tr(e){return Object.freeze({owner:O,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>rr(e),bind:async t=>{if(t.intent.kind===`exact-owner`&&!re(t.intent.owner,O))throw new n(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return nr(e,t.device,t.scope.signal)},shutdown:async()=>void 0})}function nr(e,t,r){if(t.platform!==`apple`)throw new n(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${t.platform}`);let i=ot({codec:jn,reattach:async(n,r)=>n.backend!==D(t)||!it(e,r.sessionId,n)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await at(e,n.pidPath),cleanup:async(n,r)=>n.backend===D(t)&&it(e,r.sessionId,n)?await dt(e,n.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`Apple app-log descriptor does not match the bound device or owning session`}}),a=Object.freeze({appLogInspect:async()=>({backend:D(t)}),appLogDoctor:async({appBundleId:n})=>await Hn(e,t,n,r),appLogStart:async n=>await qn(e,t,n,O,r),...i});return Object.freeze({device:t,owner:O,facts:rr(t),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function rr(e){if(e.appleOs===`watchos`)return ir(e);let t=g(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:E}:er;return Object.freeze({device:{family:`apple`,appleOs:e.appleOs,kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:er,appLogCleanup:er}})}function ir(e){let t=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app logs are not supported.`});return Object.freeze({device:{family:`apple`,appleOs:`watchos`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:t,appLogCleanup:t}})}async function ar(e,t,n,r){let i=D(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=lt(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(sr(t,n,o.dump)){let i=await cr(e,t,n,a.path,r);i&&(o=or(s,o,i,n.maxEntries))}return dr(s,t,n),ur(s,o.dump),o.dump.entries.length===0&&s.push(fr(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function or(e,t,n,r){let i=n.scan.dump.entries.length;return i===0&&(n.scan.dump.unnamedRequests??0)===0?(n.lineCount>0&&e.push(`Recovered ${n.lineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`),t):(i>0&&e.push(`Recovered ${i} iOS simulator HTTP entr${i===1?`y`:`ies`} from simctl log show (${n.lineCount} app log lines scanned).`),ft(n.scan,t,r))}function sr(e,t,n){return g(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function cr(e,t,n,r,i){let a=n.appLogSnapshot?.startedAt,o=b(t,[`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,lr(n.appBundleId),...typeof a==`number`&&Number.isFinite(a)&&a>0?[`--start`,`@${Math.floor(a/1e3)}`]:[`--last`,`5m`]]),s=await e.appleTools.run({tool:`simctl`,args:o,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
|
|
2
|
+
`).map(e=>e.trimEnd()).filter(e=>e.trim()&&!e.trim().startsWith(`Timestamp Ty Process[PID:TID]`));if(c.length!==0)return{scan:lt(`${c.join(`
|
|
3
|
+
`)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function lr(e){let t=e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`);return[`subsystem == "${t}"`,`subsystem CONTAINS "${t}"`,`processImagePath ENDSWITH[c] "/${t}"`,`senderImagePath ENDSWITH[c] "/${t}"`].join(` OR `)}function ur(e,t){let n=t.entries.filter(e=>e.pathUnavailable).length,r=t.unnamedRequests??0,i=n+r;if(i===0)return;let a=[`${i} request${i===1?``:`s`} reused a keep-alive connection, so CFNetwork logged no request URL.`];n>0&&a.push(`${n} listed against the origin the connection was opened for, without a path.`),r>0&&a.push(`${r} opened before this scan window and are missing from the entries entirely; scan more lines, or run logs clear --restart before the repro.`),a.push(`Absence of an endpoint in this dump does not prove it was not called.`),e.push(a.join(` `))}function dr(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(g(t)&&t.kind===`simulator`?`Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop.`:`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):e.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`)}function fr(e){return g(e)&&e.kind===`simulator`?`No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.`:g(e)?`No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.`:`No HTTP(s) entries were found in recent session app logs.`}async function pr(t){let{host:n,snapshot:r,targetLabel:i,recorderWarning:a,nativePathDisposition:o}=t,s=r.invalidatedReason?{recorder:`lost`,why:`owner-session-lost`}:t.stopObservation;if(r.invalidatedReason&&!r.showTouches)throw Error(`recording invalidated: ${r.invalidatedReason}`);let c;try{c=await n.screenRecording.finalize.complete({outputPath:r.outPath,showTouches:!r.invalidatedReason&&r.showTouches,gestureEvents:r.gestureEvents,exportQuality:r.exportQuality??`medium`,...r.fps===void 0?{}:{fps:r.fps},targetLabel:i})}catch(t){throw e(t,`COMMAND_FAILED`)}let l=[...c.warning?[c.warning]:[],...a?[a]:[]];return ht(r,{...c,...l.length>0?{warning:l.join(` `)}:{},...r.invalidatedReason?{overlayWarning:`overlay unavailable: ${r.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function mr(e){let{host:t,snapshot:n,targetLabel:r,collectedPath:i,exportPath:a,nativePath:o}=e;if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let s=e.overlayUnavailable??n.invalidatedReason,c;try{await t.screenRecording.outputs.copy({from:i,to:a}),c=await hr(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:s===void 0&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,...n.fps===void 0?{}:{fps:n.fps},targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...c,...s===void 0?{}:{overlayWarning:`overlay unavailable: ${s}`},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function hr(t){try{return await t()}catch(t){throw e(t,`COMMAND_FAILED`)}}const gr=[`outPath`,`startedAt`,`clientOutPath`,...vt],_r=Object.freeze({resourceKind:Tt,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e})),...e.recording===void 0?{}:{recording:{...e.recording}}}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>kr(e)});function vr(e){let{device:t,owner:n,input:r,descriptor:i}=e;return tt({resourceKind:Tt,sessionId:r.sessionId,device:p(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:et(_r,i)})}function yr(e){let t={};for(let n of gr)e[n]!==void 0&&Object.assign(t,{[n]:e[n]});return t}async function br(e,t,n,r){let i=_r.decode(n);return i.status!==`decoded`||!zr(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await xr(e,i.descriptor.processes,r):await Cr(e,t,i.descriptor)}async function xr(e,t,n){let r=await Promise.all(t.map(async t=>await e.screenRecording.apple.inspectProcess(t)));if(r.includes(`ownership-lost`))return{status:`cleanup-pending`,reason:`ownership-fence-lost`};if(r.every(e=>e===`missing`))return n!==void 0&&e.screenRecording.ownedProcesses.clear(Sr(n)),{status:`already-missing`};let i=await Promise.all(t.flatMap((t,n)=>r[n]===`owned-alive`?[e.screenRecording.apple.terminateProcess(t)]:[]));return i.includes(`ownership-lost`)?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(n!==void 0&&e.screenRecording.ownedProcesses.clear(Sr(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function Sr(e){return{kind:`session`,sessionId:e}}async function Cr(e,t,n){try{let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`already-missing`}:r===`ownership-lost`?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(await e.screenRecording.apple.runRunner(t,{kind:`stop`,appBundleId:n.appBundleId,runnerSessionId:n.runnerSessionId,runnerAuthority:n.runnerAuthority}),{status:`cleaned`})}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple recording cleanup failed`}}}async function wr(e){let{host:t,device:n,envelope:r}=e,i=_r.decode(r.descriptor.body);return i.status===`decoded`?zr(n,i.descriptor)?i.descriptor.backend===`simctl`?await Tr(e,i.descriptor):await Dr(t,n,i.descriptor):k(`descriptor-invalid`,`Apple screen-recording descriptor does not match the bound device.`):k(`descriptor-invalid`,i.message)}async function Tr(e,t){let n=await Promise.all(t.processes.map(async t=>await e.host.screenRecording.apple.inspectProcess(t)));if(!n.every(e=>e===`missing`))return k(`transport-not-reattachable`,n.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`);let{recording:r}=t,i=Er(St(e.envelope.metadata),t.outputPath);return r===void 0||i!==void 0&&!await Or(e.host,i)?{status:`missing`}:{status:`restore-export`,recording:r,nativePath:t.outputPath,cleanup:async()=>await xr(e.host,t.processes,e.envelope.sessionId)}}function Er(e,t){if(e.finalization===void 0)return e.collectedPath??t}async function Dr(e,t,n){let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`missing`}:k(`transport-not-reattachable`,r===`ownership-lost`?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`)}async function Or(e,t){try{return await e.screenRecording.finalize.sniff({outputPath:t}),!0}catch{return!1}}function k(e,t){return{status:`unreattachable`,reason:e,message:t}}function kr(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?j():e.backend===`simctl`?Ar(e,e.outputPath):e.backend===`runner`?Nr(e,e.outputPath):j()}function Ar(e,t){let n=Br(e.processes),r=jr(e.recording);return!n||r===`invalid`?j():{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n,...r===void 0?{}:{recording:r}})}}function jr(e){if(e!==void 0)return l(e)&&Mr(e)?Object.freeze(e):`invalid`}function Mr(e){return A(e.outPath)&&Fr(e.startedAt)&&Pr(e.clientOutPath)&>(e)}function Nr(e,t){return!A(e.appBundleId)||!A(e.runnerSessionId)||!Ir(e.runnerAuthority)||!Lr(e.remotePath)?j():{status:`decoded`,descriptor:Object.freeze({backend:`runner`,outputPath:t,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}})}}function A(e){return typeof e==`string`&&e.length>0}function Pr(e){return e===void 0||A(e)}function Fr(e){return typeof e==`number`&&Number.isFinite(e)}function Ir(e){return e===`local-lease`||e===`scoped-provider`}function Lr(e){return e===void 0||Rr(e)}function Rr(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function zr(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:g(e)?t.remotePath!==void 0&&Rr(t.remotePath):t.remotePath===void 0:!1}function Br(e){if(!Array.isArray(e)||e.length===0)return;let t=e.filter(e=>typeof e==`object`&&!!e&&Number.isInteger(e.pid)&&(e.pid??0)>0&&typeof e.startTime==`string`&&e.startTime.length>0&&typeof e.command==`string`&&e.command.length>0);return t.length===e.length?Object.freeze([...t]):void 0}function j(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function Vr(e,t,n){if(e.kind!==`simulator`||t.scope!==`app`)return;let r=t.activeSessionApp?.bundleId;if(!r)throw TypeError(`App-scoped recording requires an active app session; open the app under test before recording.`);if(await n(r))throw TypeError(`App-scoped recording requires a real application session; open the app under test before recording.`)}const Hr=`iOS recording`,Ur=`simctl recordVideo`;function Wr(e){return e.appleOs===`watchos`?_(`unsupported-platform-leaf`,`watchOS recording is not supported.`):g(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?_(`unsupported-device-backend`,`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`):Object.freeze({available:!0})}function Gr(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Kr({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>{let r=await wr({host:t,device:n,envelope:e.envelope});return r.status===`restore-export`?{status:`active`,handle:Jr({host:t,restored:r})}:r},screenRecordingCleanup:async e=>await br(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function Kr(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await qr(e):await Xr(e)}async function qr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await Vr(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0,s=It(i.outputPath);await t.screenRecording.outputs.prepare(s);let c=await t.screenRecording.apple.startSimulator(n,s,a),l=c.markers;if(!l||l.length===0)throw await ti(c).catch(()=>{}),Error(`simctl recordVideo did not expose durable process identity`);try{a.throwIfAborted(),t.screenRecording.ownedProcesses.replace({kind:`session`,sessionId:i.sessionId},l.map(e=>({...e,purpose:`simctl-screen-recording`})))}catch(e){try{t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId})}catch{}throw await ti(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=Qr(e),t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),{observation:{recorder:`confirmed`},...u===void 0?{}:{warning:`${u} before record stop; the video covers only what the recorder wrote before it stopped.`}}},p=ii(i,Ur,{},o);return ri({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l,recording:yr(p)},snapshot:p,finish:(e,n)=>bt({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await Yr(t,s,e)}catch(e){throw $r(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await mr({host:t,snapshot:e,targetLabel:Hr,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw $r(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await ni(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}function Jr(e){let{host:t,restored:{recording:n,nativePath:r,cleanup:i}}=e,a=Object.freeze({...n,backend:Ur,gestureEvents:[]});return mt(a,{finish:(e,i)=>bt({snapshot:e,progress:i,steps:{stop:async()=>({observation:{recorder:`confirmed`},warning:`simctl recordVideo had already ended when record stop reattached to it; the video covers only what the recorder wrote before it stopped.`}),collect:async e=>{await Yr(t,r,e)},finalize:async({collectedPath:i,exportPath:a})=>await mr({host:t,snapshot:e,targetLabel:Hr,collectedPath:i,exportPath:a,nativePath:r,...n.showTouches?{overlayUnavailable:`the daemon that held the touch events ended before record stop`}:{}}),discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),forceCleanup:async()=>await i()})}async function Yr(e,t,n){await e.screenRecording.outputs.copy({from:t,to:n}),await e.screenRecording.finalize.sniff({outputPath:n})}async function Xr(e){let{host:t,device:n,owner:r,input:i,signal:a}=e,o=i.activeSessionApp?.bundleId;if(!o)throw TypeError(`Apple runner recording requires an active app session identity`);await t.screenRecording.outputs.prepare(i.outputPath);let s=await t.screenRecording.apple.runRunner(n,{kind:`start`,appBundleId:o,outputPath:i.outputPath,...i.fps===void 0?{}:{fps:i.fps}},a);if(!s.runnerSessionId||!s.runnerAuthority)throw Error(`Apple runner recording did not expose durable session ownership`);let c={runnerSessionId:s.runnerSessionId,runnerAuthority:s.runnerAuthority},l,u=()=>(l??=Zr(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!ei(n,s.remotePath))throw await u().catch(()=>{}),Error(`Apple runner recording did not expose coherent durable media ownership`);try{a.throwIfAborted()}catch(e){throw await u().catch(()=>{}),e}return ri({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:ii(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await pr({host:t,snapshot:e,targetLabel:n.appleOs===`macos`?`macOS recording`:`iOS recording`,stopObservation:{recorder:`confirmed`},...s.remotePath===void 0?{}:{nativePathDisposition:`retirable`}})),cleanup:async()=>(await u(),{status:`cleaned`})})}async function Zr(t){try{return await t()}catch(t){throw e(t,`COMMAND_FAILED`)}}function Qr(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function $r(t,r,i){let a=e(t,`COMMAND_FAILED`);return r===void 0||i===void 0||a.details?.reason!==`recording-output-unplayable`?t:new n(a.code,`${a.message}; ${r}`,y(i,{...a.details??{},...i.signal===void 0?{}:{signal:i.signal},retriable:!1,hint:`The recorder exited before record stop, so the next record stop reads the same file. Close this session to release the device, then record again.`}))}function ei(e,t){return e.appleOs===`macos`||!g(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function ti(e){return await e.terminate(),await e.wait}async function ni(e){try{return await ti(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function ri(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=mt(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new nt(c),envelope:vr({device:t,owner:n,input:r,descriptor:i})})}function ii(e,t,n={},r){let i=Date.now();return Object.freeze({backend:t,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:i,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},...e.fps===void 0?{}:{fps:e.fps},gestureEvents:[],...r===void 0?{}:{gestureClockOriginAtMs:r.wallClockAtMs,gestureClockOriginUptimeMs:r.uptimeMs},...n.recorderStartUptimeMs===void 0?{}:{gestureClockOriginAtMs:i,gestureClockOriginUptimeMs:n.recorderStartUptimeMs,runnerStartedAtUptimeMs:n.recorderStartUptimeMs},...n.runnerSessionId===void 0?{}:{runnerSessionId:n.runnerSessionId}})}const ai=15e3;async function M(e,t,n,r={}){return n.throwIfAborted(),h(t)?{...t,booted:!0}:t.kind===`device`?(await e.deviceReadiness.applePhysical.ensureConnected(t,n),{...t,booted:!0}):t.kind===`simulator`?((await oi(e,t)?`Booted`:await fi(e,t,n))!==`Booted`&&(r.onColdBootStart?.(),e.deviceReadiness.appleAutomation.keepHot(t),await si(e,t,n,r.deadlineAtMs),await pi(e,n)),e.deviceReadiness.appleAutomation.keepHot(t),e.deviceReadiness.appleAutomation.markBooted(t),{...t,booted:!0}):{...t,booted:!0}}async function oi(e,t){try{return await e.deviceReadiness.appleAutomation.wasRecentlyObservedBooted(t)}catch{return!1}}async function si(e,t,n,r=Date.now()+12e4){let i=!1;try{i=await ci(e,t,n,r),await li(e,t,n,r)}catch(a){throw i&&n.aborted&&mi(e,t),n.throwIfAborted(),Date.now()>=r?di(t,a):a}}async function ci(e,t,r,i){let a=await e.appleTools.run({tool:`simctl`,args:b(t,[`boot`,t.id]),allowFailure:!0,timeoutMs:ui(i,t)},r),o=`${a.stdout}\n${a.stderr}`.toLowerCase(),s=o.includes(`already booted`)||o.includes(`current state: booted`);if(a.exitCode!==0&&!s)throw new n(`COMMAND_FAILED`,`simctl boot failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return!s}async function li(e,t,r,i){be({type:`command`,status:`progress`,message:`Waiting for the Simulator to finish booting...`});let a=await e.appleTools.run({tool:`simctl`,args:b(t,[`bootstatus`,t.id,`-b`]),allowFailure:!0,timeoutMs:ui(i,t)},r);if(a.exitCode!==0)throw new n(`COMMAND_FAILED`,`simctl bootstatus failed`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});if(await pn(e.appleTools,t,r,Math.min(ai,ui(i,t)))!==`Booted`)throw new n(`COMMAND_FAILED`,`Simulator is still booting`,{deviceId:t.id});if(Date.now()>=i)throw di(t)}function ui(e,t){let n=e-Date.now();if(n<=0)throw di(t);return n}function di(e,t){return new n(`COMMAND_FAILED`,`Simulator did not finish booting within the startup budget`,{reason:wt,deviceId:e.id,hint:`The Simulator keeps booting in the background; a first boot can take several minutes. Retry once it is up, or pass a larger --timeout.`},t instanceof Error?t:void 0)}async function fi(e,t,n){return await pn(e.appleTools,t,n,ai)}async function pi(e,t){await e.commands.run({executable:`open`,args:[`-a`,`Simulator`],allowFailure:!0,timeoutMs:1e4},t)}function mi(e,t){e.appleTools.run({tool:`simctl`,args:b(t,[`shutdown`,t.id]),allowFailure:!0}).catch(()=>{})}const hi=Object.freeze({resolveOpenTarget:`simulator`,prepareApplicationOpen:`simulator`,openApplication:`simulator`,applyRuntimeHints:`simulator`,clearRuntimeHints:`simulator`,closeApplication:`simulator`,finalizeApplicationClose:`simulator`,prepareAppleRunner:`runner`,configureProviderPortReverse:`simulator`,ensureReady:`simulator`,bootTarget:`simulator`,bootTargetHeadless:`simulator`,shutdownTarget:`simulator`,listApps:`simulator`,deployApp:`simulator`,materializeAppSource:`simulator`,deployMaterializedApp:`simulator`,sendPushNotification:`simulator`,appState:`simulator`,appLogStart:`simulator`,appLogInspect:`simulator`,appLogDoctor:`simulator`,appLogReattach:`simulator`,appLogCleanup:`simulator`,networkDump:`simulator`,audioProbeStart:`simulator`,audioProbeQuery:`simulator`,audioProbeReattach:`simulator`,audioProbeCleanup:`simulator`,readClipboard:`simulator`,writeClipboard:`runner`,setSetting:`simulator`,readSetting:`simulator`,setFoldPose:`simulator`,captureSnapshot:`simulator`,captureSnapshotWithoutActiveApp:`simulator`,captureSnapshotWithCustomActions:`runner`,captureScreenshot:`simulator`,findText:`runner`,readTextAtPoint:`runner`,tapPoint:`runner`,tapRef:`runner`,tapElementSelector:`runner`,fillPoint:`runner`,fillRef:`runner`,longPressPoint:`runner`,hoverPoint:`runner`,hoverRef:`runner`,focusPoint:`runner`,typeText:`runner`,scrollDirection:`runner`,performGesturePlan:`runner`,performMultiTouchGesturePlan:`runner`,performTargetAuthoredDrag:`runner`,performDirectionalFlingPlan:`runner`,gestureViewport:`runner`,setViewport:`runner`,back:`runner`,home:`runner`,setOrientation:`runner`,appSwitcher:`runner`,actionButton:`runner`,tvRemote:`runner`,keyboardDismiss:`runner`,keyboardEnter:`runner`,keyboardStatus:`runner`,triggerAppEvent:`runner`,readAlert:`runner`,awaitAlert:`runner`,acceptAlert:`runner`,dismissAlert:`runner`,perfFrames:`runner`,perfMemorySample:`runner`,perfMemorySnapshot:`runner`,perfNativeCaptureStart:`runner`,perfNativeCaptureReattach:`runner`,perfNativeCaptureCleanup:`runner`,perfProfileReport:`runner`,screenRecordingStart:`runner`,screenRecordingReattach:`runner`,screenRecordingCleanup:`runner`});function gi(e){return e===void 0?`possible`:e.some(e=>hi[e]===`runner`)?`required`:`none`}function _i(e){let{waitMs:t,signal:n,stop:r,cancelled:i}=e;return new Promise((e,a)=>{let o=()=>l(()=>a(i())),s=()=>l(e),c=setTimeout(()=>l(e),t);function l(e){clearTimeout(c),n?.removeEventListener(`abort`,o),r?.removeEventListener(`abort`,s),e()}n?.addEventListener(`abort`,o,{once:!0}),r?.addEventListener(`abort`,s,{once:!0}),n?.aborted?o():r?.aborted&&s()})}function vi(e){let t=e.now??Date.now,n=e.waitGrant??`every-caller`,r=new Map,i=(n,i)=>{let a={status:`pending`,value:void 0,error:void 0,settledAtMs:t(),waitSpent:!1,controller:new AbortController,settled:void 0},o=()=>{};a.settled=new Promise(e=>{o=e}),r.set(n,a);let s=(i,s)=>{a.status=i,i===`ready`?a.value=s:a.error=s,a.settledAtMs=t(),(i===`ready`||e.retryAfterMs===void 0)&&r.get(n)===a&&r.delete(n),o()};try{i(a.controller.signal).then(e=>s(`ready`,e),e=>s(`failed`,e))}catch(e){s(`failed`,e)}return a},a=(n,a)=>{let o=r.get(n);if(!o)return i(n,a);if(o.status!==`failed`)return o;let s=t()-o.settledAtMs;return e.retryAfterMs===void 0||s>=e.retryAfterMs?i(n,a):o};return{value:async(t,r)=>{let i=a(t,r.start);if(i.status===`pending`&&(n===`every-caller`||!i.waitSpent)){i.waitSpent=!0;let t=new AbortController,n=r.wait(e.waitMs,t.signal);n.catch(()=>{});try{await Promise.race([i.settled,n])}finally{t.abort()}}if(i.status===`ready`)return i.value;throw i.status===`failed`?i.error:r.pending()},close:()=>{let e=[...r.values()];r.clear();for(let t of e)t.controller.abort()}}}async function yi(e,t){let n=await Qt(`ps`,[`-p`,String(e),`-o`,`lstart=`],{allowFailure:!0,signal:t.signal,timeoutMs:t.timeoutMs});return n.exitCode===0&&n.stdout.trim()||null}const bi=3e3,xi=`simulator-target-discovery-pending`,Si=`simulator-target-unavailable`;function Ci(){let e=new Map,t=new Map,n=vi({waitMs:1500});return async(r,i,a,o)=>{a.throwIfAborted();let s=`${r.id}:${i}`,c=e.get(s);if(c&&o!==`refresh`){let e=await yi(c.pid,{signal:a,timeoutMs:bi});if(a.throwIfAborted(),e===c.processStartTime)return c}return e.delete(s),await n.value(s,{start:async()=>{let n=await Di(r,i,t);return e.set(s,n),n},wait:(e,t)=>_i({waitMs:e,signal:a,stop:t,cancelled:()=>wi(a)}),pending:()=>N(xi,r,i)})}}function wi(e){return t({readinessPhase:`target-discovery`},e.reason)}function Ti(e){return e instanceof n&&e.details?.reason===xi}function Ei(e){return e instanceof n&&e.details?.reason===Si}async function Di(e,t,n){let r=Date.now()+15e3,[i,a]=await Promise.allSettled([sn(e,[`spawn`,e.id,`launchctl`,`list`],{allowFailure:!0,timeoutMs:Ai(r)}),Oi(e,n,r)]);if(i.status===`rejected`)throw i.reason;if(a.status===`rejected`)throw a.reason;let o=i.value,s=a.value;if(o.exitCode!==0)throw N(`simulator-target-probe-failed`,e,t);let c=ki(o.stdout,t);if(!c)throw N(Si,e,t);let l=await yi(c.pid,{timeoutMs:Math.min(bi,Ai(r))});if(!l)throw N(`simulator-target-identity-unavailable`,e,t);return Object.freeze({simulator:cn(e),runtime:s,pid:c.pid,generation:`${c.pid}:${c.label}:${l}`,targetId:`${e.id}:${t}`,processStartTime:l})}async function Oi(e,t,n){let r=t.get(e.id);if(r)return await r;let i=sn(e,[`list`,`devices`,`-j`],{allowFailure:!0,timeoutMs:Ai(n)}).then(t=>{if(t.exitCode!==0)throw N(`simulator-runtime-probe-failed`,e,``);let n=Object.entries(rn(t.stdout)).find(([,t])=>t.some(t=>t.udid===e.id))?.[0];if(!n)throw N(`simulator-runtime-unavailable`,e,``);return n});t.set(e.id,i);try{return await i}catch(n){throw t.delete(e.id),n}}function ki(e,t){for(let n of e.split(`
|
|
4
|
+
`)){let[e,,r]=n.trim().split(/\s+/);if(!e||!r||!r.startsWith(`UIKitApplication:${t}[`))continue;let i=Number(e);if(Number.isSafeInteger(i)&&i>0)return{pid:i,label:r}}}function Ai(e){return Math.max(1,e-Date.now())}function N(e,t,r){return new n(`COMMAND_FAILED`,`Unable to resolve the running iOS Simulator app (${e}).`,{reason:e,deviceId:t.id,appBundleId:r})}function ji(e){return e?.observation===`unobservable`&&e.proof===`no-running-process`}const Mi=new Map([[`application-element-missing`,5e3],[`application-server-unavailable`,5e3],[`foreground-owner-unverified`,1e3],[`foreground-owner-changed`,1e3]]);function P(e){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`}function Ni(e){let t=_e(ye({depth:1,interactiveOnly:!0}));return Object.freeze({awaitObservable:async(n,r,i)=>{if(!P(n))return{observation:`not-eligible`};let a;for(;;){let o=await Fi(e.resolveTarget,n,r,i);if(`verdict`in o)return o.verdict;let{target:s}=o;if(e.isBridgeDisabled(s))return d({level:`debug`,phase:`ios_launch_observation_skipped`,data:{reason:`circuit-disabled`,deviceId:n.id,generation:s.generation}}),Pi({source:`circuit`});let c=await e.source.acquire({target:s,hint:t,signal:i});if(c.stage!==`failed`)return{observation:`observable`};i.throwIfAborted();let{kind:l,code:u}=c.failure,f=Mi.get(u);if(f===void 0)return Pi({source:`bridge`,kind:l,code:u});let p=e.clock.now();if(a=Math.min(a??1/0,p+f),p>=a)return{observation:`unobservable`,proof:`launch-transition`};await e.clock.sleep(Math.min(150,a-p),i)}}})}function Pi(e){return{observation:`probe-failed`,failure:e}}async function Fi(e,t,n,i){for(;;)try{return{target:await e(t,n,i)}}catch(e){if(i.throwIfAborted(),Ti(e))continue;if(Ei(e))return{verdict:{observation:`unobservable`,proof:`no-running-process`}};let{code:t,details:n}=r(e),a=n?.reason;return{verdict:Pi(typeof a==`string`?{source:`target`,code:t,reason:a}:{source:`target`,code:t})}}}function Ii(e,t,n){let r=n&&P(e),i=r?gi(t.execution.plannedOperations):void 0,a=g(e)&&t.surface===`app`&&t.positionals.length>0&&!!t.appBundleId&&i!==`none`;return{...i?{runnerDemand:i}:{},shouldPrewarmRunner:a,awaitPrewarmAfterOpen:t.relaunch&&!r}}function Li(e,t,n,r){r.runnerDemand===`none`&&e.appleApplications.releaseSpeculativeRunner(t.device,n.execution).catch(()=>{})}async function Ri(e,t,r,i,a,o){let s=Date.now(),c=async()=>await Ui(t,r,i,a.observation),l=await c(),u,d=a.answerConfirmation,f=d&&l?.observation!==`observable`?await zi(d,a.redispatchLaunchUrl,c,l):void 0;if(f&&(o.runnerDemand=`required`,u=f.launchConfirmation,l=f.observed,f.unanswered))throw new n(`COMMAND_FAILED`,`The Simulator has not completed the launch URL for ${r.appBundleId}.`,{reason:`launch_confirmation_unanswered`,appBundleId:r.appBundleId,hint:`iOS may still be holding an "Open in" prompt, or the answer died with the runner session that raised it. Inspect the current alert before deciding on another action.`});return i&&l?.observation!==`observable`&&await e.clock.sleep(300,t.signal),l&&(o.postOpenObservation=l.observation,l.observation===`probe-failed`&&(o.postOpenObservationFailure=l.failure)),o.postOpenSettleDurationMs=Math.max(0,Date.now()-s),u}async function zi(e,t,n,r){let i={observed:r,acceptAttempted:!1,confirmationStillPresent:!1};for(let r=0;r<2;r+=1){i=await Bi(e,n,i);let a=r===1;if(i.confirmationStillPresent||a||!Vi(i)||!t)break;await t()}return{observed:i.observed,launchConfirmation:i.launchConfirmation,unanswered:Vi(i)||i.confirmationStillPresent}}async function Bi(e,t,n){let r=await e(),i=r.outcome===`unanswered`&&r.reason===`alert-still-present`,a=n.acceptAttempted||Hi(r),o=r.outcome===`accepted`?`accepted`:n.launchConfirmation;return a?{observed:await t(),launchConfirmation:o,acceptAttempted:a,confirmationStillPresent:i}:{observed:n.observed,launchConfirmation:o,acceptAttempted:a,confirmationStillPresent:i}}function Vi(e){return e.acceptAttempted&&ji(e.observed)}function Hi(e){return e.outcome===`accepted`||e.outcome===`unanswered`&&e.reason===`alert-still-present`||e.outcome===`unreadable`&&e.step===`alert-accept`}async function Ui(e,t,n,r){if(!(!n||!P(e.device))&&!(!r||!t.appBundleId))return await r.awaitObservable(e.device,t.appBundleId,e.signal)}let Wi;const Gi=()=>Wi??=import(`./launch-confirmation.js`);let Ki;const qi=()=>Ki??=import(`./expo-dev-client-launch.js`);function Ji(e){let t=Lt({device:e.device,signal:e.signal,resolveInteractor:e.host.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async t=>await e.host.appleApplications.resolveOpenTarget(e.device,t),prepareApplicationOpen:async t=>{await M(e.host,e.device,e.signal,{deadlineAtMs:t.execution.startupDeadlineAtMs,onColdBootStart:t.prewarmRunnerOnColdBoot?()=>{e.host.appleApplications.prewarmRunnerCache(e.device,t.execution,e.signal).catch(()=>{})}:void 0})},openApplication:async n=>await Yi(e.host,t,n,e.observation),applyRuntimeHints:async t=>await e.host.appleApplications.applyRuntimeHints(e.device,t),clearRuntimeHints:async t=>await e.host.appleApplications.clearRuntimeHints(e.device,t),closeApplication:async n=>await ca(e.host,t,n),finalizeApplicationClose:async t=>await la(e.host,e.device,e.signal,t),prepareAppleRunner:async t=>await ua(e.host,e.device,e.signal,t),configureProviderPortReverse:ga})}async function Yi(e,t,n,r){let i={},a=F(t.device),o=da(e,t,n,i),s=Ii(t.device,n,a);s.runnerDemand&&(i.runnerDemand=s.runnerDemand),Li(e,t,n,s);let{shouldPrewarmRunner:c}=s,l=sa(t.device,n,a);a&&c&&!n.prewarmRunnerBeforeOpen&&o.schedule();try{await Xi(e,t,n,a,l,i);let u=await Zi(t,n,a,i),d=pa(t.device,u?{...n,runtimeLaunchUrl:u}:n,a);await Qi(o,c,n.prewarmRunnerBeforeOpen);let f=o.wasAwaited();await $i(t,n,d,a,i),await ia(o,c,s.awaitPrewarmAfterOpen),await aa(e,t,n,a,f,l);let p=await Ri(e,t,n,a,{observation:r,answerConfirmation:na(t,n,d),redispatchLaunchUrl:ra(t,n,d)},i);return{appBundleId:n.appBundleId,timing:i,...p?{launchConfirmation:p}:{}}}catch(n){throw l&&await e.appleApplications.stopRunnerSession(t.device.id).catch(()=>{}),n}}async function Xi(e,t,n,r,i,a){if(!oa(n,r)||!n.target)return;let o=Date.now();m(t.device.platform)&&!r&&!i&&await e.appleApplications.stopRunnerSession(t.device.id),await Rt({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:[n.appBundleId??n.target]}),r&&await e.clock.sleep(300,t.signal),a.relaunchCloseDurationMs=I(o)}async function Zi(e,t,r,i){if(!xe(t.runtimeHints))return;let a=Date.now(),o=r?await(await qi()).resolveExpoDevClientLaunchUrl(e.device,t):void 0;if(!o){if(!t.applyRuntimeHints)throw new n(`COMMAND_FAILED`,`Runtime hint operation was not admitted for this open.`,{reason:`runtime-hints-operation-missing`});await t.applyRuntimeHints({appId:t.appBundleId,values:t.runtimeHints})}return i.runtimeHintsDurationMs=I(a),o}async function Qi(e,t,n){!t||!n||(e.schedule(!0),await e.wait())}async function $i(e,t,n,r,i){let a=Date.now();await zt({device:e.device,interactor:await e.resolveInteractor(t.execution,t.appBundleId),positionals:n.positionals,appBundleId:t.appBundleId,execution:t.execution,...r&&t.relaunch&&!t.execution.clearAppState?{terminateRunningApp:!0}:{}}),i.openDispatchDurationMs=I(a),await ea(e,t,n.followUpUrl,i)}async function ea(e,t,n,r){if(!n){r.launchUrlDurationMs=0;return}let i=Date.now();await ta(e,t,n),r.launchUrlDurationMs=I(i)}async function ta(e,t,n){let r={...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0};await zt({device:e.device,interactor:await e.resolveInteractor(r,t.appBundleId),positionals:[n],appBundleId:t.appBundleId,execution:r})}function na(e,t,{confirmation:n}){if(n)return async()=>{let{answerSimulatorLaunchConfirmation:r}=await Gi();return await r(e.device,n,e.resolveInteractor(t.execution,n.appBundleId),e.signal)}}function ra(e,t,{confirmation:n}){if(n)return async()=>{await ta(e,t,n.url)}}async function ia(e,t,n){t&&!e.wasScheduled()&&e.schedule(),n?await e.wait():e.recordUnawaited()}async function aa(e,t,n,r,i,a){!g(t.device)||!r&&!a||!n.relaunch&&!i||r&&!i&&!await e.appleApplications.hasLiveRunnerSession(t.device,n.execution)||await e.appleApplications.notifyRunnerAppRelaunched(t.device,n.execution,t.signal)}function oa(e,t){return!!(e.relaunch&&e.target)&&!(t&&!e.execution.clearAppState)}function sa(e,t,n){return e.kind===`device`&&e.appleOs===`ios`&&oa(t,n)}async function ca(e,t,n){n.ensureReady&&await M(e,t.device,t.signal),m(t.device.platform)&&!F(t.device)&&await e.appleApplications.stopRunnerSession(t.device.id),await Rt({device:t.device,interactor:await t.resolveInteractor(n.execution,n.appBundleId),positionals:n.positionals}),F(t.device)&&await e.clock.sleep(300,t.signal)}async function la(e,t,n,r){r.daemonShutdown||await e.appleApplications.releaseRunnerOnClose(t.id,{retain:r.retainRunner}),await e.appleApplications.dismissCloseAlerts(t,r).catch(()=>{});let i=r.shutdownTarget&&F(t)?await e.deviceShutdown.apple.shutdownTarget(t,n):void 0;return i===void 0?{}:{shutdown:i}}async function ua(e,t,n,r){let i=Date.now()+r.timeoutMs;await M(e,t,n,{deadlineAtMs:i});let a=Math.max(1,i-Date.now());return await e.appleApplications.prepareRunner(t,{...r,timeoutMs:a},n)}function da(e,t,n,r){let i,a=!1,o=fa(t.device,n)?{healthCheck:!1}:void 0;return{schedule:(a=!1)=>{i||=(r.runnerPrewarmKind=`session`,r.runnerPrewarmScheduled=!0,o?e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a,o):e.appleApplications.prewarmRunnerSession(t.device,n.execution,t.signal,a))},wait:async()=>{if(!i||a)return;a=!0;let e=Date.now();await i,r.runnerPrewarmWaited=!0,r.runnerPrewarmDurationMs=I(e)},wasAwaited:()=>a,wasScheduled:()=>i!==void 0,recordUnawaited:()=>{i&&!a&&(r.runnerPrewarmWaited=!1)}}}function fa(e,t){return e.kind===`device`&&e.appleOs===`ios`&&!t.hasExistingSession&&!t.relaunch&&!t.prewarmRunnerBeforeOpen}function pa(e,t,n){let r=t.runtimeLaunchUrl?.trim(),i=t.positionals.length===1?t.positionals[0]?.trim():void 0;if(!r||!i||c(i))return{positionals:t.positionals};let a=ma(e,t.appBundleId,r),o=a?{confirmation:a}:{};return n&&!ha(t)?{positionals:[i,r],...o}:{positionals:t.positionals,followUpUrl:r,...o}}function ma(e,t,n){if(e.appleOs===`ios`&&e.kind===`simulator`&&!(t===void 0||s(n)))return{url:n,appBundleId:t}}function ha(e){return e.execution.clearAppState===!0||!!e.execution.launchConsole?.trim()||!!e.execution.launchArgs?.length}function F(e){return g(e)&&e.kind===`simulator`}function I(e){return Math.max(0,Date.now()-e)}async function ga(){throw new n(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Apple.`)}const _a=Object.freeze({available:!0}),va=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`}),ya=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Push notifications are supported on Apple simulators only.`}),ba=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),xa=Object.freeze({available:!1,reason:`unsupported-device-kind`});function Sa(e){let t=Aa(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:ja(e)})}function Ca(e){let{host:t,device:n,signal:r}=e,i=Sa(n);return Object.freeze({...i.deployApp.available?{deployApp:async e=>await wa(t,n,e,r),materializeAppSource:async e=>await t.appleDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await Ta(t,n,e,r)}:{},...i.sendPushNotification.available?{sendPushNotification:async e=>(await Oa(t,n,e,r),{})}:{}})}async function wa(e,t,n,r){if(n.replaceExisting)return await e.appleDeployment.withInvalidatedAppResolutionCache(t,async()=>{let i=await e.appleDeployment.resolveAppBundleId(t,n.app);await Da(e,t,i,r);let a=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Ea(e,t,a.installablePath,r),{bundleId:i,launchTarget:i}}finally{await a.cleanup()}});let i=await e.appleDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{appIdentifierHint:n.app,signal:r});try{return await Ta(e,t,{artifact:i},r)}finally{await i.cleanup()}}async function Ta(e,t,n,r){return await Ea(e,t,n.artifact.installablePath,r),{...n.artifact.bundleId?{bundleId:n.artifact.bundleId}:{},...n.artifact.appName?{appName:n.artifact.appName}:{},...n.artifact.bundleId?{launchTarget:n.artifact.bundleId}:{}}}async function Ea(e,t,n,r){await M(e,t,r),await ka(e,t.kind===`simulator`?{tool:`simctl`,args:b(t,[`install`,t.id,n])}:{tool:`devicectl`,args:[`device`,`install`,`app`,`--device`,t.id,n],timeoutMs:Yt},r,`Apple app install failed`)}async function Da(e,t,n,r){await M(e,t,r),await ka(e,t.kind===`simulator`?{tool:`simctl`,args:b(t,[`uninstall`,t.id,n])}:{tool:`devicectl`,args:[`device`,`uninstall`,`app`,`--device`,t.id,n]},r,`Apple app uninstall failed for ${n}`,{tolerate:e=>tn(`${e.stdout}\n${e.stderr}`.toLowerCase())})}async function Oa(e,t,r,i){if(t.kind!==`simulator`)throw new n(`UNSUPPORTED_OPERATION`,`Apple push notifications require a simulator`);await M(e,t,i);let a=await e.temporaryFiles.create({prefix:`agent-device-ios-push-`,suffix:`.apns`});try{await a.writeText(`${JSON.stringify(r.payload)}\n`),await ka(e,{tool:`simctl`,args:b(t,[`push`,t.id,r.appId,a.path])},i,`Apple push notification failed`)}finally{await a[Symbol.asyncDispose]()}}async function ka(e,t,n,r,i){let a=await e.appleTools.run({...t,allowFailure:!0},n);return i?.tolerate?.(a)?a:me(a,r,e=>({cmd:`xcrun`,args:[t.tool,...t.args],...t.tool===`devicectl`?{hint:en(e.stdout,e.stderr)??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}:{}}))}function Aa(e){return Ma(e)?e.kind!==`simulator`&&e.kind!==`device`?xa:e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?va:_a:ba}function ja(e){return Ma(e)?e.kind===`simulator`?_a:ya:ba}function Ma(e){return g(e)&&e.appleOs!==`watchos`}const L=Object.freeze({available:!0}),Na=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`back is supported on Apple simulators and physical devices.`}),Pa=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Fa(e){return e.kind!==`simulator`&&e.kind!==`device`?Na:f(e)===`watchos`?Pa:L}const Ia=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`home is supported on Apple simulators and physical devices.`}),La=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ra=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`app-switcher is supported on Apple simulators and physical devices.`});function za(e,t){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let n=f(e);return n===`macos`||n===`watchos`?La:L}function R(e){if(e.kind!==`simulator`&&e.kind!==`device`)return!1;let t=f(e);return t!==`tvos`&&t!==`macos`&&t!==`watchos`}const Ba=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`orientation is supported on Apple simulators and physical devices.`}),Va=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function Ha(e){return e.kind!==`simulator`&&e.kind!==`device`?Ba:R(e)?L:Va}const Ua=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`tv-remote is supported only on tvOS devices.`});function Wa(e){return(e.kind===`simulator`||e.kind===`device`)&&ne(e)?L:Ua}const z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ga=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`keyboard status/get is currently supported only on Android; use keyboard dismiss or enter on iOS`});function Ka(e){return R(e)?Ga:z}function qa(e){return R(e)?L:z}function Ja(e){return R(e)?L:z}const Ya=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`No Apple leaf carries this system button.`}),Xa=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`action-button is supported on iPhone and iPad simulators and physical devices.`}),Za=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`The Action Button is iPhone and iPad hardware; tvOS, macOS, watchOS and visionOS have no such control.`});function Qa(e){return e.kind!==`simulator`&&e.kind!==`device`?Xa:ee(e)?L:Za}function $a(e){return Object.freeze({...we({back:Fa(e)}),...Je({unsupported:Ya,home:za(e,Ia),appSwitcher:za(e,Ra),actionButton:Qa(e)}),...Fe({orientation:Ha(e)}),...Ce({tvRemote:Wa(e)}),...He({unsupported:z,status:Ka(e),dismiss:qa(e),enter:Ja(e)})})}function eo(e){let{host:t,device:n,signal:r,admitted:i}=e,a=Object.keys($a(n));return kt({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:Object.fromEntries(a.map(e=>[e,i[e]]))})}const B=Object.freeze({available:!0}),to=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`clipboard is supported on Apple simulators and the macOS host.`}),no=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`settings is supported on Apple simulators and the macOS host.`}),ro=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`settings is supported on Apple simulators and the macOS host, not on physical devices of this OS.`}),io=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:"Apple targets answer a settings read only on iPhone and iPad simulators, where `simctl ui` reports the value the device holds."}),ao=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`clipboard is supported on Apple simulators and the macOS host, not on physical devices of this OS.`}),V=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function oo(e,t,n){if(e.kind!==`simulator`&&e.kind!==`device`)return t;let r=f(e);return r===`watchos`?V:e.kind===`simulator`||r===`macos`?B:n}function so(e){return oo(e,to,ao)}const co=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`trigger-app-event is supported on Apple simulators and physical devices.`}),lo=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`alert is supported on Apple simulators and physical devices.`}),uo=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`alert is supported on Apple simulators, the macOS host, and physical iOS devices.`});function fo(e){if(e.kind!==`simulator`&&e.kind!==`device`)return lo;let t=f(e);return t===`watchos`?V:e.kind===`simulator`||t===`ios`||t===`macos`?B:uo}function po(e){return e.kind!==`simulator`&&e.kind!==`device`?co:f(e)===`watchos`?V:B}function mo(e){let t=so(e);return t.available?ao:t}function ho(e){return e.kind!==`simulator`&&e.kind!==`device`?no:f(e)===`watchos`?V:te(e)?B:io}function go(e){let t=so(e),n=fo(e);return Object.freeze({...Ve({unsupported:mo(e),read:t,write:t}),...We({read:n,wait:n,accept:n,dismiss:n}),...Ke({triggerAppEvent:po(e)}),...Ue({setSetting:oo(e,no,ro),readSetting:ho(e)})})}function _o(e){let{host:t,device:n,signal:r}=e;return kt({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:go(n)})}const vo=/Angle:\s*(-?\d+(?:[.,]\d+)?)\s*°/g;async function yo(e,t={}){let r=[`devicectl`,`device`,`motion`,`hinge-angle`,`--device`,e.id,`--session-timeout`,`1`,`--timeout`,`5`],i=await $t(r,{allowFailure:!0,signal:t.signal,timeoutMs:Zt}),a=bo(i.stdout)??bo(i.stderr);if(a!==void 0)return a;throw new n(`COMMAND_FAILED`,`CoreDevice reported no hinge angle sample`,y(i,{cmd:`xcrun`,args:r,stdout:i.stdout,stderr:i.stderr,deviceId:e.id,hint:`This Xcode/CoreDevice toolchain does not stream 'devicectl device motion hinge-angle' for this device. Foldable poses can be verified only through that stream; update Xcode to a version that ships it.`}))}function bo(e){let t;for(let n of e.matchAll(vo)){let e=Number.parseFloat(n[1].replace(`,`,`.`));Number.isFinite(e)&&(t=e)}return t}var H=class extends n{buildFailureKind;buildFailureCode;buildDetails;constructor(e,t,n=`native build ${e}: ${t}`,r={},i){super(`COMMAND_FAILED`,n,{...r,nativeBuildFailure:e,nativeBuildFailureCode:t,...e===`cancelled`?{reason:`request_canceled`}:{}},i),this.name=`NativeBuildError`,this.buildFailureKind=e,this.buildFailureCode=t,this.buildDetails=r}};function U(e,t,n={},r){return new H(e,t,void 0,n,r)}function xo(e,t,n=Date.now){if(t?.aborted)throw U(`cancelled`,`abort-signal`);return{clock:he.fromTimeoutMs(e,n()),now:n,signal:t}}function W(e,t){if(e.signal?.aborted)throw U(`cancelled`,`abort-signal`);let n=e.clock.remainingMs(e.now());if(n<=0)throw U(`timeout`,t);return Math.max(1,Math.floor(n))}function So(e){return{run:e,readText:Jt,readBinary:Wt,writeText:Vt,ensureDirectory:Kt,chmod:Gt,exists:Ht,rename:qt,remove:Bt,acquireLock:Co,processId:fe,cpuArch:ce}}async function Co(e,t){let n=fe(),r=t.deadline,i=de({lockDirPath:e,owner:{pid:n,startTime:ue(n),acquiredAtMs:Date.now()},timeoutMs:W(r,`cache-lock-deadline`),pollMs:100,description:t.description}),a=r.signal;if(!a)try{return await i}catch(e){throw wo(e,r)}let o=!1,s,c=new Promise((e,t)=>{s=()=>{o=!0,t(U(`cancelled`,`abort-signal`))},a.addEventListener(`abort`,s,{once:!0}),a.aborted&&s()});try{return await Promise.race([i,c])}catch(e){throw o&&i.then(e=>e().catch(()=>void 0),()=>void 0),wo(e,r)}finally{a.removeEventListener(`abort`,s)}}function wo(e,t){return t.clock.isExpired()&&!(e instanceof H&&e.buildFailureKind===`cancelled`)?U(`timeout`,`cache-lock-deadline`):e}async function To(e,t){let n=await Do(e,`xcodebuild`,[`-version`],t),r=await Do(e,`sw_vers`,[`-productVersion`],t),i=await Do(e,`sw_vers`,[`-buildVersion`],t),a=await Eo(e,t);if(a!==`arm64`&&a!==`x86_64`)throw U(`unsupported`,`simulator-architecture-unsupported`,{architecture:a});return{xcode:n,macosProductVersion:r,macosBuild:i,architecture:a}}async function Eo(e,t){let n=W(t,`host-arch-deadline`),r=t.signal,i,a,o=new Promise((e,t)=>{i=setTimeout(()=>t(U(`timeout`,`host-arch-deadline`)),n),i.unref?.(),a=()=>t(U(`cancelled`,`abort-signal`)),r?.addEventListener(`abort`,a,{once:!0})});try{return await Promise.race([e.cpuArch(),o])}finally{clearTimeout(i),a&&r?.removeEventListener(`abort`,a)}}async function Do(e,t,n,r){let i=await Oo(e,t,n,r);if(i.exitCode!==0)throw U(`unsupported`,`toolchain-probe-failed`,{command:t,exitCode:i.exitCode,stderr:i.stderr.slice(0,1024)});let a=(i.stdout||i.stderr).trim();if(!a)throw U(`unsupported`,`toolchain-probe-empty`,{command:t});return a}async function Oo(e,t,n,r){let i=[],a;for(let o=1;;o+=1){let s;try{s=Math.min(nn,W(r,`toolchain-probe-deadline`))}catch(e){throw a??e}i.push(s);try{return await jo(e,t,n,r,s)}catch(e){if(a=ko(e,t,r,i),o>=2)throw a}}}function ko(e,t,n,r){if(i(e))throw U(`cancelled`,`abort-signal`,{},e);if(!pe(e))throw e;if(n.signal?.aborted)throw U(`cancelled`,`abort-signal`);return Ao(t,r,e)}function Ao(e,t,n){let r=t.length;return U(`timeout`,`toolchain-probe-stalled`,{command:e,attemptTimeoutsMs:[...t],hint:`${e} did not answer within ${t[r-1]}ms on ${r} attempt(s). A toolchain probe that cannot answer is a host condition rather than a toolchain defect: run \`${e}\` by hand until it answers, then retry.`},n)}function jo(e,t,n,r,i){return e.run(t,n,{allowFailure:!0,signal:r.signal,timeoutMs:i})}const Mo=`manifest.json`;async function No(e){let{host:t,deadline:n,cacheRoot:r,binaryFilename:i}=e,a=mn(`sha256`).update(JSON.stringify(e.keyInputs)).digest(`hex`).slice(0,32),o=x.join(r,a);return await le({acquire:()=>t.acquireLock(x.join(r,`${a}.lock`),{deadline:n,description:e.lockDescription}),task:async()=>{let s=await Po(t,o,i,a,n);if(s)return{path:s,cacheKey:a};W(n,`native-build-deadline`),t.exists(o)&&await t.remove(o),W(n,`native-build-deadline`),await t.ensureDirectory(r);let c=x.join(r,`.${a}.${t.processId()}.tmp`);W(n,`native-build-deadline`),await t.remove(c);try{W(n,`native-build-deadline`),await t.ensureDirectory(c);let r=x.join(c,i);await e.build(r),W(n,`native-build-deadline`),await t.chmod(r,493);let s=await Io(t,r),l={...e.keyInputs,cacheKey:a,binarySha256:s};return await t.writeText(x.join(c,Mo),`${JSON.stringify(l,null,2)}\n`),W(n,`native-build-deadline`),await t.rename(c,o),{path:x.join(o,i),cacheKey:a}}catch(e){throw await t.remove(c),e}}})}async function Po(e,t,n,r,i){let a=x.join(t,n),o=x.join(t,Mo);if(!(!e.exists(a)||!e.exists(o)))try{let t=JSON.parse(await e.readText(o));return t.cacheKey!==r||typeof t.binarySha256!=`string`?void 0:(W(i,`native-cache-hash-deadline`),await Io(e,a)===t.binarySha256?a:void 0)}catch(e){if(Fo(e))throw e;return}}function Fo(e){return e instanceof H&&(e.buildFailureKind===`cancelled`||e.buildFailureKind===`timeout`)}async function Io(e,t){return mn(`sha256`).update(await e.readBinary(t)).digest(`hex`)}async function Lo(e,t,n,r){let i=mn(`sha256`);for(let a of n){let n=x.join(t,a);if(W(r,`native-source-fingerprint-deadline`),!e.exists(n))throw U(`unsupported`,`native-source-missing`,{filePath:n});i.update(a),i.update(`\0`),i.update(await e.readBinary(n)),i.update(`\0`)}return i.digest(`hex`)}async function Ro(e){let t=Math.min(e.budgetMs,W(e.deadline,`native-build-deadline`));try{return await e.host.run(`xcrun`,[...e.argv],{signal:e.deadline.signal,timeoutMs:t,allowFailure:!0})}catch(n){throw pe(n)?U(`timeout`,`native-build-stalled`,{timeoutMs:t,hint:`The Simulator SDK toolchain did not answer within ${t}ms, which stopped the ${e.label} build before clang reported anything. Run \`xcrun --sdk iphonesimulator clang --version\` by hand until it answers, then retry.`},n):n}}const zo=`Fold.m`,Bo=3e4,Vo=nn+Bo;async function Ho(e={}){let t=e.host??Uo(),n=xo(Vo,e.signal);try{let r=e.sourceRoot??x.join(ge(),`apple`,`fold-helper`),i=await Lo(t,r,[zo],n),a=await To(t,n);return await No({host:t,deadline:n,lockDescription:`iOS Simulator fold helper cache`,cacheRoot:e.cacheRoot??x.join(Ut(),`.agent-device`,`fold-helper`),binaryFilename:`fold-helper`,keyInputs:{schemaVersion:1,sourceHash:i,toolchain:a,compileArgv:Wo({sourceRoot:``,outputPath:``})},build:e=>Go(t,n,r,e)})}catch(e){throw Ko(e)}}function Uo(){return So(Qt)}function Wo(e){return[`--sdk`,`iphonesimulator`,`clang`,`-mios-simulator-version-min=15.0`,`-fobjc-arc`,`-Wall`,`-Wextra`,`-framework`,`Foundation`,`-framework`,`IOKit`,x.join(e.sourceRoot,zo),`-o`,e.outputPath]}async function Go(e,t,n,r){let i=await Ro({host:e,deadline:t,argv:Wo({sourceRoot:n,outputPath:r}),budgetMs:Bo,label:`fold helper`});if(i.exitCode!==0||!e.exists(r))throw qo(y(i))}function Ko(e){return!(e instanceof H)||e.buildFailureKind===`cancelled`?e:qo({...e.buildDetails,cause:e.buildFailureCode},e)}function qo(e,t){return new n(`COMMAND_FAILED`,`Unable to build the simulator fold helper`,{hint:`Select an Xcode with the iOS simulator SDK and foldable HID support using DEVELOPER_DIR.`,...e,reason:`fold-helper-build-failed`},t)}async function Jo(e,t,r){r?.throwIfAborted();let i=await Ho({signal:r});r?.throwIfAborted();let a=typeof t==`string`?0:t.at(-1).atMs,o=typeof t==`string`?t:JSON.stringify(t),s=await sn(e,[`spawn`,e.id,i.path,o],{signal:r,timeoutMs:a+1e4,kill:{signal:`SIGTERM`,graceMs:1e3},allowFailure:!0});if(s.exitCode!==0)throw new n(`COMMAND_FAILED`,`Unable to send the simulator hinge pose`,y(s,{reason:`fold-hid-dispatch-failed`,deviceId:e.id}))}async function Yo(e,t,n={}){n.signal?.throwIfAborted(),ln(e,`fold`);let r=t,i=r.keyframes?.at(-1)?.angle,o=r.pose??a(i);Xo(e,await un(e,{signal:n.signal})),await Jo(e,r.keyframes??o,n.signal),d({level:`info`,phase:`apple_fold_pose_dispatched`,data:{deviceId:e.id,pose:o}});let s=await Zo(e,o,n.signal,i),c=await os(e,n.signal);return{pose:a(s),hingeAngleDegrees:s,...c?{screen:ss(c)}:{}}}function Xo(e,t){if(t.unresolved)throw new n(`COMMAND_FAILED`,`CoreDevice reported no display table for this simulator`,{deviceId:e.id,hint:`fold needs 'devicectl device info displays' to tell a foldable from a single-panel simulator; update Xcode to a version that ships the display-information feature.`});if(!t.multiScreen)throw new n(`UNSUPPORTED_OPERATION`,`${e.name} is not a foldable simulator: fold requires more than one integrated panel`,{deviceId:e.id,reason:`single-panel-device`,hint:`fold sets the hinge angle of a foldable simulator such as iPhone Duo; this simulator reports one integrated panel, so it has no hinge to pose.`})}async function Zo(e,t,n,r){let i,a;for(let o=1;o<=4;o+=1)if(n?.throwIfAborted(),a=i,i=await yo(e,{signal:n}),Qo(i,a,t,r))return i;throw ts(e,t,i,a,r)}function Qo(e,t,n,r){return r===void 0?a(e)===n?n!==`half-open`||t!==void 0&&ns(e,t):!1:$o(e,t,r)}function $o(e,t,n){return es(e,n)?n===0||n===180||t!==void 0&&es(t,n)&&Math.abs(e-t)<=.5:!1}function es(e,t){return t===void 0||e!==void 0&&Math.abs(e-t)<=.5}function ts(e,t,r,i,o){return es(r,o)?o!==void 0&&r!==void 0?as(e,a(r),r,i):r!==void 0&&t===`half-open`&&a(r)===t?as(e,t,r,i):is(e,t,r):new n(`COMMAND_FAILED`,`The hinge did not reach the final keyframe angle`,{reason:`fold-angle-unverified`,targetAngleDegrees:o,hingeAngleDegrees:r,deviceId:e.id})}function ns(e,t){return a(e)===`half-open`&&a(t)===`half-open`&&Math.abs(e-t)<=.5}function rs(e,t,n){return{deviceId:e.id,requestedPose:t,observedPose:n===void 0?void 0:a(n),hingeAngleDegrees:n}}function is(e,t,r){return new n(`COMMAND_FAILED`,`${e.name} did not reach the ${t} pose: CoreDevice still reports a hinge angle of ${r}°`,{...rs(e,t,r),reason:`fold-pose-unverified`,hint:`The simulator HID command completed, but the hinge did not follow. Verify that the selected Xcode and simulator runtime support foldable HID control, then retry.`})}function as(e,t,r,i){return new n(`COMMAND_FAILED`,`${e.name} was observed ${t} at ${r}° but did not settle: 4 hinge reads never held two consecutive angles within ${Xt}° of each other`,{...rs(e,t,r),reason:`fold-pose-unsettled`,...i===void 0?{}:{previousHingeAngleDegrees:i},hint:`The hinge reached the requested pose and was still moving when the read budget ended. Retry the fold, then read the angle directly with xcrun devicectl device motion hinge-angle --device <udid> --session-timeout 1 --timeout 5 to see whether the simulator holds the pose.`})}async function os(e,t){let n=await un(e,{signal:t});if(!(n.unresolved||n.ambiguous))return n.activeDisplay}function ss(e){return{display:e.name,coordinateSpace:o,widthPt:Math.round(e.widthPx/e.pointScale),heightPt:Math.round(e.heightPx/e.pointScale)}}const cs=Object.freeze({available:!0}),ls=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`fold is supported on foldable iPhone simulators controlled through simulator HID; a physical device is folded by hand.`}),us=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`fold poses the hinge of a foldable iPhone; tvOS, macOS, watchOS and visionOS simulators have no hinge.`});function ds(e){return{available:!1,reason:`unsupported-device-scope`,hint:`fold cannot resolve a simulator scoped to the set at "${e}": CoreDevice's display inventory and hinge-angle readback need a simulator in the default set, so the pose could not be verified. Run fold without --ios-simulator-device-set.`}}function fs(e){if(e.kind!==`simulator`)return ls;let t=f(e);return t!==`ios`&&t!==`ipados`?us:e.simulatorSetPath?ds(e.simulatorSetPath):cs}function ps(e){return Ct({fold:fs(e)})}function ms(e){let{device:t,signal:n}=e;return v(ps(t).setFoldPose,()=>({setFoldPose:async e=>(n.throwIfAborted(),await Yo(t,e,{signal:n}))}))}function hs(e,t,n){let r=Re({device:t.device,signal:t.signal,resolveInteractor:e.localInteractors.resolve}),i=async i=>{if(i.options?.observeOnly===!0)return await r.captureSnapshot(i);let a=h(t.device)?oe(i.options?.surface,t.appBackend):void 0;if(a)return await e.snapshot.captureSurface(t.device,{...i.options,surface:a},ke(t.signal,i));if(!n)return await r.captureSnapshot(i);let o=ke(t.signal,i);return await n.capture(t.device,i,o,async e=>await r.captureSnapshot(e))};return Object.freeze({captureSnapshot:i,captureSnapshotWithCustomActions:i,captureSnapshotWithoutActiveApp:i})}function gs(e,t){return Object.freeze({findText:async n=>{let r=await _s(e,t,n);if(!r)return{found:!1};let i=await e.localInteractors.resolve(t.device,{...n.execution,...r});return i.findText?await i.findText(n.text,r):{found:!1}}})}async function _s(e,t,n){let r=n.options?.appBundleId;if(r===void 0||h(t.device)&&se(n.options?.surface,t.appBackend)===`macos-helper`)return;let i=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal;if(i.throwIfAborted(),await vs(e,t.device,n.execution))return{appBundleId:r,signal:i}}async function vs(e,t,n){return!P(t)||await e.appleApplications.hasLiveRunnerSession(t,n??{})}const G=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`The native macOS app backend never starts the XCTest runner, which this command needs. Unset AGENT_DEVICE_MACOS_APP_BACKEND to use XCTest.`});function ys(e,t){return!h(e)||t!==`native`?{}:Object.freeze({screenRecordingStart:G,screenRecordingReattach:G,prepareAppleRunner:G,longPressPoint:G,...we({back:G}),...Pe({unsupported:G})})}function bs(){let e,t=!1,n=async()=>(e??=import(`./adapter.js`).then(({createSimulatorSnapshotSource:e})=>e()),await e);return{acquire:async e=>t?{stage:`failed`,failure:{kind:`unsupported`,code:`source-closed`}}:await(await n()).acquire(e),close:async()=>{t=!0,e&&await(await e).close()}}}function xs(e=Date.now){let t=new Map;return async(n,r)=>{if(n.kind!==`simulator`)return`absent`;let i=t.get(n.id);if(i!==void 0&&e()-i.at<1e3)return{kind:`present`,host:i.host};t.delete(n.id);let a=await Ss(n,r);return a!==`absent`&&a!==`unknown`&&t.set(n.id,{at:e(),host:a.host}),a}}async function Ss(e,t){let n=!1;for(let r of Et){let i=await Cs(r.processExecutable,t);if(i===`unknown`){n=!0;continue}for(let a of i){let i=await ws(a,e.id,t);if(i===`unknown`)n=!0;else if(i)return{kind:`present`,host:r}}}return n?`unknown`:`absent`}async function Cs(e,t){let n=await Ts(`pgrep`,[`-f`,e],t);return n===`unknown`?`unknown`:n.exitCode===1?[]:n.exitCode===0?n.stdout.split(`
|
|
5
|
+
`).map(e=>Number.parseInt(e.trim(),10)).filter(e=>Number.isSafeInteger(e)&&e>0):`unknown`}async function ws(e,t,n){let r=await Ts(`ps`,[`eww`,`-p`,String(e),`-o`,`command=`],n);return r===`unknown`||r.exitCode!==0?`unknown`:r.stdout.includes(`SIMULATOR_UDID=${t}`)?!0:!r.stdout.includes(`SIMULATOR_UDID=`)&&`unknown`}async function Ts(e,t,n){try{let r=await Qt(e,t,{allowFailure:!0,timeoutMs:3e3,...n?{signal:n}:{}});return{exitCode:r.exitCode,stdout:r.stdout}}catch{return`unknown`}}const Es=`system-surface-presented`,Ds=`system-surface-host-lingering`,Os=`window-coordinate-space-unresolved`;function ks(e,t={}){let r=t.source??bs(),i=t.resolveTarget??Ci(),a=t.systemSurfacePresent??xs(),o=new Set,s=new Map,c=e=>(Ws(e,s,o),o.has(Gs(e))),l=Ni({source:r,resolveTarget:i,clock:e.clock,isBridgeDisabled:c});return Object.freeze({awaitObservable:l.awaitObservable,shutdown:async()=>await r.close(),capture:async(t,s,l,d)=>{if(!Ms(t,s))return await Is(t,s,d);let f=await a(t,l);if(f===`unknown`)return await K(t.id,s,d,Rs(t.id,s),q(s),`system-surface-probe-unavailable`,[Us()]);if(f!==`absent`)return await Fs(t,s,d,f.host.bundleId);let p;try{p=await As(e,i,t,s,l)}catch(e){return js(l,e),J(`target-resolution-failed`,t,void 0,e),await K(t.id,s,d,Rs(t.id,s),q(s),`target-resolution-failed`,[Us()])}if(c(p))return J(`circuit-disabled`,t,p.generation),await K(t.id,s,d,p,q(s),`circuit-disabled`);let m=q(s),h=await r.acquire({target:p,hint:_e(m),signal:l});if(h.stage===`failed`){if(h.failure.kind===`cancelled`)throw l.throwIfAborted(),new n(`COMMAND_FAILED`,`Simulator AX snapshot acquisition was cancelled.`,{reason:h.failure.code,...h.failure.details});let e=await Hs(h.failure,p,t,s.options.appBundleId,l,i);return await Ns(s,d,p,e,m,h.failure,o)}try{return await u(`ios.snapshot-source.present`,async()=>await e.snapshot.presentIosAcquisition(h,s.options),{producer:`simulator-ax-bridge`})}catch(e){return await Ns(s,d,p,{lineage:p,residue:[]},m,{kind:`malformed-tree`,code:`presentation-invariant`},o,e)}}})}async function As(e,t,n,r,i){let a=r.options.appBundleId;for(;;)try{return await t(n,a,i)}catch(t){if(!Ti(t))throw t;let i={requestId:r.execution?.requestId};if(await e.appleApplications.hasLiveRunnerSession(n,i))throw t}}function js(e,t){if(e.aborted)throw i(t)?t:e.reason}function Ms(e,t){return e.platform===`apple`&&e.appleOs===`ios`&&e.kind===`simulator`&&!!t.options?.appBundleId&&t.options?.customActions!==!0&&t.options?.preferredBackend===void 0}async function Ns(e,t,n,r,i,a,o,s){return Ps(a)&&o.add(Gs(n)),J(a.code,{id:n.simulator.udid},n.generation,s,a.details),await K(n.simulator.udid,e,t,r.lineage,i,a.code,r.residue)}function Ps(e){return e.kind!==`preparing`&&e.code!==Os}async function K(e,t,n,r,i,a,o=[]){return Ls(e,await n(t),r,i,a,o)}async function Fs(e,t,n,r){let i=await n(t),a=i.systemSurface?Es:Ds;return i.systemSurface||J(a,e,void 0,void 0,{detectedHost:r}),Ls(e.id,i,Rs(e.id,t),q(t),a)}async function Is(e,t,n){let r=await n(t),i=r.systemSurface;return i?{...r,comparisonIdentity:Bs(zs(e.id,i.bundleId),q(t),[])}:r}function Ls(e,t,n,r,i,a=[]){let o=t.systemSurface;return{...t,comparisonIdentity:Bs(o?zs(e,o.bundleId):n,r,[...o?[]:a,{kind:`fallback-source`,producer:`apple-runner`}]),warnings:[...t.warnings??[],Vs(i,n,o!==void 0)]}}function Rs(e,t){return{targetId:`${e}:${t.options.appBundleId}`}}function zs(e,t){return{targetId:`${e}:${t}`}}function Bs(e,t,n){return Object.freeze({producer:`apple-runner`,intent:t.acquisitionIntent,lineage:Object.freeze({...e.targetId?{targetId:e.targetId}:{},...e.generation?{generation:e.generation}:{}}),presentationKey:ve(t),residue:Object.freeze([...n])})}function Vs(e,t,n){return e===Es?`Simulator AX snapshot inapplicable (${e}); used XCTest to read the system surface presented over the app.`:e===Ds?`Simulator AX snapshot inapplicable (${e}); used XCTest, which read app content: the system surface host process was still running but no longer presenting.`:n?`Simulator AX snapshot unavailable (${e}); used XCTest, which read the system surface presented over the app.`:e===`bridge-preparation-pending`?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture while the bridge is still being prepared.`:e===Os?`Simulator AX snapshot unavailable (${e}); used XCTest for this capture, which reports captured geometry in the app's own orientation space.`:`Simulator AX snapshot unavailable (${e}); used XCTest for ${t.generation?`this app generation`:`an unverified app generation`}.`}async function Hs(e,t,n,r,i,a){if(e.kind!==`stale-target`)return{lineage:t,residue:[]};try{return{lineage:await a(n,r,i,`refresh`),residue:[]}}catch(e){return i.throwIfAborted(),J(`fallback-target-resolution-failed`,n,void 0,e),{lineage:{targetId:t.targetId},residue:[Us()]}}}function Us(){return{kind:`unknown-generation`,captureId:hn()}}function q(e){return ye({raw:e.options?.raw,interactiveOnly:e.options?.interactiveOnly,depth:e.options?.depth,scope:e.options?.scope,customActions:e.options?.customActions,acquisitionIntent:e.options?.acquisitionIntent})}function Ws(e,t,n){let r=t.get(e.targetId);r&&r!==e.generation&&n.delete(`${e.targetId}:${r}`),t.set(e.targetId,e.generation)}function Gs(e){return`${e.targetId}:${e.generation}`}function J(e,t,n,r,i){d({level:`debug`,phase:`ios_snapshot_route_fallback`,data:{reason:e,deviceId:t.id,...n?{generation:n}:{},...r?{error:r instanceof Error?r.message:String(r)}:{},...i?{details:i}:{}}})}const Y=ie(`apple`),X=Object.freeze({available:!0}),Z=_(`unsupported-platform-leaf`),Ks=_(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web). Apple screen geometry is fixed by the selected simulator or device type — open a different simulator to test another screen size.`),qs=_(`unsupported-platform-leaf`,`the stateless audio page probe is a web-session operation; Apple targets use the host capture.`),Js=_(`unsupported-device-backend`,`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`),Ys=_(`unsupported-device-kind`,`focus is supported on Apple simulators and physical devices.`),Xs=_(`unsupported-platform-leaf`,`Apple appstate is unavailable here: the runner reads the session app's XCUIApplication state on iOS-family simulators and physical devices only, and the Apple target answers no sessionless foreground probe. The per-command answer is the targetActivation disclosure, which a capture carries when its command had to re-activate the session app (#2682).`);function Zs(e){return!g(e)||e.appleOs===`watchos`?Xs:e.kind===`simulator`||e.kind===`device`?X:Xs}const Qs=_(`unsupported-provider-mode`,`Headless boot is supported only for local Android emulators.`),$s=_(`unsupported-platform-leaf`,`watchOS has no XCUITest-driveable UI, so element text comes from the captured tree only.`),ec=_(`unsupported-device-kind`),tc=_(`unsupported-platform-leaf`,`watchOS open is not supported because XCUITest cannot drive watchOS UI.`),nc=_(`unsupported-platform-leaf`,`watchOS runner preparation is not supported because XCUITest cannot drive watchOS UI.`),rc=_(`unsupported-platform-leaf`,`watchOS close is not supported because XCUITest cannot drive watchOS UI.`),ic=_(`unsupported-device-kind`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),ac=Q(`open is supported only for Apple simulators and devices.`),oc=Q(`prepare is supported only for Apple simulators and devices.`),sc=Q(`close is supported only for Apple simulators and devices.`),cc=_(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),lc=_(`unsupported-device-kind`,`shutdown is supported only for Apple simulators and Android emulators.`),uc=Q(`snapshot is supported only for Apple simulators and devices.`),dc=_(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),fc=_(`unsupported-platform-leaf`,`screenshot is not supported on watchOS because XCUITest cannot drive watchOS UI.`),pc=Q(`screenshot is supported only for Apple simulators and devices.`),mc=_(`owner-capability-missing`,`Open the app under test before capturing its snapshot.`);function Q(e){return _(`unsupported-device-kind`,e)}function hc(e){return!g(e)||e.appleOs===`watchos`?Z:e.kind===`simulator`?X:lc}function gc(e){let t=_c(e),n=vc(e),r=yc(e),i=bc(e);return Be({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:cc})}function _c(e){return f(e)===`watchos`?tc:e.kind===`simulator`||e.kind===`device`?X:ac}function vc(e){return f(e)===`watchos`?nc:e.kind===`simulator`||e.kind===`device`?X:oc}function yc(e){return f(e)===`watchos`?rc:e.kind===`simulator`||e.kind===`device`?X:sc}function bc(e){return f(e)!==`watchos`&&g(e)&&e.kind===`simulator`?X:ic}function xc(e){return e.appleOs===`watchos`?_(`unsupported-platform-leaf`,`watchOS app inventory is not supported.`):e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?_(`unsupported-device-backend`,`App inventory is available only on CoreDevice-backed physical iOS devices.`):X}function $(e){return e.kind===`simulator`||e.kind===`device`?X:Ys}function Sc(e){let t=tr(e),n=ks(e),r,i=e=>h(e)?r??=fn():`xctest`,a=async n=>{let r=await t.inspectFacts(n),a=Sa(n),o=Wr(n),s=o.available?await e.screenRecording.apple.availability(n):void 0,c=o.available&&s?.available===!1?_(`unsupported-provider-mode`,s.hint):o,l=n.appleOs===`watchos`?Z:X,u=h(n)||n.appleOs===`watchos`?Z:X,d=xc(n);return Object.freeze({device:r.device,operations:{...r.operations,...a,appState:Zs(n),networkDump:X,screenRecordingStart:c,screenRecordingReattach:c,screenRecordingCleanup:c,...Dc(n),...ze({capture:Ec(n)}),...Ie({findText:Tc(n)}),...Ee({setViewport:Ks}),...Le({focus:$(n)}),...wn(n),...Ae({type:$(n)}),...Ze({unsupported:Z,tap:$(n),longPress:$(n),fill:$(n),...g(n)?{tapElementSelector:$(n)}:{}}),...Ge({readTextAtPoint:wc(n)}),...$a(n),...ps(n),...go(n),...$e({capture:_n(n),query:qs}),...qe(Cc(n)),ensureReady:l,bootTarget:u,bootTargetHeadless:Qs,listApps:d,...gc(n),shutdownTarget:hc(n),...ys(n,i(n))}})};return Object.freeze({owner:Y,ownsDevice:e=>e.platform===`apple`,inspectFacts:a,bind:async r=>{let o=await t.bind(r),s=await a(r.device),c=s.operations.screenRecordingStart,l={...v(s.operations.appState,()=>gn(e,{device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...o.operations,...Ca({host:e,device:r.device,signal:r.scope.signal}),networkDump:async t=>await ar(e,r.device,t,r.scope.signal),...v(c,()=>Gr({host:e,device:r.device,owner:Y,signal:r.scope.signal})),...v(s.operations.audioProbeStart,()=>ct({host:e.audioProbe.hostCapture,device:r.device,owner:Y})),...v(s.operations.perfFrames,()=>vn({resolveHost:()=>e.perf.apple,device:r.device,owner:Y})),...v(s.operations.captureSnapshot,()=>hs(e,{device:r.device,signal:r.scope.signal,appBackend:i(r.device)},n)),...v(s.operations.captureScreenshot,()=>Oe({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...v(s.operations.focusPoint,()=>Xe({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...De({device:r.device,signal:r.scope.signal,facts:s.operations,resolveInteractor:e.localInteractors.resolve}),...v(s.operations.scrollDirection,()=>je({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...v(s.operations.typeText,()=>Se({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...v(s.operations.tapPoint,()=>Qe({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:s.operations,pause:async t=>await e.clock.sleep(t,r.scope.signal)})),...v(s.operations.readTextAtPoint,()=>Me({device:r.device,signal:r.scope.signal,resolveInteractor:e.localInteractors.resolve})),...v(s.operations.findText,()=>gs(e,{device:r.device,signal:r.scope.signal,appBackend:i(r.device)})),...eo({host:e,device:r.device,signal:r.scope.signal,admitted:s.operations}),..._o({host:e,device:r.device,signal:r.scope.signal}),...ms({device:r.device,signal:r.scope.signal}),...v(s.operations.ensureReady,()=>({ensureReady:async()=>await M(e,r.device,r.scope.signal)})),...v(s.operations.bootTarget,()=>({bootTarget:async t=>await M(e,r.device,r.scope.signal,{deadlineAtMs:t.deadlineAtMs})})),...v(s.operations.listApps,()=>({listApps:async e=>{r.scope.signal.throwIfAborted();let{listIosApps:t}=await import(`./app-resolution.js`).then(e=>e.t);return(await t(e.device,e.filter)).map(e=>({id:e.bundleId,name:e.name}))}})),...Ne(Ji({host:e,device:r.device,signal:r.scope.signal,observation:n}),s.operations),...v(s.operations.shutdownTarget,()=>({shutdownTarget:async()=>await e.deviceShutdown.apple.shutdownTarget(r.device,r.scope.signal)}))};return Object.freeze({device:o.device,owner:Y,facts:s,operations:Object.freeze(l),[Symbol.asyncDispose]:async()=>await o[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([t.shutdown(),n.shutdown()])}})}function Cc(e){let t=e.iosPhysicalDeviceBackend!==`xctest`&&f(e)!==`watchos`?X:Js;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function wc(e){return f(e)===`watchos`?$s:e.kind===`simulator`||e.kind===`device`?X:ec}function Tc(e){return f(e)===`watchos`?uc:e.kind===`simulator`||e.kind===`device`?X:uc}function Ec(e){return f(e)===`watchos`?fc:e.kind===`simulator`||e.kind===`device`?X:pc}function Dc(e){let t=Tc(e);return Ye({capture:t,customActions:t.available&&g(e)&&e.kind===`simulator`?X:dc,withoutActiveApp:g(e)?mc:t})}export{So as a,H as c,Sc as createApplePlatformRuntime,_i as d,To as i,yi as l,Ro as n,xo as o,Lo as r,W as s,No as t,vi as u};
|