agent-device 0.21.30 → 0.21.31
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.30.apk → agent-device-android-ime-helper-0.21.31.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.31.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.30.manifest.json → agent-device-android-ime-helper-0.21.31.manifest.json} +4 -4
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.31.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.31.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.30.manifest.json → agent-device-android-snapshot-helper-0.21.31.manifest.json} +7 -7
- package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/BackgroundInteraction.swift +20 -6
- package/apple/snapshot-bridge/README.md +16 -3
- package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +33 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +110 -8
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAppScreenCapture.swift +20 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +4 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +1 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +30 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +14 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +81 -41
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +40 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotAcquisition.swift +5 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +74 -10
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTiming.swift +33 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +2 -2
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +23 -2
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +158 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +165 -70
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryConfirmation.swift +2 -3
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +49 -27
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +17 -9
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +30 -28
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +87 -87
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +4 -3
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.h +13 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.m +45 -0
- package/dist/src/absence-observation-errors.js +1 -1
- package/dist/src/adapter.js +1 -1
- package/dist/src/adb-executor.js +1 -1
- 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 +1 -1
- package/dist/src/alert-tree-driver.js +1 -1
- package/dist/src/alert.js +1 -1
- package/dist/src/alert2.js +1 -1
- package/dist/src/android.js +1 -1
- package/dist/src/app-backend.js +1 -1
- package/dist/src/app-launch.js +1 -1
- package/dist/src/app-lifecycle.js +4 -4
- package/dist/src/app-log-runtime2.js +3 -3
- package/dist/src/app-log-session-resource.js +1 -1
- 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/application-lifecycle-interaction.js +1 -1
- package/dist/src/artifact-tracking.js +1 -1
- package/dist/src/automation-helper-artifact.js +1 -1
- package/dist/src/automation-helper.js +1 -1
- package/dist/src/back-mode.js +1 -1
- package/dist/src/boot-diagnostics.js +1 -1
- package/dist/src/browser-launch.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +35 -29
- package/dist/src/cli-runner.js +1 -1
- package/dist/src/cli.js +3 -3
- package/dist/src/client-metro-companion.js +1 -1
- package/dist/src/client-metro.js +1 -1
- package/dist/src/client-types.d.ts +3 -3
- package/dist/src/cloud-artifacts.d.ts +5 -4
- package/dist/src/code-signature-cache.js +1 -1
- package/dist/src/command-metadata.js +10 -10
- package/dist/src/command-tools.js +2 -2
- package/dist/src/command.js +1 -1
- package/dist/src/composed-inventory-gateways.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection.js +5 -5
- package/dist/src/contracts.js +1 -1
- package/dist/src/daemon-client-ensure.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-client.js +1 -1
- package/dist/src/daemon-command-registry.js +1 -1
- package/dist/src/daemon-composition.js +1 -1
- package/dist/src/daemon-policy-file.js +1 -1
- package/dist/src/daemon-registration-owner.js +3 -3
- package/dist/src/daemon-resolution.js +1 -1
- package/dist/src/daemon-startup-diagnostics.js +1 -1
- package/dist/src/debug-symbols-facade.js +3 -3
- package/dist/src/device-claim-recovery.js +1 -1
- package/dist/src/device-claims.js +1 -1
- package/dist/src/device-inventory-context.js +1 -1
- package/dist/src/device-readiness-runtime.js +1 -1
- package/dist/src/device-selection-resolver.js +1 -1
- package/dist/src/device.js +1 -1
- package/dist/src/devicectl.js +1 -1
- package/dist/src/diagnostics.js +1 -1
- package/dist/src/display-inventory.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/explicit-session-resolution.js +1 -1
- package/dist/src/expo-dev-client-launch.js +1 -1
- package/dist/src/file.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/gesture-admission.js +1 -1
- package/dist/src/gesture-plan.js +1 -1
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/hdc.js +1 -1
- package/dist/src/helper.js +2 -2
- package/dist/src/host.js +1 -1
- package/dist/src/host2.js +1 -1
- package/dist/src/host3.js +1 -1
- package/dist/src/host4.js +1 -1
- package/dist/src/host5.js +1 -0
- 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.js +1 -1
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions2.js +1 -1
- package/dist/src/install-source-network-transport.js +1 -1
- package/dist/src/install-source2.js +1 -1
- 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/interactor3.js +1 -1
- package/dist/src/interactor4.js +1 -1
- package/dist/src/interactor5.js +1 -1
- package/dist/src/interactors.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +1 -1
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/inventory.js +1 -1
- package/dist/src/inventory2.js +1 -1
- package/dist/src/inventory6.js +1 -1
- package/dist/src/ios-node-interpretation.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-engine.js +1 -1
- package/dist/src/ios-snapshot-runtime.js +1 -1
- package/dist/src/keyboard-occlusion.js +1 -1
- package/dist/src/keyed-lock.js +1 -1
- package/dist/src/launch-confirmation.js +1 -1
- package/dist/src/launch-services-registration.js +4 -4
- package/dist/src/lease.js +1 -1
- package/dist/src/legacy.js +1 -1
- package/dist/src/limrun-runtime-dependencies.js +1 -1
- package/dist/src/local-interactor-operation-set.js +1 -1
- package/dist/src/mechanics.js +12 -12
- package/dist/src/mobile-snapshot-semantics.js +1 -1
- package/dist/src/observability.js +1 -1
- package/dist/src/output-path.js +1 -1
- package/dist/src/parameterized-recorded-fill.js +1 -1
- package/dist/src/perf-facade.js +1 -1
- package/dist/src/perf-runtime-operation-builder.js +1 -1
- package/dist/src/perf-target.js +1 -1
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/platform-runtime-android-adb-host.js +1 -1
- package/dist/src/platform-runtime-claim-recovery.js +1 -1
- package/dist/src/platform-runtime-daemon-services.js +1 -1
- package/dist/src/platform-runtime-host.js +1 -1
- package/dist/src/platform-runtime-open-target.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +5 -5
- package/dist/src/platform-runtime-runtime-hints.js +2 -2
- package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-finalizer-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/png-resize.js +1 -1
- package/dist/src/png-worker-client.js +1 -1
- package/dist/src/process-exit.js +1 -1
- package/dist/src/provider-device-runtime.d.ts +28 -0
- package/dist/src/provider-plugin-catalog.js +2 -0
- package/dist/src/provider-plugin.d.ts +1 -1
- package/dist/src/provider-webdriver.js +1 -1
- package/dist/src/proxy.js +1 -1
- package/dist/src/react-native-overlay2.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/react-profile-command.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/recording-scope.js +1 -1
- package/dist/src/recording.js +1 -1
- package/dist/src/registry.js +1 -1
- package/dist/src/remote-config-core.js +1 -1
- package/dist/src/replay-backend-host.js +1 -1
- package/dist/src/replay-divergence.js +1 -1
- package/dist/src/replay-maestro-backend.js +3 -3
- package/dist/src/replay-script-selection.js +1 -1
- package/dist/src/replay2.js +1 -1
- package/dist/src/request-runtime-binding.js +1 -1
- package/dist/src/request.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-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 +2 -2
- 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 -1
- package/dist/src/runner-selector-query.js +1 -1
- package/dist/src/runner-start-budget.js +1 -1
- package/dist/src/runner-startup-transport.js +1 -1
- package/dist/src/runner-toolchain-probe.js +1 -1
- package/dist/src/runner.js +2 -2
- package/dist/src/runtime-admission.js +1 -1
- package/dist/src/runtime-deployment.js +1 -1
- package/dist/src/runtime-factory.js +1 -1
- package/dist/src/runtime-session.js +1 -1
- package/dist/src/runtime.js +4 -4
- package/dist/src/runtime10.js +2 -2
- package/dist/src/runtime2.js +1 -1
- package/dist/src/runtime3.js +5 -5
- package/dist/src/runtime4.js +1 -1
- package/dist/src/runtime5.js +1 -1
- 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 +2 -2
- package/dist/src/screen-recording-transport.js +1 -1
- package/dist/src/screenshot-density.js +1 -1
- package/dist/src/screenshot-runtime.js +1 -1
- package/dist/src/screenshot3.js +1 -1
- package/dist/src/sdk-batch-runner.js +2 -2
- package/dist/src/sdk-batch.js +2 -2
- package/dist/src/sdk-contracts.d.ts +9 -0
- package/dist/src/sdk-contracts.js +2 -2
- package/dist/src/sdk-device.js +1 -1
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-io.js +5 -5
- package/dist/src/sdk-remote-config.js +1 -1
- 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-startup.js +1 -1
- package/dist/src/session-paths.js +1 -1
- package/dist/src/session-replay-vars.js +1 -1
- package/dist/src/session-runtime.js +1 -1
- package/dist/src/session-store.js +3 -3
- package/dist/src/session.js +1 -1
- package/dist/src/session2.js +5 -5
- package/dist/src/settings-bluetooth.js +1 -1
- package/dist/src/settings.js +1 -1
- package/dist/src/settings2.js +1 -1
- package/dist/src/settle-observation-capture.js +1 -1
- package/dist/src/simctl-settings.js +1 -1
- package/dist/src/simctl.js +1 -1
- package/dist/src/simulator-boot.js +1 -1
- package/dist/src/simulator-state.js +1 -1
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-chrome.js +1 -1
- package/dist/src/snapshot-desktop-projection.js +1 -1
- package/dist/src/snapshot-helper-install.js +6 -6
- package/dist/src/snapshot-node-lookup.js +1 -1
- package/dist/src/snapshot-occlusion.js +1 -1
- package/dist/src/snapshot-runtime-binding.js +1 -1
- package/dist/src/snapshot-runtime-capture-input.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/snapshot3.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src3.js +1 -1
- package/dist/src/src4.js +1 -1
- package/dist/src/store.js +1 -1
- package/dist/src/tap-keyboard-occlusion.js +1 -1
- package/dist/src/target-evidence-tree.js +1 -1
- package/dist/src/target-evidence.js +1 -1
- package/dist/src/telephony-runtime.js +1 -1
- package/dist/src/text-entry-focus.js +1 -1
- package/dist/src/tool-provider.js +3 -3
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tool-provider3.js +1 -1
- package/dist/src/toolchain-probe.js +1 -1
- package/dist/src/touch-reference-frame.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-runtime.js +1 -1
- package/dist/src/tv-remote.js +2 -2
- package/dist/src/type-text-runtime.js +1 -1
- package/dist/src/update-check.js +1 -1
- package/dist/src/vega-executable.js +1 -1
- package/dist/src/video.js +1 -1
- package/dist/src/webdriver-source.js +1 -1
- package/package.json +7 -6
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.30.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk.sha256 +0 -1
- package/dist/src/physical-device-apps.js +0 -1
package/dist/src/runtime.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{R as e,
|
|
2
|
-
`,String.raw`\n`)}const
|
|
1
|
+
import{R as e,tt as t}from"./sdk-contracts.js";import{i as n}from"./sdk-batch-runner.js";import{H as r,_t as i}from"./sdk-io.js";import"./diagnostics.js";import{U as a}from"./sdk-device.js";import{bn as o,pn as s,yn as c}from"./sdk-batch.js";import{n as l,t as u}from"./android-snapshot-quality.js";import{n as d}from"./device-shell.js";import{n as f}from"./adb-failure.js";import"./retry.js";import{i as p,o as m}from"./adb.js";import{t as h}from"./open-target.js";import{i as g,n as ee}from"./recording-stop-observation.js";import{i as te,n as ne}from"./durable-resource.js";import{n as re}from"./screen-recording-runtime.js";import{n as ie,r as ae,t as oe}from"./application-lifecycle-runtime.js";import{n as se}from"./async-lifecycle.js";import{i as ce}from"./touch-runtime.js";import{r as le,t as ue}from"./gesture-admission.js";import{readAndroidAppStateWithExecutor as de}from"./app-state.js";import{ANDROID_CLIPBOARD_SHELL_COMMAND_UNAVAILABLE_HINT as fe}from"./clipboard-shell-response.js";import{B as pe,C as me,I as he,K as ge,M as _e,N as ve,O as ye,R as be,T as xe,U as Se,Y as Ce,Z as we,_ as Te,h as Ee,k as De,l as Oe,o as ke,p as Ae,r as je,v as Me,x as Ne}from"./tv-remote-runtime.js";import{a as Pe,n as Fe,o as Ie,s as Le,u as Re}from"./application-lifecycle-interaction.js";import{t as ze}from"./local-interactor-operation-set.js";import{n as Be,t as Ve}from"./network-traffic.js";import{a as He,n as Ue,t as We}from"./src4.js";import{n as Ge}from"./screen-recording-completion.js";import{a as _,c as Ke,l as qe,n as Je,o as Ye,s as Xe,t as Ze}from"./device-readiness-runtime.js";import{a as Qe,i as $e,n as et,r as tt,t as nt}from"./perf-runtime-operation-builder.js";import{t as rt}from"./app-log-runtime.js";import{t as it}from"./mp4-duration.js";import v from"node:path";async function y(e,t,n){let r=await p(e,[`emu`,...t],{signal:n,allowFailure:!0,timeoutMs:1e4});if(r.exitCode!==0)throw f(`adb emu ${t.slice(0,2).join(` `)} exited with code ${r.exitCode}`,r,{deviceId:e.id});let i=/^KO\b:?[ \t]*(.*)$/m.exec(r.stdout);return i?{stdout:r.stdout,refusal:i[1].trim()}:{stdout:r.stdout}}const b=Object.freeze({closed:{id:`1`,state:`CLOSED`},"half-open":{id:`2`,state:`HALF_OPENED`},open:{id:`3`,state:`OPENED`}});async function at(e,t,n={}){let{signal:r}=n;r?.throwIfAborted();let a=st(e,t),o=await ct(e,r),s=b[a],c=ot(e,a,o),l=a===`closed`&&await pt(e,r);return await lt(e,a,s.id,r),i({level:`info`,phase:`android_fold_pose_dispatched`,data:{deviceId:e.id,pose:a}}),await ut(e,a,c,o,r),a===`closed`&&!l&&await ft(e,r),{pose:a,hingeAngleDegrees:await mt(e,r)}}function ot(t,n,r){let i=b[n],a=r.get(i.state);if(a!==void 0)return a;let o=Object.keys(b).filter(e=>r.has(b[e].state)),s=o.map(e=>b[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 st(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 ct(e,t){let{stdout:n}=await x(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 lt(t,n,r,i){let a=await y(t,[`posture`,r],i);if(a.refusal!==void 0)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 ut(t,n,i,a,o){let s;for(let e=1;e<=60;e+=1)if(o?.throwIfAborted(),e>1&&await r(250,o),s=await dt(t,o),s===i)return;let c=[...a].find(([,e])=>e===s)?.[0];throw new e(`COMMAND_FAILED`,`${t.name} did not reach the ${n} pose: the emulator still reports device state ${c??s}`,{deviceId:t.id,requestedPose:n,observedDeviceState:c??s,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 dt(e,t){let{stdout:n}=await x(e,[`cmd`,`device_state`,`print-state`],t);return/\d+/.exec(n)?.[0]}async function ft(t,n){let a=0,o=!1;for(let e=1;e<=60;e+=1)if(await r(250,n),await pt(t,n))a=0,o=!0,await x(t,[`wm`,`dismiss-keyguard`],n);else if(a+=1,a>=3)break;if(a<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."});o&&i({level:`info`,phase:`android_fold_lock_screen_dismissed`,data:{deviceId:t.id}})}async function pt(e,t){let{stdout:n}=await x(e,[`dumpsys`,`window`],t);return n.includes(`isKeyguardShowing=true`)}async function mt(t,n){let{stdout:r}=await y(t,[`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 x(e,t,n){let r=await m(e,t,{signal:n,allowFailure:!0});if(r.exitCode!==0)throw f(`adb shell ${t.join(` `)} exited with code ${r.exitCode}`,r,{deviceId:e.id});return r}const ht=Object.freeze({available:!0}),gt=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 _t(e){return e.kind===`emulator`?ht:gt}function vt(e){return Xe({fold:_t(e)})}function yt(e){let{device:t,signal:n}=e;return o(vt(t).setFoldPose,()=>({setFoldPose:async e=>(n.throwIfAborted(),await at(t,e,{signal:n}))}))}async function bt(t,n,r){let i=await y(t,xt(n),r);if(i.refusal!==void 0)throw new e(`COMMAND_FAILED`,`The emulator console refused telephony ${n.action}`,{deviceId:t.id,reason:`telephony-console-refused`,stdout:i.stdout.trim(),...i.refusal?{consoleReason:i.refusal}:{},hint:`The emulator console refused the event. accept needs a call from that same number (start one with telephony call <number>), and an emulator image without a modem has no telephony to simulate.`})}function xt(e){switch(e.action){case`call`:case`accept`:case`cancel`:return[`gsm`,e.action,e.number];case`sms`:return[`sms`,`send`,e.number,St(e.text)]}}function St(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`
|
|
2
|
+
`,String.raw`\n`)}const Ct=Object.freeze({available:!0}),wt=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`telephony simulates calls and SMS through the Android emulator console; a physical device has no console, so place a real call or send a real message to it instead.`});function Tt(e){return e.kind===`emulator`?Ct:wt}function S(e){return Object.freeze({sendTelephonyEvent:Tt(e)})}function Et(e){let{device:t,signal:n}=e;return o(S(t).sendTelephonyEvent,()=>({sendTelephonyEvent:async e=>{n.throwIfAborted(),await bt(t,e,n)}}))}function Dt(e){return Ye(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 Ot(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...nt({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 $e(t().sampleFrames(n,e)):et(`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 $e(t().sampleMemory(n,e)):et(`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=kt();if(o!==`android-hprof`)return Qe(`Android`,o,s,`Use perf memory snapshot --kind android-hprof for Android Java heap artifacts.`);if(!e)throw tt();let c=i??v.join(a,`memory-android-hprof-${At()}.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 kt(){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 At(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}function C(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:rt,version:1,encode:e=>({...e}),decode:e=>e.transport!==`android-logcat-local`&&e.transport!==`android-logcat-transport-composed`||!Mt(e.outputPath)||!Mt(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 jt(e){let t=w.decode(e.descriptor);if(t.status!==`decoded`)throw TypeError(t.message);return ne({resourceKind:rt,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 Mt(e){return typeof e==`string`&&e.trim().length>0}function Nt(e){return We(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 Pt(e,t.id,r,n),validateStart:({input:e})=>C(e.appBundleId),process:async({host:e,device:t,input:n})=>({resolvePid:async r=>await Ue(e,Ft(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})=>jt({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function Pt(e,t,n,r){let i={};return i.adbAvailable=await qe(async()=>Ke(await e.commands.run({executable:`adb`,args:d(`adb`,`shell`,[`echo`,`ok`],[`-s`,t]),allowFailure:!0,timeoutMs:1e3},r)),r),n&&(i.androidPidVisible=await qe(async()=>!!await Ue(e,Ft(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 Ft(e,t){return{executable:`adb`,args:d(`adb`,`shell`,[`pidof`,t],[`-s`,e]),allowFailure:!0,timeoutMs:5e3}}async function It(e,t,n,r){let i=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),a=Be(i.text,{...n,path:i.path,exists:i.exists,lineNumberOffset:i.skippedLines,backend:`android`}),o=[],s=await Rt(e,t,n,r);if(s&&n.appBundleId){C(n.appBundleId);let c=await Bt(e,t,n.appBundleId,r);if(c){let e=Be(c.text,{...n,path:`${i.path} (adb logcat recovery)`,exists:!0,backend:`android`});e.dump.entries.length>0&&(a=Ve(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 Lt(e,t,n){n.throwIfAborted();try{let r=await e.commands.run(t,n);return n.throwIfAborted(),r}catch{n.throwIfAborted();return}}async function Rt(e,t,n,r){if(!n.appBundleId||n.appLogSnapshot?.state===void 0)return;if(n.appLogSnapshot.state!==`active`)return{reason:`inactive`};let i=zt(await e.appLogs.readProcessMarker(n.sessionId));if(!i)return;let a=await Vt(e,t.id,n.appBundleId,r);if(!(!a||a===i))return{reason:`stale-active`,trackedPid:i}}function zt(e){if(e.status===`decoded`)return/(?:^|\s)--pid\s+(\d+)(?:\s|$)/.exec(e.marker.command)?.[1]}async function Bt(e,t,n,r){let i=await Vt(e,t.id,n,r),a=await Lt(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=Ht(a.stdout,n,i);if(o.length===0)return;let s=new Set(o),c=a.stdout.split(`
|
|
3
3
|
`).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(`
|
|
4
4
|
`);return c.trim()?{text:c,pids:o}:void 0}async function Vt(e,t,n,r){let i=await Lt(e,{executable:`adb`,args:d(`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 Ht(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(`
|
|
5
|
-
`))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=y.parse(e);return y.join(n.dir,`${n.name}.part-${String(t).padStart(3,`0`)}${n.ext||`.mp4`}`)}const Ut=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-\d{1,20}\.mp4$/,Wt=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-active\.json$/;function Gt(e){return Jt(e)&&Yt(e)&&Xt(e)}function Kt(e){if(!E(e))return!1;let t=e;return Zt(t)&&Qt(t)&&$t(t)&&en(t)&&(t.completion===void 0||cn(t))}function qt(e,t){return ln(e,t)&&un(e,t.outputPath,t.clientOutputPath)}function Jt(e){return e.backend===`adb-screenrecord`&&typeof e.manifestPath==`string`&&Wt.test(e.manifestPath)&&typeof e.outputPath==`string`}function Yt(e){return fn(e.clientOutputPath)&&v(e)}function Xt(e){return dn(e.transportMode)}function Zt(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 Qt(e){return typeof e.outputPath==`string`&&fn(e.clientOutputPath)&&v(e)}function $t(e){return dn(e.transportMode)&&(e.pendingRemotePath===void 0||pn(e.pendingRemotePath))}function en(e){return Array.isArray(e.chunks)&&e.chunks.every(tn)&&(e.chunks.length>0||e.pendingRemotePath!==void 0)&&(e.completion===void 0||nn(e.completion))}function tn(e,t){if(!E(e))return!1;let n=e;return n.index===t+1&&pn(n.remotePath)&&mn(n.remotePid)&&mn(n.remoteStartTime)}function nn(e){if(!E(e))return!1;let t=e;return an(t)&&on(t)&&rn(t)&&(t.chunks===void 0||t.chunks.every(sn))}function rn(e){return(e.stopObservation===void 0||ee(e.stopObservation))&&(e.nativePathDisposition===void 0||g(e.nativePathDisposition))}function an(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 on(e){return v(e)}function sn(e,t){return e.index===t+1&&typeof e.path==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)}function cn(e){let t=e.completion;return t!==void 0&&ln(t,e)&&t.startedAt===e.startedAt&&un(t,e.outputPath,e.clientOutputPath,e.chunks.length)}function ln(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&&hn(e.activeSessionApp,t.activeSessionApp)}function un(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 dn(e){return e===`local`||e===`transport-composed`}function fn(e){return e===void 0||typeof e==`string`}function pn(e){return typeof e==`string`&&Ut.test(e)}function mn(e){return typeof e==`string`&&/^\d+$/.test(e)}function hn(e,t){return JSON.stringify(e)===JSON.stringify(t)}const D=Object.freeze({resourceKind:re,version:1,encode:e=>({...e}),decode:e=>Gt(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 gn(e,t){return Object.freeze({...e,completion:t})}function k(e){try{let t=e&&JSON.parse(e);return Kt(t)?t:void 0}catch{return}}function _n(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 vn(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||qt(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 yn(e){switch(e){case`missing`:case`ownership-lost`:return!0;case`foreign-writer`:case`owned-alive`:case`uncertain`:return!1}}const bn=1e4,xn=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 Sn(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 Dn(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&&Cn(i)&&!await On(e,i)?new j(t):r?.aborted?r.reason:t}}function Cn(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 I(e,a);a===n&&(r=t)}catch(e){i??=e}if(i)throw i;return r}async function wn(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 Tn(e,t,n){for(let[r,i]of t.entries())await kn(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 En(e,t){for(let n of t)if(await e.exists(n.remotePath)!==!1)return`retirable`;return`retired`}async function F(e,t){try{await N(e,t)}finally{await P(e,t)}}async function Dn(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 On(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 I(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 An(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 kn(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 jn(1e3)}throw Error(`failed to retrieve playable Android recording`)}async function An(e,t){for(let n=0;n<=bn;n+=xn){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<bn&&await jn(xn)}return!1}function jn(e){return new Promise(t=>setTimeout(t,e))}async function L(e,t,n,r){await e.writeManifest({manifestPath:t,contents:JSON.stringify(n)},r)}async function R(e,t){if(!await e.removeManifest(t))throw Error(`failed to remove Android recording manifest: ${t}`)}async function Mn(e,t){let n=(await Nn(e)).flatMap(n=>Pn(n,t,e.mode));for(let t of n)await In(e,t.evidence,t.manifestPath)}async function Nn(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 Pn(e,t,n){if(e.read.status===`missing`)return[];if(e.read.status!==`read`)throw zn(e.manifestPath,e.read.message);let r=k(e.read.contents);if(r===void 0)throw Bn(e.manifestPath);if(r.transportMode!==n)throw Vn(e.manifestPath,r,n);if(!Fn(r,t))throw Hn(e.manifestPath,r,t);return[{manifestPath:e.manifestPath,evidence:r}]}function Fn(e,t){return e.completion!==void 0||e.deviceId!==t.id}async function In(e,t,n){if(await Ln(e,t),await P(e,t.chunks),await Rn(e,t),await R(e,n),(await e.readManifest(n)).status!==`missing`)throw Gn(n)}async function Ln(e,t){for(let n of t.chunks){let t=await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime});if(!yn(t))throw t===`uncertain`?Kn(n.remotePath):Un(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 Un(n,`other-recorder`);if(!r.conclusive)throw Kn(n)}async function Rn(e,t){let n=t.pendingRemotePath;if(n!==void 0&&!await e.remove(n))throw Wn(n)}function zn(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 Bn(t){return new e(`COMMAND_FAILED`,`Android screenrecord native recovery evidence is unreadable: ${t}`,{reason:`native_recovery_evidence_unreadable`,manifestPath:t,hint:z(t)})}function Vn(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:z(t)})}function Hn(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, ${z(t)}`})}function Un(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 Wn(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 Gn(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 Kn(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 z(e){return`no recording session can retire this marker; remove it on the device with \`adb shell rm -f ${e}\`.`}async function qn(e){let{transport:t,device:n,input:r,startedAt:i,signal:a,prepareOutput:o}=e;await Mn(t,n),await o();let s;for(let e of M(void 0)){let o=t.manifestPathFor(e);await L(t,o,O(n,r,i,[],e,t.mode),a);let c,l;try{l=Date.now(),c=await Sn(t,e,r,a)}catch(e){if(a.aborted)throw await Jn(t,o,e),a.reason;await Zn(t,o,e),s=e;continue}try{await L(t,o,O(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 Jn(e,t,n){n instanceof j||await R(e,t).catch(()=>{})}async function Yn(e,t,n){try{await F(e,[n])}catch{return}await R(e,t).catch(()=>{})}async function Xn(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 L(t,o,O(n,r,i,a,e,t.mode));try{return await Sn(t,e,r)}catch(e){if(e instanceof j)throw e;try{await L(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 Zn(e,t,n){if(n instanceof j)throw n;try{await R(e,t)}catch{throw new j(n)}}function Qn(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 $n(e){let t=er(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 ${tr(t)}s of the ${tr(n)}s recording window.`}}function er(e){let t=0;for(let n of e){let e=rt(n);if(e===void 0)return;t+=e}return t}function tr(e){return(e/1e3).toFixed(1)}async function nr(e){let{host:t,transport:n,evidence:r,recording:i,startedAtMs:a,progress:o}=e,s=e.reachedLimit===!0;return await sr(e,await qe({snapshot:i,progress:o,steps:{stop:async()=>(s=await N(n,r.chunks)||s,await wn(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=>Tn(n,r.chunks,e),finalize:({collectedPath:e,exportPath:n,stoppedAtMs:o})=>rr({host:t,evidence:r,recording:i,startedAtMs:a,stoppedAtMs:o,collectedPath:e,exportPath:n}),discard:e=>ar(t,e,r.chunks.length)}}))}async function rr(e){let{host:t,evidence:n,recording:r,collectedPath:i,exportPath:a}=e,o=cr({collectedPath:i,exportPath:a,exportClientPath:r.clientOutPath,count:n.chunks.length}),s=o.length>1,c;try{await ir(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=$n({chunkPaths:o.map(({collected:e})=>e.path),startedAtMs:e.startedAtMs,stoppedAtMs:e.stoppedAtMs});return or({finalization:c,captured:l,recording:r,chunked:s,files:o})}async function ir(e,t){for(let{collected:n,served:r}of t)await e.screenRecording.outputs.copy({from:n.path,to:r.path})}async function ar(e,t,n){for(let r=1;r<=n;r+=1)await e.screenRecording.outputs.remove(T(t,r))}function or(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 sr(e,t){let{transport:n,evidence:r,manifestPath:i}=e;return await L(n,i,gn(r,t.result)),await P(n,r.chunks),{status:`completed`,result:{...t.result,nativePathDisposition:await En(n,r.chunks)}}}function cr(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 lr(e,t,n){try{let r=t.pendingRemotePath;if(await N(e,[...t.chunks,...await ur(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 R(e,n),{status:`cleaned`}}catch(e){return dr(e)}}async function ur(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 dr(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:String(e)}}async function fr(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&&_n(o,n,r)&&vn(o,i)?{status:`matched`,evidence:o}:{status:`ownership-lost`}}async function pr(e){let t=await e.transport.readManifest(e.manifestPath);if(t.status!==`read`)return;let n=k(t.contents);return n&&mr(n,e)?n:void 0}function mr(e,t){return e.deviceId===t.deviceId&&e.sessionId===t.sessionId&&e.fenceToken===t.fence.token&&e.fenceGeneration===t.fence.generation}async function hr(e){let{host:t,transport:n,device:r,input:i}=e,a=D.decode(i.envelope.descriptor.body);if(a.status!==`decoded`)return B(`descriptor-invalid`);let o=await fr({transport:n,device:r,envelope:i.envelope,descriptor:a.descriptor});return o.status===`matched`?await _r({host:t,transport:n,device:r,input:i,descriptor:a.descriptor,evidence:o.evidence}):B(o.status===`transport-unavailable`?`transport-not-reattachable`:`ownership-fence-lost`)}async function gr(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 fr({transport:e.transport,device:e.device,envelope:e.input.envelope,descriptor:t.descriptor});return n.status===`matched`?await lr(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 _r(e){let{host:t,transport:n,device:r,input:i,descriptor:a,evidence:o}=e;if(o.completion!==void 0){let e=await vr(n,o);return e.status===`terminal`?{status:`completed`,result:{...o.completion,nativePathDisposition:e.nativePathDisposition}}:B(`ownership-fence-lost`,`Android recording completed evidence still names a live or unverifiable recorder.`)}if(o.pendingRemotePath!==void 0)return B(`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 B(`transport-not-reattachable`,`Android recording process ended before its artifact could be recovered.`);let l=yr(i.envelope.sessionId,i.envelope.fence,a),u=!1;return{status:`active`,handle:We(Qn(l,o.startedAt),{finish:async(e,r)=>{let i=await nr({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 gr({transport:n,device:r,input:i})})}}async function vr(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 En(e,t.chunks)}}catch{return{status:`retained`}}}function yr(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 B(e,t){return{status:`unreattachable`,reason:e,...t===void 0?{}:{message:t}}}async function br(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 xr({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await hr({host:t,transport:a,device:n,input:e}),screenRecordingCleanup:async e=>await gr({transport:a,device:n,input:e})})}async function xr(e){let{host:t,transport:n,device:r,owner:i,input:o,signal:s}=e;s.throwIfAborted();let c=Date.now(),l=await qn({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 Xn({transport:n,device:r,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:y.posix.dirname(e.remotePath)})}catch(a){await I(n,e),t=!0;try{i=await Xn({transport:n,device:r,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:y.posix.dirname(e.remotePath)})}catch(e){throw e instanceof Error?e:a}}let a=[...d,{...i,index:d.length+1}];try{await L(n,u,O(r,o,c,a,void 0,n.mode))}catch(a){if(await F(n,[i]).catch(()=>{}),t)await L(n,u,O(r,o,c,d,i.remotePath,n.mode)).catch(()=>{});else try{await L(n,u,O(r,o,c,d,void 0,n.mode))}catch{await I(n,e).catch(()=>{}),await L(n,u,O(r,o,c,d,i.remotePath,n.mode)).catch(()=>{})}throw a}d=a,t||await I(n,e),g()};g();let ie=We(Qn(o,c),{finish:async(e,i)=>{if(f&&clearTimeout(f),await p,m)throw m;let a=await nr({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 pr({transport:n,deviceId:r.id,sessionId:o.sessionId,fence:o.fence,manifestPath:u});return e?await lr(n,e,u):{status:`cleanup-pending`,reason:`ownership-fence-lost`}}});return Object.freeze({pendingHandle:new se(ie),envelope:ne({resourceKind:re,sessionId:o.sessionId,device:a(r),owner:i,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 Sr=1e3;async function V(e,t,n,r){return r.throwIfAborted(),t.kind===`emulator`&&(t.booted!==!0||!H(t))?await Cr(e,t,n,r):(t.booted!==!0&&await Dr(e,t.id,kr(e,n),r),{...t,booted:!0})}async function Cr(e,t,n,r){await wr(e);let i=Ar(n),a=kr(e,n),o=Tr(await e.deviceReadiness.androidEmulator.discover(i,r),t.name,n.serial),s=H(o)?o:void 0,c=s?void 0:await e.deviceReadiness.androidEmulator.launch(o.name,n.headless,a-e.clock.now());try{let t=s??await Er(e,o.name,i,n.serial,a,r);return await Dr(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 wr(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 Tr(t,n,r){let i=jr(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 Er(e,t,n,r,i,a){for(;e.clock.now()<i;){let i=jr(await e.deviceReadiness.androidEmulator.discover(n,a),t,r);if(i&&H(i))return i;await e.clock.sleep(Sr,a)}throw Or(`Android emulator did not appear in time`,{avdName:t,serial:r})}async function Dr(e,t,n,r){for(;e.clock.now()<n;){if((await e.commands.run({executable:`adb`,args:d(`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(Sr,r)}throw Or(`Android device failed to finish booting`,{serial:t})}function Or(t,n){return new e(`COMMAND_FAILED`,t,{...n,reason:Xe,hint:`The emulator keeps booting in the background. Retry once it is up, or pass a larger --timeout.`})}function kr(e,t){return t.deadlineAtMs??e.clock.now()+12e4}function Ar(e){return{platform:`android`,kind:`emulator`,...e.serial?{serial:e.serial}:{},...e.androidSerialAllowlist?{androidSerialAllowlist:[...e.androidSerialAllowlist]}:{}}}function jr(e,t,n){let r=Mr(t);return e.find(e=>e.platform===`android`&&e.kind===`emulator`&&Mr(e.name)===r&&(!n||!H(e)||e.id===n))}function H(e){return e.id.startsWith(`emulator-`)}function Mr(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}async function Nr(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(),u(e)?{observation:`unobservable`}:{observation:`probe-failed`,failure:Pr(e)}}}function Pr(e){let n=t(e),r=l(n)??n.details?.reason,{code:i}=n;return typeof r==`string`?{source:`capture`,code:i,reason:r}:{source:`capture`,code:i}}function Fr(t){let{host:n,device:r,signal:i}=t,a=Pe({device:r,signal:i,resolveInteractor:n.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async e=>await n.androidApplications.resolveOpenTarget(r,e),prepareApplicationOpen:async e=>{await V(n,r,{headless:!1,deadlineAtMs:e.execution.startupDeadlineAtMs},i)},openApplication:async e=>await Ir(n,a,e),applyRuntimeHints:async e=>await n.androidApplications.applyRuntimeHints(r,e),clearRuntimeHints:async e=>await n.androidApplications.clearRuntimeHints(r,e),closeApplication:async t=>{if(t.ensureReady&&await V(n,r,{headless:!1},i),t.mode===`kill`){let[n]=t.positionals;if(!n)throw new e(`INVALID_ARGS`,`Kill requires an app target`);let{killAndroidApp:i}=await import(`./app-lifecycle.js`).then(e=>e.n);await i(r,n);return}await Fe({device:r,interactor:await a.resolveInteractor(t.execution,t.appBundleId),positionals:t.positionals})},finalizeApplicationClose:async e=>{await n.androidApplications.restoreTestIme(r,{stateDir:e.stateDir,shutdownTarget:e.shutdownTarget===!0&&r.kind===`emulator`,signal:i});let t=e.shutdownTarget&&r.kind===`emulator`?await n.deviceShutdown.android.shutdownTarget(r,i):void 0;return t===void 0?{}:{shutdown:t}},prepareAppleRunner:Rr,configureProviderPortReverse:Rr})}async function Ir(t,n,r){let i={},a=r.relaunch&&!!r.target,o=a?r.appBundleId:void 0;if(o){let e=Date.now();await Fe({device:n.device,interactor:await n.resolveInteractor(r.execution,o),positionals:[o]}),i.relaunchCloseDurationMs=U(e)}if(ae(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=U(t)}let s=Date.now(),c=await Ie({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:r.positionals,appBundleId:r.appBundleId,execution:r.execution,terminateRunningApp:a&&!o});i.openDispatchDurationMs=U(s),r.enableTestIme&&await t.androidApplications.activateTestIme(n.device,{stateDir:r.stateDir});let l=Ne(r);if(l){let e=Date.now();await Ie({device:n.device,interactor:await n.resolveInteractor({...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},r.appBundleId),positionals:[l],appBundleId:r.appBundleId,execution:{...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}}),i.launchUrlDurationMs=U(e)}else i.launchUrlDurationMs=0;let u=await t.androidApplications.inferOpenedAppBundleId(n.device,r.target,r.appBundleId,c?.launchedAppBundleId);u&&await t.androidApplications.resetFramePerfStats(n.device,u);let d=Date.now();return Object.assign(i,await Lr(n,r,u)),i.postOpenSettleDurationMs=U(d),{appBundleId:u,timing:i}}async function Lr(e,t,r){if(!t.target||n(t.target))return{};if(!r)return{postOpenObservation:`app-unidentified`};let i=await Nr(await e.resolveInteractor(t.execution,r),r,e.signal);return i.observation===`probe-failed`?{postOpenObservation:`probe-failed`,postOpenObservationFailure:i.failure}:{postOpenObservation:i.observation}}function U(e){return Math.max(0,Date.now()-e)}async function Rr(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Android.`)}async function W(e,t,n,r,i){let a=r?void 0:await Ur(e,t,i);if(y.extname(n).toLowerCase()===`.aab`?await Hr(e,t,n,i):K(await e.androidTools.installPackage(t,n,{replace:!0},i),`adb install failed`),r)return r;let o=[...await Ur(e,t,i)].filter(e=>!a?.has(e));return o.length===1?o[0]:void 0}async function zr(e,t,n,r){let i=await G(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`)||K(i,`adb uninstall failed for ${n}`)}async function Br(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 l=0;for(let[e,t]of Object.entries(c))e&&(Wr(s,e,t),l+=1);return K(await G(t,n,d(`adb`,`shell`,s),i),`adb push broadcast failed`),{action:o,extrasCount:l}}function Vr(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 Hr(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{K(await t.commands.run({executable:s,args:[...c,`build-apks`,`--bundle`,r,`--output`,u,`--mode`,`universal`]},i),`bundletool build-apks failed`),K(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 Ur(e,t,n){let r=await G(e,t,d(`adb`,`shell`,[`pm`,`list`,`packages`]),n);return K(r,`adb package inventory failed`),new Set(r.stdout.split(`
|
|
6
|
-
`).map(e=>e.replace(`package:`,``).trim()).filter(Boolean))}function Wr(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 G(e,t,n,r,i=15e3){return await e.androidTools.runAdb(t,n,{timeoutMs:i,allowFailure:!0},r)}function K(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 Gr=Object.freeze({available:!0});function Kr(e){let t=Zr(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:t,uninstallApp:t})}function qr(e){let{host:t,device:n,signal:r}=e;return Kr(n).deployApp.available?Object.freeze({deployApp:async e=>await Yr(t,n,e,r),materializeAppSource:async e=>await t.androidDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await Xr(t,n,e,r),sendPushNotification:async e=>await Br(t,n,e,r),uninstallApp:async e=>await Jr(t,n,e,r)}):Object.freeze({})}async function Jr(t,n,r,i){let a=n.booted===!0?n:await
|
|
5
|
+
`))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=v.parse(e);return v.join(n.dir,`${n.name}.part-${String(t).padStart(3,`0`)}${n.ext||`.mp4`}`)}const Ut=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-\d{1,20}\.mp4$/,Wt=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-active\.json$/;function Gt(e){return Jt(e)&&Yt(e)&&Xt(e)}function Kt(e){if(!E(e))return!1;let t=e;return Zt(t)&&Qt(t)&&$t(t)&&en(t)&&(t.completion===void 0||cn(t))}function qt(e,t){return ln(e,t)&&un(e,t.outputPath,t.clientOutputPath)}function Jt(e){return e.backend===`adb-screenrecord`&&typeof e.manifestPath==`string`&&Wt.test(e.manifestPath)&&typeof e.outputPath==`string`}function Yt(e){return fn(e.clientOutputPath)&&_(e)}function Xt(e){return dn(e.transportMode)}function Zt(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 Qt(e){return typeof e.outputPath==`string`&&fn(e.clientOutputPath)&&_(e)}function $t(e){return dn(e.transportMode)&&(e.pendingRemotePath===void 0||pn(e.pendingRemotePath))}function en(e){return Array.isArray(e.chunks)&&e.chunks.every(tn)&&(e.chunks.length>0||e.pendingRemotePath!==void 0)&&(e.completion===void 0||nn(e.completion))}function tn(e,t){if(!E(e))return!1;let n=e;return n.index===t+1&&pn(n.remotePath)&&mn(n.remotePid)&&mn(n.remoteStartTime)}function nn(e){if(!E(e))return!1;let t=e;return an(t)&&on(t)&&rn(t)&&(t.chunks===void 0||t.chunks.every(sn))}function rn(e){return(e.stopObservation===void 0||ee(e.stopObservation))&&(e.nativePathDisposition===void 0||g(e.nativePathDisposition))}function an(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 on(e){return _(e)}function sn(e,t){return e.index===t+1&&typeof e.path==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)}function cn(e){let t=e.completion;return t!==void 0&&ln(t,e)&&t.startedAt===e.startedAt&&un(t,e.outputPath,e.clientOutputPath,e.chunks.length)}function ln(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&&hn(e.activeSessionApp,t.activeSessionApp)}function un(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 dn(e){return e===`local`||e===`transport-composed`}function fn(e){return e===void 0||typeof e==`string`}function pn(e){return typeof e==`string`&&Ut.test(e)}function mn(e){return typeof e==`string`&&/^\d+$/.test(e)}function hn(e,t){return JSON.stringify(e)===JSON.stringify(t)}const D=Object.freeze({resourceKind:re,version:1,encode:e=>({...e}),decode:e=>Gt(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 gn(e,t){return Object.freeze({...e,completion:t})}function k(e){try{let t=e&&JSON.parse(e);return Kt(t)?t:void 0}catch{return}}function _n(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 vn(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||qt(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 yn(e){switch(e){case`missing`:case`ownership-lost`:return!0;case`foreign-writer`:case`owned-alive`:case`uncertain`:return!1}}const bn=1e4,xn=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 Sn(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 On(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&&Cn(i)&&!await kn(e,i)?new j(t):r?.aborted?r.reason:t}}function Cn(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 wn(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 Tn(e,t,n){for(let[r,i]of t.entries())await An(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 En(e,t){for(let n of t)if(await e.exists(n.remotePath)!==!1)return`retirable`;return`retired`}async function Dn(e,t){try{await N(e,t)}finally{await P(e,t)}}async function On(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 kn(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 jn(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 An(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 Mn(1e3)}throw Error(`failed to retrieve playable Android recording`)}async function jn(e,t){for(let n=0;n<=bn;n+=xn){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<bn&&await Mn(xn)}return!1}function Mn(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 Nn(e,t){let n=(await Pn(e)).flatMap(n=>Fn(n,t,e.mode));for(let t of n)await Ln(e,t.evidence,t.manifestPath)}async function Pn(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 Fn(e,t,n){if(e.read.status===`missing`)return[];if(e.read.status!==`read`)throw Bn(e.manifestPath,e.read.message);let r=k(e.read.contents);if(r===void 0)throw Vn(e.manifestPath);if(r.transportMode!==n)throw Hn(e.manifestPath,r,n);if(!In(r,t))throw Un(e.manifestPath,r,t);return[{manifestPath:e.manifestPath,evidence:r}]}function In(e,t){return e.completion!==void 0||e.deviceId!==t.id}async function Ln(e,t,n){if(await Rn(e,t),await P(e,t.chunks),await zn(e,t),await L(e,n),(await e.readManifest(n)).status!==`missing`)throw Kn(n)}async function Rn(e,t){for(let n of t.chunks){let t=await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime});if(!yn(t))throw t===`uncertain`?qn(n.remotePath):Wn(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 Wn(n,`other-recorder`);if(!r.conclusive)throw qn(n)}async function zn(e,t){let n=t.pendingRemotePath;if(n!==void 0&&!await e.remove(n))throw Gn(n)}function Bn(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 Vn(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 Hn(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 Un(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 Wn(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 Gn(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 Kn(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 qn(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 Jn(e){let{transport:t,device:n,input:r,startedAt:i,signal:a,prepareOutput:o}=e;await Nn(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 Sn(t,e,r,a)}catch(e){if(a.aborted)throw await Yn(t,o,e),a.reason;await Qn(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 Xn(t,o,c),e}return{chunk:c,manifestPath:o,startedAtMs:l}}throw s??Error(`Android screenrecord did not begin producing frames`)}async function Yn(e,t,n){n instanceof j||await L(e,t).catch(()=>{})}async function Xn(e,t,n){try{await Dn(e,[n])}catch{return}await L(e,t).catch(()=>{})}async function Zn(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 Sn(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 Qn(e,t,n){if(n instanceof j)throw n;try{await L(e,t)}catch{throw new j(n)}}function $n(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 er(e){let t=tr(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 ${nr(t)}s of the ${nr(n)}s recording window.`}}function tr(e){let t=0;for(let n of e){let e=it(n);if(e===void 0)return;t+=e}return t}function nr(e){return(e/1e3).toFixed(1)}async function rr(e){let{host:t,transport:n,evidence:r,recording:i,startedAtMs:a,progress:o}=e,s=e.reachedLimit===!0;return await cr(e,await Je({snapshot:i,progress:o,steps:{stop:async()=>(s=await N(n,r.chunks)||s,await wn(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=>Tn(n,r.chunks,e),finalize:({collectedPath:e,exportPath:n,stoppedAtMs:o})=>ir({host:t,evidence:r,recording:i,startedAtMs:a,stoppedAtMs:o,collectedPath:e,exportPath:n}),discard:e=>or(t,e,r.chunks.length)}}))}async function ir(e){let{host:t,evidence:n,recording:r,collectedPath:i,exportPath:a}=e,o=lr({collectedPath:i,exportPath:a,exportClientPath:r.clientOutPath,count:n.chunks.length}),s=o.length>1,c;try{await ar(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=er({chunkPaths:o.map(({collected:e})=>e.path),startedAtMs:e.startedAtMs,stoppedAtMs:e.stoppedAtMs});return sr({finalization:c,captured:l,recording:r,chunked:s,files:o})}async function ar(e,t){for(let{collected:n,served:r}of t)await e.screenRecording.outputs.copy({from:n.path,to:r.path})}async function or(e,t,n){for(let r=1;r<=n;r+=1)await e.screenRecording.outputs.remove(T(t,r))}function sr(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 cr(e,t){let{transport:n,evidence:r,manifestPath:i}=e;return await I(n,i,gn(r,t.result)),await P(n,r.chunks),{status:`completed`,result:{...t.result,nativePathDisposition:await En(n,r.chunks)}}}function lr(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 ur(e,t,n){try{let r=t.pendingRemotePath;if(await N(e,[...t.chunks,...await dr(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 fr(e)}}async function dr(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 fr(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:String(e)}}async function pr(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&&_n(o,n,r)&&vn(o,i)?{status:`matched`,evidence:o}:{status:`ownership-lost`}}async function mr(e){let t=await e.transport.readManifest(e.manifestPath);if(t.status!==`read`)return;let n=k(t.contents);return n&&hr(n,e)?n:void 0}function hr(e,t){return e.deviceId===t.deviceId&&e.sessionId===t.sessionId&&e.fenceToken===t.fence.token&&e.fenceGeneration===t.fence.generation}async function gr(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 pr({transport:n,device:r,envelope:i.envelope,descriptor:a.descriptor});return o.status===`matched`?await vr({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 _r(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 pr({transport:e.transport,device:e.device,envelope:e.input.envelope,descriptor:t.descriptor});return n.status===`matched`?await ur(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 vr(e){let{host:t,transport:n,device:r,input:i,descriptor:a,evidence:o}=e;if(o.completion!==void 0){let e=await yr(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=br(i.envelope.sessionId,i.envelope.fence,a),u=!1;return{status:`active`,handle:Ge($n(l,o.startedAt),{finish:async(e,r)=>{let i=await rr({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 _r({transport:n,device:r,input:i})})}}async function yr(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 En(e,t.chunks)}}catch{return{status:`retained`}}}function br(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 xr(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 Sr({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await gr({host:t,transport:a,device:n,input:e}),screenRecordingCleanup:async e=>await _r({transport:a,device:n,input:e})})}async function Sr(e){let{host:t,transport:n,device:r,owner:i,input:o,signal:s}=e;s.throwIfAborted();let c=Date.now(),l=await Jn({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 Zn({transport:n,device:r,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:v.posix.dirname(e.remotePath)})}catch(a){await F(n,e),t=!0;try{i=await Zn({transport:n,device:r,input:o,startedAt:c,chunks:d,manifestPath:u,preferredDir:v.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 Dn(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 ie=Ge($n(o,c),{finish:async(e,i)=>{if(f&&clearTimeout(f),await p,m)throw m;let a=await rr({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 mr({transport:n,deviceId:r.id,sessionId:o.sessionId,fence:o.fence,manifestPath:u});return e?await ur(n,e,u):{status:`cleanup-pending`,reason:`ownership-fence-lost`}}});return Object.freeze({pendingHandle:new se(ie),envelope:ne({resourceKind:re,sessionId:o.sessionId,device:a(r),owner:i,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 Cr=1e3;async function B(e,t,n,r){return r.throwIfAborted(),t.kind===`emulator`&&(t.booted!==!0||!V(t))?await wr(e,t,n,r):(t.booted!==!0&&await Or(e,t.id,Ar(e,n),r),{...t,booted:!0})}async function wr(e,t,n,r){await Tr(e);let i=jr(n),a=Ar(e,n),o=Er(await e.deviceReadiness.androidEmulator.discover(i,r),t.name,n.serial),s=V(o)?o:void 0,c=s?void 0:await e.deviceReadiness.androidEmulator.launch(o.name,n.headless,a-e.clock.now());try{let t=s??await Dr(e,o.name,i,n.serial,a,r);return await Or(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 Tr(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 Er(t,n,r){let i=Mr(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 Dr(e,t,n,r,i,a){for(;e.clock.now()<i;){let i=Mr(await e.deviceReadiness.androidEmulator.discover(n,a),t,r);if(i&&V(i))return i;await e.clock.sleep(Cr,a)}throw kr(`Android emulator did not appear in time`,{avdName:t,serial:r})}async function Or(e,t,n,r){for(;e.clock.now()<n;){if((await e.commands.run({executable:`adb`,args:d(`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(Cr,r)}throw kr(`Android device failed to finish booting`,{serial:t})}function kr(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 Ar(e,t){return t.deadlineAtMs??e.clock.now()+12e4}function jr(e){return{platform:`android`,kind:`emulator`,...e.serial?{serial:e.serial}:{},...e.androidSerialAllowlist?{androidSerialAllowlist:[...e.androidSerialAllowlist]}:{}}}function Mr(e,t,n){let r=H(t);return e.find(e=>e.platform===`android`&&e.kind===`emulator`&&H(e.name)===r&&(!n||!V(e)||e.id===n))}function V(e){return e.id.startsWith(`emulator-`)}function H(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}async function Nr(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(),u(e)?{observation:`unobservable`}:{observation:`probe-failed`,failure:Pr(e)}}}function Pr(e){let n=t(e),r=l(n)??n.details?.reason,{code:i}=n;return typeof r==`string`?{source:`capture`,code:i,reason:r}:{source:`capture`,code:i}}function Fr(t){let{host:n,device:r,signal:i}=t,a=Fe({device:r,signal:i,resolveInteractor:n.localInteractors.resolve});return Object.freeze({resolveOpenTarget:async e=>await n.androidApplications.resolveOpenTarget(r,e),prepareApplicationOpen:async e=>{await B(n,r,{headless:!1,deadlineAtMs:e.execution.startupDeadlineAtMs},i)},openApplication:async e=>await Ir(n,a,e),applyRuntimeHints:async e=>await n.androidApplications.applyRuntimeHints(r,e),clearRuntimeHints:async e=>await n.androidApplications.clearRuntimeHints(r,e),closeApplication:async t=>{if(t.ensureReady&&await B(n,r,{headless:!1},i),t.mode===`kill`){let[n]=t.positionals;if(!n)throw new e(`INVALID_ARGS`,`Kill requires an app target`);let{killAndroidApp:i}=await import(`./app-lifecycle.js`).then(e=>e.n);await i(r,n);return}await Ie({device:r,interactor:await a.resolveInteractor(t.execution,t.appBundleId),positionals:t.positionals})},finalizeApplicationClose:async e=>{await n.androidApplications.restoreTestIme(r,{stateDir:e.stateDir,shutdownTarget:e.shutdownTarget===!0&&r.kind===`emulator`,signal:i});let t=e.shutdownTarget&&r.kind===`emulator`?await n.deviceShutdown.android.shutdownTarget(r,i):void 0;return t===void 0?{}:{shutdown:t}},prepareAppleRunner:Rr,configureProviderPortReverse:Rr})}async function Ir(t,n,r){let i={},a=r.relaunch&&!!r.target,o=a?r.appBundleId:void 0;if(o){let e=Date.now();await Ie({device:n.device,interactor:await n.resolveInteractor(r.execution,o),positionals:[o]}),i.relaunchCloseDurationMs=U(e)}if(ae(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=U(t)}let s=Date.now(),c=await Le({device:n.device,interactor:await n.resolveInteractor(r.execution,r.appBundleId),positionals:r.positionals,appBundleId:r.appBundleId,execution:r.execution,terminateRunningApp:a&&!o});i.openDispatchDurationMs=U(s),r.enableTestIme&&await t.androidApplications.activateTestIme(n.device,{stateDir:r.stateDir});let l=Pe(r);if(l){let e=Date.now();await Le({device:n.device,interactor:await n.resolveInteractor({...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0},r.appBundleId),positionals:[l],appBundleId:r.appBundleId,execution:{...r.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}}),i.launchUrlDurationMs=U(e)}else i.launchUrlDurationMs=0;let u=await t.androidApplications.inferOpenedAppBundleId(n.device,r.target,r.appBundleId,c?.launchedAppBundleId);u&&await t.androidApplications.resetFramePerfStats(n.device,u);let d=Date.now();return Object.assign(i,await Lr(n,r,u)),i.postOpenSettleDurationMs=U(d),{appBundleId:u,timing:i}}async function Lr(e,t,r){if(!t.target||n(t.target))return{};if(!r)return{postOpenObservation:`app-unidentified`};let i=await Nr(await e.resolveInteractor(t.execution,r),r,e.signal);return i.observation===`probe-failed`?{postOpenObservation:`probe-failed`,postOpenObservationFailure:i.failure}:{postOpenObservation:i.observation}}function U(e){return Math.max(0,Date.now()-e)}async function Rr(){throw new e(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for Android.`)}async function W(e,t,n,r,i){let a=r?void 0:await Ur(e,t,i);if(v.extname(n).toLowerCase()===`.aab`?await Hr(e,t,n,i):K(await e.androidTools.installPackage(t,n,{replace:!0},i),`adb install failed`),r)return r;let o=[...await Ur(e,t,i)].filter(e=>!a?.has(e));return o.length===1?o[0]:void 0}async function zr(e,t,n,r){let i=await G(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`)||K(i,`adb uninstall failed for ${n}`)}async function Br(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 l=0;for(let[e,t]of Object.entries(c))e&&(Wr(s,e,t),l+=1);return K(await G(t,n,d(`adb`,`shell`,s),i),`adb push broadcast failed`),{action:o,extrasCount:l}}function Vr(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 Hr(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{K(await t.commands.run({executable:s,args:[...c,`build-apks`,`--bundle`,r,`--output`,u,`--mode`,`universal`]},i),`bundletool build-apks failed`),K(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 Ur(e,t,n){let r=await G(e,t,d(`adb`,`shell`,[`pm`,`list`,`packages`]),n);return K(r,`adb package inventory failed`),new Set(r.stdout.split(`
|
|
6
|
+
`).map(e=>e.replace(`package:`,``).trim()).filter(Boolean))}function Wr(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 G(e,t,n,r,i=15e3){return await e.androidTools.runAdb(t,n,{timeoutMs:i,allowFailure:!0},r)}function K(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 Gr=Object.freeze({available:!0});function Kr(e){let t=Zr(e);return Object.freeze({deployApp:t,materializeAppSource:t,deployMaterializedApp:t,sendPushNotification:t,uninstallApp:t})}function qr(e){let{host:t,device:n,signal:r}=e;return Kr(n).deployApp.available?Object.freeze({deployApp:async e=>await Yr(t,n,e,r),materializeAppSource:async e=>await t.androidDeployment.prepareArtifact(e,{signal:r}),deployMaterializedApp:async e=>await Xr(t,n,e,r),sendPushNotification:async e=>await Br(t,n,e,r),uninstallApp:async e=>await Jr(t,n,e,r)}):Object.freeze({})}async function Jr(t,n,r,i){let a=n.booted===!0?n:await B(t,n,{headless:!1},i);return await t.androidDeployment.withInvalidatedAppResolutionCache(a,async()=>{let n;try{n=await t.androidDeployment.resolveAppPackage(a,r.app,{installedOnly:!0})}catch(t){if(t instanceof e&&t.code===`APP_NOT_INSTALLED`&&h(r.app)===`package`)return{wasInstalled:!1};throw t}return await zr(t,a,n,i),{wasInstalled:!0,packageName:n}})}async function Yr(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 zr(e,t,a,r),i=await e.androidDeployment.prepareArtifact({source:{kind:`path`,path:n.appPath}},{resolveIdentity:!1,signal:r}),await W(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 W(e,t,i.installablePath,i.packageName,r);return a?{packageName:a,appName:Vr(a),launchTarget:a}:{}}finally{await i?.cleanup()}}async function Xr(t,n,r,i){let a=await W(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:Vr(a),launchTarget:a}}function Zr(e){return e.kind===`emulator`||e.kind===`device`?Gr:Object.freeze({available:!1,reason:`unsupported-device-kind`})}const q=s(`android`),J=Object.freeze({available:!0}),Qr=c(`unsupported-device-kind`),$r=c(`unsupported-platform-leaf`,"Run `agent-device settings --help` for the settings each target serves."),ei=c(`unsupported-device-kind`,`focus is supported on Android emulators and physical devices.`),ti=c(`unsupported-device-kind`,`keyboard actions are supported on Android emulators and physical devices.`),ni=c(`unsupported-platform-leaf`),ri=c(`unsupported-platform-leaf`,`Android has no key event for this system button.`),ii=c(`unsupported-device-kind`,`Headless boot is supported only for Android emulators.`),ai=c(`unsupported-device-kind`,`Android appstate is supported only for Android emulators and devices.`),oi=c(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),si=c(`unsupported-device-kind`,`open is supported only for Android emulators and devices.`),ci=c(`unsupported-device-kind`,`close is supported only for Android emulators and devices.`),li=c(`unsupported-device-kind`,`Runtime hints are supported only for Android emulators and devices.`),ui=c(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),di=c(`unsupported-device-kind`,`shutdown is supported only for Apple simulators and Android emulators.`),fi=c(`unsupported-device-kind`,`screenshot is supported only for Android emulators and devices.`),Y=c(`unsupported-device-kind`,`snapshot is supported only for Android emulators and devices.`),pi=c(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),mi=c(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web).`),hi=c(`unsupported-platform-leaf`,`the stateless audio page probe is a web-session operation; Android targets use the host capture.`);function gi(e){let t=_i(e),n=vi(e),r=yi(e);return oe({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:r,clearRuntimeHints:r,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:oi,configureProviderPortReverse:ui})}function _i(e){return e.kind===`emulator`||e.kind===`device`?J:si}function vi(e){return e.kind===`emulator`||e.kind===`device`?J:ci}function yi(e){return e.kind===`emulator`||e.kind===`device`?J:li}const X=c(`unsupported-device-kind`,`Gestures are supported on Android emulators and physical devices.`),bi=c(`unsupported-platform-leaf`,ue),xi=c(`unsupported-platform-leaf`,le);function Si(e,t){return e.kind===`simulator`?X:e.target===`tv`?t:J}function Z(e){return e.kind===`simulator`?X:J}function Q(e){return e.kind===`simulator`?ei:J}const $=c(`owner-capability-missing`,fe),Ci=c(`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 wi(e,t){let n=e.androidTools?.probeClipboardShellSupport;return n?await n.call(e.androidTools,t):`probe-failed`}const Ti=c(`unsupported-device-kind`,`tv-remote is supported only on Android TV targets.`);function Ei(e){return e.kind!==`simulator`&&e.target===`tv`?J:Ti}function Di(e){let t=Nt(e),n=new Map,r=async t=>{if(t.kind===`simulator`)return $;let r=n.get(t.id)??await wi(e,t);return r!==`probe-failed`&&n.set(t.id,r),r===`supported`?J:r===`unsupported`?$:Ci},i=async e=>{let n=await t.inspectFacts(e),i=Kr(e),a=await r(e);return Object.freeze({device:n.device,operations:{...n.operations,...i,appState:e.kind===`simulator`?ai:J,networkDump:J,screenRecordingStart:J,screenRecordingReattach:J,screenRecordingCleanup:J,..._e({capture:e.kind===`simulator`?Y:J,customActions:pi,withoutActiveApp:e.kind===`simulator`?Y:J}),...he({capture:e.kind===`simulator`?fi:J}),...ve({findText:Y,querySelector:Y}),...xe({setViewport:mi}),...Ce({focus:Q(e)}),...ge({unsupported:X,plan:Z(e),directionalFling:Z(e),multiTouch:Si(e,bi),targetAuthoredDrag:Si(e,xi),viewport:Z(e)}),...Se({scroll:Z(e)}),...ye({type:Q(e)}),...ce({unsupported:ei,tap:Q(e),longPress:Q(e),hover:ni,fill:Q(e)}),...we({readTextAtPoint:e.kind===`simulator`?Qr:J}),...me({back:Q(e)}),...Te({unsupported:ri,home:Q(e),appSwitcher:Q(e),...Ee(e)}),...vt(e),...S(e),...Me({triggerAppEvent:Q(e)}),...Re({target:Q(e),unsupported:$r,write:{wifi:J,bluetooth:J,airplane:J,"mobile-data":J,location:J,animations:J,appearance:J,"text-size":J,fingerprint:J,"clear-app-state":J,permission:J},read:{"text-size":J}}),...Ne({read:Q(e),wait:Q(e),accept:Q(e),dismiss:Q(e)}),...ke({orientation:Q(e),unlock:Q(e)}),...je({tvRemote:Ei(e)}),...Oe({unsupported:ti,status:Q(e),dismiss:Q(e),enter:Q(e)}),...Ae({unsupported:a.available?$:a,read:a,write:a}),...pe({capture:Dt(e),query:hi}),...be({frames:Q(e),memorySample:Q(e),memorySnapshot:Q(e),nativeCapture:Q(e),profileReport:Q(e)}),ensureReady:J,bootTarget:J,bootTargetHeadless:e.kind===`emulator`?J:ii,listApps:J,...gi(e),shutdownTarget:e.kind===`emulator`?J:di}})};return Object.freeze({owner:q,ownsDevice:e=>e.platform===`android`,inspectFacts:i,bind:async n=>{let r=await t.bind(n),a=await i(n.device),s=await xr({host:e,device:n.device,owner:q,signal:n.scope.signal});return Object.freeze({device:r.device,owner:q,facts:a,operations:Object.freeze({...r.operations,...qr({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 de(async(t,r)=>await e(n.device,t,{...r,signal:n.scope.signal}),n.scope.signal)}}:{},networkDump:async t=>await It(e,n.device,t,n.scope.signal),...s,...o(a.operations.audioProbeStart,()=>He({host:e.audioProbe.hostCapture,device:n.device,owner:q})),...o(a.operations.perfFrames,()=>Ot({resolveHost:()=>e.perf.android,device:n.device,owner:q})),...Oi(e,n,a),...yt({device:n.device,signal:n.scope.signal}),...Et({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}))},...ie(Fr({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 Oi(e,t,n){let r={device:t.device,signal:t.scope.signal,resolveInteractor:e.localInteractors.resolve};return{...n.operations.captureSnapshot.available?De(r):{},...ze({...r,facts:n.operations,pause:async n=>await e.clock.sleep(n,t.scope.signal)})}}export{Di as createAndroidPlatformRuntime};
|
package/dist/src/runtime10.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{R as e,V as t,Z as n,q as r}from"./sdk-contracts.js";import{a as i}from"./tv-remote.js";import{Z as a,lt as o}from"./sdk-io.js";import{i as s}from"./recording-export-quality.js";import"./command-metadata.js";import{r as c}from"./success-text.js";import{n as l,t as u}from"./app-inventory.js";import"./file.js";import"./command.js";import{r as d}from"./version.js";import{t as f}from"./keyboard-actions.js";import{m as p}from"./selector-pipeline-policy.js";import{i as ee}from"./png-worker-client.js";import{o as m}from"./png-worker-contract.js";import{t as te}from"./png-encode.js";import{n as ne}from"./png-resize.js";import{t as re}from"./png-size.js";import{i as h,n as ie,r as ae}from"./screenshot-overlay-draw.js";import{r as g}from"./artifact-paths.js";import{t as oe}from"./mp4-duration.js";import{a as se,c as _,i as v,l as y,n as ce,o as le,r as b,s as x,t as ue}from"./runtime-factory.js";import{c as de,o as fe,r as pe,s as me}from"./video.js";import S from"node:fs";import he from"node:os";import C from"node:path";function w(e,t){if(e!==void 0)return T(e,t)}function T(t,n){let r=t?.trim();if(!r)throw new e(`INVALID_ARGS`,`${n} must be a non-empty string`);return r}const ge=async(t,n={})=>{if(!t.backend.listDevices)throw new e(`UNSUPPORTED_OPERATION`,`admin.devices is not supported by this backend`);return{kind:`adminDevices`,devices:await t.backend.listDevices(y(t,n),n.filter)}},_e=async(t,n={})=>{if(!t.backend.bootDevice)throw new e(`UNSUPPORTED_OPERATION`,`admin.boot is not supported by this backend`);let r=O(n.target),i=await t.backend.bootDevice(y(t,n),r),a=_(i);return{kind:`deviceBooted`,...r?{target:r}:{},...a?{backendResult:a}:{},...c(`Booted device`)}},ve=async(t,n={})=>{if(!t.backend.shutdownDevice)throw new e(`UNSUPPORTED_OPERATION`,`admin.shutdown is not supported by this backend`);let r=O(n.target),i=await t.backend.shutdownDevice(y(t,n),r),a=_(i);return{kind:`deviceShutdown`,...r?{target:r}:{},...a?{backendResult:a}:{},...c(`Shutdown device`)}},ye=async(e,t)=>await E(e,t,`install`),be=async(e,t)=>await E(e,t,`reinstall`),xe=async(e,t)=>await E(e,t,`installFromSource`);async function E(t,n,r){let i=r===`reinstall`?`reinstallApp`:`installApp`,a=t.backend[i];if(!a)throw new e(`UNSUPPORTED_OPERATION`,`admin.${r} is not supported by this backend`);let o=`app`in n&&n.app!==void 0?T(n.app,`app`):void 0;if(r!==`installFromSource`&&!o)throw new e(`INVALID_ARGS`,`admin.${r} requires app`);let s=y(t,n),c=await Se(t,s,n.source);try{let e=await a.call(t.backend,s,{...o?{app:o}:{},source:c.source});return Te(r,o,c.source,e)}finally{await c.cleanup?.()}}async function Se(e,t,n){let r=await Ce(e,D(n));try{return{source:D(e.backend.resolveInstallSource?await e.backend.resolveInstallSource(t,r.source):r.source),...r.cleanup?{cleanup:r.cleanup}:{}}}catch(e){if(r.cleanup)try{await r.cleanup()}catch{}throw e}}async function Ce(e,t){if(t.kind===`url`)return{source:t};let n=await v(e,t,{usage:`admin.install`,field:`source`});return{source:{kind:`path`,path:n.path},...n.cleanup?{cleanup:n.cleanup}:{}}}function D(t){if(!t||typeof t!=`object`)throw new e(`INVALID_ARGS`,`install source is required`);if(t.kind===`path`)return{kind:`path`,path:T(t.path,`source.path`)};if(t.kind===`uploadedArtifact`)return{kind:`uploadedArtifact`,id:T(t.id,`source.id`)};if(t.kind===`url`){let e=T(t.url,`source.url`);return we(e),{kind:`url`,url:e}}throw new e(`INVALID_ARGS`,`install source kind must be path, uploadedArtifact, or url`)}function we(t){let n;try{n=new URL(t)}catch{throw new e(`INVALID_ARGS`,`Invalid install source URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new e(`INVALID_ARGS`,`Install source URL must use http or https`)}function O(e){if(!e)return;let t=w(e.id,`target.id`),n=w(e.name,`target.name`),r={...t?{id:t}:{},...n?{name:n}:{},...e.platform?{platform:e.platform}:{},...e.target?{target:e.target}:{},...e.headless===void 0?{}:{headless:e.headless}};return Object.keys(r).length>0?r:void 0}function Te(e,t,n,r){let i=_(r),a=e===`reinstall`?`appReinstalled`:e===`installFromSource`?`appInstalledFromSource`:`appInstalled`,o=k(r,`appName`),s=k(r,`appId`),l=k(r,`bundleId`),u=k(r,`packageName`),d=k(r,`launchTarget`),f=k(r,`installablePath`),p=k(r,`archivePath`);return{kind:a,...t?{app:t}:{},source:n,...s?{appId:s}:{},...o?{appName:o}:{},...l?{bundleId:l}:{},...u?{packageName:u}:{},...d?{launchTarget:d}:{},...f?{installablePath:f}:{},...p?{archivePath:p}:{},...i?{backendResult:i}:{},...c(`${e===`reinstall`?`Reinstalled`:`Installed`}: ${o??d??t??Ee(n)}`)}}function k(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ee(e){return e.kind===`path`?e.path:e.kind===`uploadedArtifact`?e.id:e.url}const De=/^[A-Za-z0-9_.:-]{1,64}$/,Oe=async(t,n)=>{if(!t.backend.openApp)throw new e(`UNSUPPORTED_OPERATION`,`apps.open is not supported by this backend`);let r=Pe(n),i=await t.backend.openApp(j(t,n),r,{launchArgs:n.launchArgs,relaunch:n.relaunch}),a=_(i);return{kind:`appOpened`,target:r,relaunch:n.relaunch===!0,...a?{backendResult:a}:{},...c(`Opened: ${Ie(r)}`)}},ke=async(t,n={})=>{if(!t.backend.closeApp)throw new e(`UNSUPPORTED_OPERATION`,`apps.close is not supported by this backend`);let r=w(n.app,`app`),i=await t.backend.closeApp(j(t,n),r),a=_(i);return{kind:`appClosed`,...r?{app:r}:{},...a?{backendResult:a}:{},...c(r?`Closed: ${r}`:`Closed app`)}},Ae=async(t,n={})=>{if(!t.backend.listApps)throw new e(`UNSUPPORTED_OPERATION`,`apps.list is not supported by this backend`);return{kind:`appsList`,apps:await t.backend.listApps(j(t,n),u(n.filter))}},je=async(t,n)=>{if(!t.backend.getAppState)throw new e(`UNSUPPORTED_OPERATION`,`apps.state is not supported by this backend`);let r=T(n.app,`app`);return{kind:`appState`,app:r,state:await t.backend.getAppState(j(t,n),r)}},Me=async(t,n)=>{if(!t.backend.pushFile)throw new e(`UNSUPPORTED_OPERATION`,`apps.push is not supported by this backend`);let r=T(n.app,`app`),i=await Le(t,n.input);try{let e=await t.backend.pushFile(j(t,n),i.backendInput,r),a=_(e);return{kind:`appPushed`,app:r,inputKind:i.inputKind,...a?{backendResult:a}:{},...c(`Pushed to ${r}`)}}finally{await i.cleanup?.()}},Ne=async(t,n)=>{if(!t.backend.triggerAppEvent)throw new e(`UNSUPPORTED_OPERATION`,`apps.triggerEvent is not supported by this backend`);let r=Re(n.name);ze(n.payload,`apps.triggerEvent payload for "${r}"`);let i=await t.backend.triggerAppEvent(j(t,n),{name:r,...n.payload?{payload:n.payload}:{}}),a=_(i);return{kind:`appEventTriggered`,name:r,...n.payload?{payload:n.payload}:{},...a?{backendResult:a}:{},...c(`Triggered app event: ${r}`)}};function Pe(t){let n=w(t.app,`app`),r=w(t.appId,`appId`),i=w(t.bundleId,`bundleId`),a=w(t.packageName,`packageName`),o=w(t.url,`url`),s=w(t.activity,`activity`),c={...n?{app:n}:{},...r?{appId:r}:{},...i?{bundleId:i}:{},...a?{packageName:a}:{},...o?{url:o}:{},...s?{activity:s}:{}};if(!Fe(c))throw new e(`INVALID_ARGS`,`apps.open requires app, appId, bundleId, packageName, url, or activity`);return c}function Fe(e){return!!(e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity)}function Ie(e){return e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity??`app`}async function Le(t,n){if(!n||typeof n!=`object`)throw new e(`INVALID_ARGS`,`apps.push requires an input`);if(n.kind===`json`)return A(n.payload,`apps.push JSON payload`,8192),{backendInput:{kind:`json`,payload:n.payload},inputKind:`json`};let r=await v(t,n,{usage:`apps.push`,field:`input`});return{backendInput:{kind:`file`,path:r.path},inputKind:`file`,...r.cleanup?{cleanup:r.cleanup}:{}}}function Re(t){let n=T(t,`name`);if(!De.test(n))throw new e(`INVALID_ARGS`,`Invalid apps.triggerEvent name: ${n}`,{hint:`Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash.`});return n}function ze(e,t){e!==void 0&&A(e,t,8192)}function A(t,n,r){if(Be(t,n),Buffer.byteLength(Ve(t,n),`utf8`)>r)throw new e(`INVALID_ARGS`,`${n} exceeds ${r} bytes`)}function Be(t,n){if(!t||typeof t!=`object`||Array.isArray(t))throw new e(`INVALID_ARGS`,`${n} must be a JSON object`)}function Ve(t,n){try{let r=JSON.stringify(t);if(typeof r!=`string`)throw new e(`INVALID_ARGS`,`${n} must be JSON-serializable`);return r}catch{throw new e(`INVALID_ARGS`,`${n} must be JSON-serializable`)}}function j(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}const He={open:Oe,close:ke,list:Ae,state:je,push:Me,triggerEvent:Ne},Ue={devices:ge,boot:_e,shutdown:ve,install:ye,reinstall:be,installFromSource:xe};function We(e){return{...x(He,e),list:(t={})=>He.list(e,{...t,filter:l(t.filter)})}}const Ge=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i,Ke=/\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g;function qe(e){let t=!1,n=e;return n=n.replaceAll(/(authorization|token|secret|password|passwd|api[-_]?key)=([^&\s]+)/gi,(e,n)=>(t=!0,`${String(n)}=[REDACTED]`)),n=n.replaceAll(/("(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)"\s*:\s*")([^"]*)(")/gi,(e,n,r,i)=>(t=!0,`${String(n)}[REDACTED]${String(i)}`)),n=n.replaceAll(/\b(Bearer\s+)([^\s",;]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`)),n=n.replaceAll(/((?:authorization|cookie|token|secret|password|passwd|api[-_]?key)\s*[:=]\s*)([^\s,;&]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`)),n=n.replaceAll(Ke,()=>(t=!0,`[REDACTED]`)),n=Ye(n,()=>{t=!0}),{value:n,redacted:t}}function Je(e){try{let t=new URL(e),n=Xe(t);return(t.username||t.password)&&(t.username=`REDACTED`,t.password=`REDACTED`,n=!0),{value:t.toString(),redacted:n}}catch{return}}function Ye(e,t){return/(https?:\/\/|token|secret|password|authorization|cookie|api[-_]?key)/i.test(e)?e.replaceAll(/https?:\/\/[^\s"'<>)]+/gi,e=>{let n=Je(e);return n?(n.redacted&&t(),n.value):e}):e}function Xe(e){let t=!1;for(let n of Array.from(e.searchParams.keys()))Ge.test(n)&&(e.searchParams.set(n,`[REDACTED]`),t=!0);return t}const M=2048,N=4096,P=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i;function Ze(e){let t=e.redacted===!0;return{kind:`diagnosticsLogs`,entries:e.entries.map(e=>{let n=z(e.message,N),r=L(e.metadata);return t||=n.redacted||r.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.level?{level:e.level}:{},message:n.value??``,...e.source?{source:e.source}:{},...r.value?{metadata:r.value}:{}}}),...e.nextCursor?{nextCursor:e.nextCursor}:{},...e.timeWindow?{timeWindow:e.timeWindow}:{},...e.backend?{backend:e.backend}:{},redacted:t,...e.notes?{notes:e.notes}:{}}}function Qe(e,t){let n=e.redacted===!0;return{kind:`diagnosticsNetwork`,entries:e.entries.map(e=>{let r=e.url?et(e.url):void 0,i=t===`headers`||t===`all`?F(e.requestHeaders):void 0,a=t===`headers`||t===`all`?F(e.responseHeaders):void 0,o=t===`body`||t===`all`?I(e.requestBody):void 0,s=t===`body`||t===`all`?I(e.responseBody):void 0,c=L(e.metadata);return n||=(r?.redacted??!1)||(i?.redacted??!1)||(a?.redacted??!1)||(o?.redacted??!1)||(s?.redacted??!1)||c.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.method?{method:e.method}:{},...r?{url:r.value}:{},...e.status===void 0?{}:{status:e.status},...e.durationMs===void 0?{}:{durationMs:e.durationMs},...i?.value?{requestHeaders:i.value}:{},...a?.value?{responseHeaders:a.value}:{},...o?.value===void 0?{}:{requestBody:o.value},...s?.value===void 0?{}:{responseBody:s.value},...c.value?{metadata:c.value}:{}}}),...e.nextCursor?{nextCursor:e.nextCursor}:{},...e.timeWindow?{timeWindow:e.timeWindow}:{},...e.backend?{backend:e.backend}:{},redacted:n,...e.notes?{notes:e.notes}:{}}}function $e(e){let t=e.redacted===!0;return{kind:`diagnosticsPerf`,metrics:e.metrics.map(e=>{let n=z(e.message,N),r=L(e.metadata);return t||=n.redacted||r.redacted,{name:e.name,...e.value===void 0?{}:{value:e.value},...e.unit?{unit:e.unit}:{},...e.status?{status:e.status}:{},...n.value===void 0?{}:{message:n.value},...r.value?{metadata:r.value}:{}}}),...e.startedAt?{startedAt:e.startedAt}:{},...e.endedAt?{endedAt:e.endedAt}:{},...e.backend?{backend:e.backend}:{},redacted:t,...e.notes?{notes:e.notes}:{}}}function F(e){if(!e)return{redacted:!1};let t=!1,n={};for(let[r,i]of Object.entries(e))if(P.test(r))n[r]=`[REDACTED]`,t=!0;else{let e=z(i,M);n[r]=e.value??``,t||=e.redacted}return{value:n,redacted:t}}function et(e){return Je(e)??z(e,M)}function I(e){return e===void 0?{redacted:!1}:tt(e)??z(e,M)}function tt(e){try{let t=R(JSON.parse(e),qe);return B(JSON.stringify(t.value),M,t.redacted)}catch{return}}function L(e){return R(e,e=>z(e,M))}function R(e,t){if(e===void 0)return{redacted:!1};if(typeof e==`string`)return t(e);if(!e||typeof e!=`object`)return{value:e,redacted:!1};if(Array.isArray(e)){let n=!1;return{value:e.map(e=>{let r=R(e,t);return n||=r.redacted,r.value}),redacted:n}}let n=!1,r={};for(let[i,a]of Object.entries(e)){if(P.test(i)){r[i]=`[REDACTED]`,n=!0;continue}let e=R(a,t);r[i]=e.value,n||=e.redacted}return{value:r,redacted:n}}function z(e,t){if(e===void 0)return{redacted:!1};let n=qe(e);return B(n.value,t,n.redacted)}function B(e,t,n){if(e===void 0)return{redacted:n};let r=e;return r.length>t&&(r=`${r.slice(0,t)}...[truncated]`,n=!0),{value:r,redacted:n}}const nt=async(t,n={})=>{if(!t.backend.readLogs)throw new e(`UNSUPPORTED_OPERATION`,`diagnostics.logs is not supported by this backend`);return Ze(await t.backend.readLogs(await V(t,n),at(n)))},rt=async(t,n={})=>{if(!t.backend.dumpNetwork)throw new e(`UNSUPPORTED_OPERATION`,`diagnostics.network is not supported by this backend`);let r=ot(n);return Qe(await t.backend.dumpNetwork(await V(t,n),r),r.include??`summary`)},it=async(t,n={})=>{if(!t.backend.measurePerf)throw new e(`UNSUPPORTED_OPERATION`,`diagnostics.perf is not supported by this backend`);return $e(await t.backend.measurePerf(await V(t,n),st(n)))};async function V(e,t){let n=y(e,t),r=t.session?await e.sessions.get(t.session):void 0;return{...n,...t.appId??r?.appId?{appId:t.appId??r?.appId}:{},...t.appBundleId??r?.appBundleId?{appBundleId:t.appBundleId??r?.appBundleId}:{}}}function at(e){return{...H(e,100,500,`logs limit`),...e.levels===void 0?{}:{levels:W(e.levels,`levels`)},...e.search===void 0?{}:{search:T(e.search,`search`)},...e.source===void 0?{}:{source:T(e.source,`source`)}}}function ot(e){return{...H(e,25,200,`network limit`),include:ct(e.include)}}function st(e){return{...U(e),...e.sampleMs===void 0?{}:{sampleMs:p(e.sampleMs,`sampleMs`,100,6e4)},...e.metrics===void 0?{}:{metrics:W(e.metrics,`metrics`,20)}}}function H(e,t,n,r){return{...U(e),...e.cursor===void 0?{}:{cursor:T(e.cursor,`cursor`)},limit:e.limit===void 0?t:p(e.limit,r,1,n)}}function U(e){return{...e.since===void 0?{}:{since:T(e.since,`since`)},...e.until===void 0?{}:{until:T(e.until,`until`)}}}function ct(t){if(t===void 0)return`summary`;if(t===`summary`||t===`headers`||t===`body`||t===`all`)return t;throw new e(`INVALID_ARGS`,`network include must be summary, headers, body, or all`)}function W(t,n,r=50){if(!Array.isArray(t))throw new e(`INVALID_ARGS`,`${n} must be an array of strings`);if(t.length>r)throw new e(`INVALID_ARGS`,`${n} must contain at most ${r} entries`);return t.map((e,t)=>T(e,`${n}[${t}]`))}const lt={logs:nt,network:rt,perf:it},G=`contact_sheet_frame_extraction_failed`,K=`contact_sheet_no_frames`;function q(t=process.platform){if(t!==`darwin`)throw new e(`UNSUPPORTED_OPERATION`,`Contact sheets can only be built on macOS hosts, which is where the frame decoder runs`,{reason:`contact_sheet_unsupported_host`,hostPlatform:t,hint:`Run this command on the macOS host that recorded the clip, or read the video artifact itself.`})}async function ut(t){if(q(t.hostPlatform??process.platform),t.timesMs.length===0)throw new e(`COMMAND_FAILED`,`Contact sheet sampling requested no frames`,{reason:K,videoPath:t.videoPath});gt(t.signal);let n=await ht(t);gt(t.signal);let r;try{r=await a(n,[`--input`,t.videoPath,`--output-dir`,t.scratchDir,`--times`,t.timesMs.join(`,`),`--max-width`,String(t.maxWidth)],{timeoutMs:9e4,env:fe(t.host.env),allowFailure:!0,...t.signal===void 0?{}:{signal:t.signal}})}catch(e){X(e,t.videoPath,`Failed to run the frame decoder`)}if(r.exitCode!==0)throw new e(`COMMAND_FAILED`,`Failed to extract frames from the recording: ${mt(r.stderr)||`exit ${r.exitCode}`}`,{reason:G,videoPath:t.videoPath,exitCode:r.exitCode});let i=dt(r.stdout,t.videoPath,t.scratchDir,t.timesMs.length);if(i.frames.length===0)throw new e(`COMMAND_FAILED`,`The recording returned no decodable frames for a contact sheet`,{reason:K,videoPath:t.videoPath,skippedSampleCount:i.skippedSampleCount});return i}function dt(e,t,n,r){let i;try{i=JSON.parse(e)}catch(e){throw Y(t,`invalid manifest: ${String(e)}`)}let a=Z(i).frames;if(!Array.isArray(a))throw Y(t,`manifest has no frames array`);let o=Z(i).skipped;if(a.length>r)throw Y(t,`returned ${a.length} frames for ${r} requested samples`);let s=a.flatMap(e=>{let r=Z(e),i=ft(r.path),a=pt(r.actualTimeMs);if(i===void 0||a===void 0||a<0)throw Y(t,`frame entry is missing a path or presentation time`);let o=C.resolve(n,C.basename(i));return S.existsSync(o)?[{requestedTimeMs:pt(r.requestedTimeMs)??a,actualTimeMs:a,path:o}]:[]});return{frames:s.sort((e,t)=>e.actualTimeMs-t.actualTimeMs),skippedSampleCount:Math.max(Array.isArray(o)?o.length:0,r-s.length)}}function J(t,n,r){return new e(`COMMAND_FAILED`,t,{reason:G,videoPath:n},r)}function Y(e,t){return J(`Frame extraction returned an unreadable manifest: ${t}`,e)}function X(t,i,a){throw n(t)||t instanceof e&&t.code===`COMMAND_FAILED`&&t.details?.reason?t:J(`${a} for ${i}: ${r(t)}`,i,t)}function Z(e){return typeof e==`object`&&e?e:{}}function ft(e){return typeof e==`string`&&e!==``?e:void 0}function pt(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function mt(e){return(e.trim().split(`
|
|
2
|
-
`).pop()??``).trim()}async function ht(e){let{cwd:t}=e.host;try{return await me({host:e.host,sourcePath:de(`recording-frames.swift`,d(),t),extraSourcePaths:[de(`RecordingExportSupport.swift`,d(),t)],cacheName:`recording-frames`,timeoutMs:12e4})}catch(t){X(t,e.videoPath,`Could not build the frame decoder`)}}function gt(e){if(e?.aborted)throw t()}function _t(t,n){if(t===void 0||!Number.isFinite(t)||t<0)throw new e(`COMMAND_FAILED`,`Cannot plan a contact sheet: the video timeline of ${n} could not be read`,{reason:`contact_sheet_duration_unknown`,videoPath:n,hint:`Retry once the recording finished finalizing; a clip whose container is still being written has no readable duration.`});if(t<=250)return{durationMs:t,timesMs:t>0?[0,Math.round(t)]:[0]};let r=Math.min(48,Math.floor(t/250)+1),i=t/(r-1);return{durationMs:t,timesMs:Array.from({length:r},(e,t)=>Math.round(t*i))}}const vt=[360,320,280,240,200,160],yt=[255,255,255,255],bt=[17,24,39,255],Q=ae(2)+8;function xt(t){let{cells:n}=t;if(n.length===0)throw new e(`COMMAND_FAILED`,`Contact sheet has no cells to render`);let r=Ct(n[0].image.height/Math.max(1,n[0].image.width),n.length,t),i=Et(r.width,r.height,bt);return n.forEach((e,t)=>{let n=t%r.columns,a=Math.floor(t/r.columns);St(i,8+n*(r.cellWidth+8),8+a*(Q+r.cellHeight+8),e,r.cellWidth,r.cellHeight)}),{bytes:te(i.data,r.width,r.height,4),width:r.width,height:r.height,cellWidth:r.cellWidth}}function St(e,t,n,r,i,a){ie(e,{x:t+4,y:n+4,text:kt(r.timeMs),color:yt,scale:2}),Dt(e,ne(Ot(r.image),i,a),t,n+Q)}function Ct(t,n,r){let i=wt(t,n,r.maxPixels);if(i)return i;let a=Tt(t,n,160);throw new e(`COMMAND_FAILED`,`Contact sheet would be ${a.width*a.height} pixels, above the configured maxImagePixels limit of ${r.maxPixels}`,{reason:`contact_sheet_pixel_budget_exceeded`,cellCount:r.cells.length,maxPixels:r.maxPixels,hint:`Shorten the recording or raise the command policy maxImagePixels limit.`})}function wt(e,t,n){for(let r of vt){let i=Tt(e,t,r);if(i.width*i.height<=n)return i}}function Tt(e,t,n){let r=Math.min(4,t),i=Math.ceil(t/r),a=Math.max(1,Math.round(n*e));return{columns:r,cellWidth:n,cellHeight:a,width:16+r*n+(r-1)*8,height:16+i*(Q+a)+(i-1)*8}}function Et(e,t,n){let r=new m.PNG({width:e,height:t});for(let i=0;i<t;i+=1)for(let t=0;t<e;t+=1)h(r,t,i,n);return r}function Dt(e,t,n,r){for(let i=0;i<t.height;i+=1)for(let a=0;a<t.width;a+=1){let o=(i*t.width+a)*4;h(e,n+a,r+i,[t.data[o],t.data[o+1],t.data[o+2],t.data[o+3]])}}function Ot(e){let t=new m.PNG({width:e.width,height:e.height});return Buffer.from(e.data.buffer,e.data.byteOffset,e.data.byteLength).copy(t.data),t}function kt(e){let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60,a=Math.floor(e%1e3);return`${[n,r,i].map(e=>String(e).padStart(2,`0`)).join(`:`)}.${String(a).padStart(3,`0`)}`}function At(e,t){if(e.width!==t.width||e.height!==t.height)return{status:`dimension_mismatch`};let n=e.width*e.height;if(n===0)return{status:`compared`,changedPixelRatio:0};if(e.data.length!==t.data.length)return{status:`dimension_mismatch`};let r=0;for(let n=0;n+3<e.data.length;n+=4)(e.data[n]!==t.data[n]||e.data[n+1]!==t.data[n+1]||e.data[n+2]!==t.data[n+2])&&(r+=1);return{status:`compared`,changedPixelRatio:r/n}}function jt(e,t=.02,n=24){let r=[],i;for(let n of e){let e=i?Nt(i,n.image):1;e<t||(r.push({timeMs:n.timeMs,changedPixelRatio:e,image:n.image}),i=n.image)}Mt(r,e);let a=r.length>n?Pt(r,n):r;return{cells:a,keptCellCount:r.length,thinned:a.length<r.length}}function Mt(e,t){let n=t.at(-1);if(!n)return;let r=e.at(-1);!r||r.timeMs===n.timeMs||e.push({timeMs:n.timeMs,changedPixelRatio:Nt(r.image,n.image),image:n.image})}function Nt(e,t){let n=At(e,t);return n.status===`compared`?n.changedPixelRatio:1}function Pt(e,t){if(t<=1)return[e.at(-1)];let n=(e.length-1)/(t-1);return Array.from({length:t},(t,r)=>e[Math.round(r*n)])}async function Ft(t){q(t.hostPlatform??process.platform);let n=C.resolve(t.videoPath),r=C.resolve(t.outputPath??g(n));Rt(n,r);let i=await pe(n);if(i!==`mp4`)throw new e(`INVALID_ARGS`,i===`webm`?`Contact sheets need an MP4 recording; ${n} is WebM, whose frames this decoder does not read`:`Contact sheets need an MP4 recording; ${n} is not a readable MP4`,{reason:`contact_sheet_container_unsupported`,videoPath:n,container:i??`unknown`,hint:`Re-record on a backend that exports MP4, or pass the MP4 artifact the recording produced.`});let a=_t(oe(n),n),o=S.mkdtempSync(C.join(he.tmpdir(),`agent-device-contact-sheet-`));try{let e=await ut({host:t.host,videoPath:n,scratchDir:o,timesMs:a.timesMs,maxWidth:360,hostPlatform:t.hostPlatform??process.platform,...t.signal===void 0?{}:{signal:t.signal}}),i=await It(e.frames,t.maxPixels);Lt(t.signal);let s=jt(i,t.changedPixelThreshold??.02),c=xt({cells:s.cells,maxPixels:t.maxPixels});return Ht(r,c.bytes),{path:r,videoPath:n,durationMs:a.durationMs,width:c.width,height:c.height,sampledFrameCount:a.timesMs.length,decodedFrameCount:e.frames.length,skippedSampleCount:e.skippedSampleCount,changedPixelThreshold:t.changedPixelThreshold??.02,cells:s.cells.map(Bt),...Vt(s,e)}}finally{S.rmSync(o,{recursive:!0,force:!0})}}async function It(t,n){let r=[];for(let i of t){let t=await re(i.path);if(t.width>360)throw new e(`COMMAND_FAILED`,`Frame extraction returned a ${t.width}px-wide frame when the sheet asked for 360px cells`,{reason:G,framePath:i.path,frameWidth:t.width,frameWidthLimit:360});if(t.width*t.height>n)throw new e(`COMMAND_FAILED`,`Frame extraction returned a ${t.width}x${t.height} frame, above the ${n}-pixel budget for the whole sheet`,{reason:G,framePath:i.path,framePixels:t.width*t.height,maxPixels:n});let a=await ee(S.readFileSync(i.path),`recording frame`);r.push({timeMs:i.actualTimeMs,image:a})}return r}function Lt(e){if(e?.aborted)throw t()}function Rt(t,n){if(zt(t,n)??n===t)throw new e(`INVALID_ARGS`,`A contact sheet cannot be written over the recording it describes: ${n}`,{reason:`contact_sheet_output_collides_with_input`,videoPath:t,outputPath:n,hint:`Choose a different --out path, or omit it to write beside the recording.`})}function zt(e,t){let n=$(e),r=$(t);if(n!==void 0&&r!==void 0)return n.dev===r.dev&&n.ino===r.ino}function $(e){try{return S.statSync(e)}catch{return}}function Bt(e){return{timeMs:e.timeMs,changedPixelRatio:e.changedPixelRatio}}function Vt(e,t){let n=[];return t.skippedSampleCount>0&&n.push(`${t.skippedSampleCount} sample times returned no frame, so the sheet covers less of the recording than it asked for`),e.thinned&&n.push(`${e.keptCellCount} changes were found and 24 cells are printed, so the sheet thins evenly across the recording instead of showing every change`),n.length===0?{}:{warning:n.join(`; `)}}function Ht(t,n){try{S.mkdirSync(C.dirname(t),{recursive:!0}),o({destination:t,contents:n})}catch(n){throw new e(`COMMAND_FAILED`,`Failed to write the contact sheet to ${t}: ${n instanceof Error?n.message:String(n)}`,{reason:`contact_sheet_output_write_failed`,outputPath:t})}}const Ut=async(t,n)=>{if(!n.video)throw new e(`INVALID_ARGS`,`record contact-sheet requires a recording to read`);Gt(n.changedPixelThreshold);let r=await v(t,n.video,{usage:`record contact-sheet`,field:`video`}),i;try{let e=Wt(n,n.video,r.path);i=await b(t,e,{field:`path`,ext:`.png`,artifactType:`screen-recording-contact-sheet`});let a=await Ft({host:n.host,videoPath:r.path,outputPath:i.path,maxPixels:t.policy.maxImagePixels,...n.changedPixelThreshold===void 0?{}:{changedPixelThreshold:n.changedPixelThreshold},signal:n.signal??t.signal}),o=await i.publish();return{...a,path:Kt(a.path,o),...o?{artifact:o}:{}}}catch(e){throw await i?.cleanup?.(),e}finally{await r.cleanup?.()}};function Wt(t,n,r){if(t.out)return t.out;if(n.kind===`path`)return{kind:`path`,path:C.resolve(g(n.path||r))};throw new e(`INVALID_ARGS`,`record contact-sheet needs an output path when the recording is an uploaded artifact`,{hint:"Pass --out <sheet.png> (CLI) or `out` (Node) to name where the sheet is written."})}function Gt(t){if(t!==void 0&&(!Number.isFinite(t)||t<0||t>1))throw new e(`INVALID_ARGS`,`record contact-sheet needs a changedPixelThreshold between 0 and 1, got ${t}`,{reason:`contact_sheet_threshold_invalid`,changedPixelThreshold:t,hint:`Omit it to use the calibrated default, or pass a share of the frame between 0 and 1.`})}function Kt(e,t){return t?t.kind===`localPath`?t.path:t.clientPath??e:e}const qt=async(t,n)=>{let r=Qt(n.action,`record`),i=r===`start`?t.backend.startRecording:t.backend.stopRecording;if(!i)throw new e(`UNSUPPORTED_OPERATION`,`record ${r} is not supported by this backend`);let a=n.out?await b(t,n.out,{field:`path`,ext:`.mp4`,artifactType:`screen-recording`}):void 0;try{let e=Yt(n,a?.path);return $t(r,await i.call(t.backend,y(t,n),e),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}},Jt=async(t,n)=>{let r=Qt(n.action,`trace`),i=r===`start`?t.backend.startTrace:t.backend.stopTrace;if(!i)throw new e(`UNSUPPORTED_OPERATION`,`trace ${r} is not supported by this backend`);let a=n.out?await b(t,n.out,{field:`outPath`,ext:`.trace`,artifactType:`trace-log`}):void 0;try{let e=a?.path?{outPath:a.path}:{};return en(r,await i.call(t.backend,y(t,n),e),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}};function Yt(e,t){let n={};t&&(n.outPath=t);let r=Xt(e.fps);r!==void 0&&(n.fps=r);let i=Zt(e.quality);return i!==void 0&&(n.quality=i),e.hideTouches!==void 0&&(n.showTouches=e.hideTouches!==!0),n}function Xt(e){return e===void 0?void 0:p(e,`fps`,1,60)}function Zt(t){if(t===void 0)return;let n=s(t);if(n===void 0)throw new e(`INVALID_ARGS`,`quality must be one of: medium, high (legacy numeric values 5-10 are accepted)`);return n}function Qt(t,n){if(t===`start`||t===`stop`)return t;throw new e(`INVALID_ARGS`,`${n} action must be start or stop`)}function $t(e,t,n){return{...typeof t.path==`string`?{path:t.path}:{},...typeof t.telemetryPath==`string`?{telemetryPath:t.telemetryPath}:{},...typeof t.warning==`string`?{warning:t.warning}:{},...tn(e,t,n,{startKind:`recordingStarted`,stopKind:`recordingStopped`,startMessage:`Recording started`,stopMessage:`Recording stopped`})}}function en(e,t,n){return{...typeof t.outPath==`string`?{outPath:t.outPath}:{},...tn(e,t,n,{startKind:`traceStarted`,stopKind:`traceStopped`,startMessage:`Trace started`,stopMessage:`Trace stopped`})}}function tn(e,t,n,r){return{kind:e===`start`?r.startKind:r.stopKind,action:e,...n?{artifact:n}:{},backendResult:t,...c(e===`start`?r.startMessage:r.stopMessage)}}const nn={record:qt,trace:Jt,contactSheet:Ut},rn=async(t,n={})=>{if(!t.backend.pressBack)throw new e(`UNSUPPORTED_OPERATION`,`system.back is not supported by this backend`);let r=n.mode??`in-app`;if(r!==`in-app`&&r!==`system`)throw new e(`INVALID_ARGS`,`system.back mode must be in-app or system`);let i=await t.backend.pressBack(y(t,n),{mode:r}),a=_(i);return{kind:`systemBack`,mode:r,...a?{backendResult:a}:{},...c(`Back`)}},an=async(t,n={})=>{if(!t.backend.pressHome)throw new e(`UNSUPPORTED_OPERATION`,`system.home is not supported by this backend`);let r=await t.backend.pressHome(y(t,n)),i=_(r);return{kind:`systemHome`,...i?{backendResult:i}:{},...c(`Home`)}},on=async(t,n)=>{if(!t.backend.pressTvRemote)throw new e(`UNSUPPORTED_OPERATION`,`system.tvRemote is not supported by this backend`);let r=i(n.button),a=n.durationMs===void 0?void 0:p(n.durationMs,`durationMs`,0,1e4),o=await t.backend.pressTvRemote(y(t,n),{button:r,...a===void 0?{}:{durationMs:a}}),s=_(o);return{kind:`tvRemotePressed`,button:r,...a===void 0?{}:{durationMs:a},...s?{backendResult:s}:{},...c(`Pressed TV remote ${r}`)}},sn=async(t,n)=>{if(!t.backend.setOrientation)throw new e(`UNSUPPORTED_OPERATION`,`system.orientation is not supported by this backend`);let r=pn(n.orientation),i=await t.backend.setOrientation(y(t,n),r),a=_(i);return{kind:`systemOrientationSet`,orientation:r,...a?{backendResult:a}:{},...c(`Rotated to ${r}`)}},cn=async(t,n={})=>{if(!t.backend.setKeyboard)throw new e(`UNSUPPORTED_OPERATION`,`system.keyboard is not supported by this backend`);let r=n.action??`status`;if(!f(r))throw new e(`INVALID_ARGS`,`system.keyboard action must be status, get, dismiss, enter, or return`);let i=await t.backend.setKeyboard(y(t,n),{action:r}),a=_(i),o=Sn(i)?i:{};return r===`enter`||r===`return`?hn(o,a):r===`dismiss`?gn(r,o,a):vn(r,o,a)},ln=async(t,n)=>{if(n.action===`read`){if(!t.backend.getClipboard)throw new e(`UNSUPPORTED_OPERATION`,`system.clipboard read is not supported by this backend`);let r=await t.backend.getClipboard(y(t,n));return{kind:`clipboardText`,action:`read`,text:typeof r==`string`?r:r.text}}if(n.action!==`write`)throw new e(`INVALID_ARGS`,`system.clipboard action must be read or write`);if(!t.backend.setClipboard)throw new e(`UNSUPPORTED_OPERATION`,`system.clipboard write is not supported by this backend`);if(typeof n.text!=`string`)throw new e(`INVALID_ARGS`,`system.clipboard write requires text`);let r=await t.backend.setClipboard(y(t,n),n.text),i=_(r);return{kind:`clipboardUpdated`,action:`write`,textLength:Array.from(n.text).length,...i?{backendResult:i}:{},...c(`Clipboard updated`)}},un=async(t,n={})=>{if(!t.backend.openSettings)throw new e(`UNSUPPORTED_OPERATION`,`system.settings is not supported by this backend`);let r=w(n.target,`target`),i=await t.backend.openSettings(y(t,n),r),a=_(i);return{kind:`settingsOpened`,...r?{target:r}:{},...a?{backendResult:a}:{},...c(r?`Opened settings: ${r}`:`Opened settings`)}},dn=async(t,n={})=>{if(!t.backend.handleAlert)throw new e(`UNSUPPORTED_OPERATION`,`system.alert is not supported by this backend`);let r=n.action??`get`;if(r!==`get`&&r!==`accept`&&r!==`dismiss`&&r!==`wait`)throw new e(`INVALID_ARGS`,`system.alert action must be get, accept, dismiss, or wait`);let i=n.timeoutMs===void 0?void 0:p(n.timeoutMs,`timeoutMs`,0,12e4);return mn(r,await t.backend.handleAlert(y(t,n),r,{timeoutMs:i}))},fn=async(t,n={})=>{if(!t.backend.openAppSwitcher)throw new e(`UNSUPPORTED_OPERATION`,`system.appSwitcher is not supported by this backend`);let r=await t.backend.openAppSwitcher(y(t,n)),i=_(r);return{kind:`appSwitcherOpened`,...i?{backendResult:i}:{},...c(`Opened app switcher`)}};function pn(t){switch(t){case`portrait`:case`portrait-upside-down`:case`landscape-left`:case`landscape-right`:return t;default:throw new e(`INVALID_ARGS`,`system.orientation must be portrait, portrait-upside-down, landscape-left, or landscape-right`)}}function mn(e,t){return e===`get`?yn(t):e===`wait`?bn(t):xn(e,t)}function hn(e,t){return{kind:`keyboardEnterPressed`,action:`enter`,state:e,...t?{backendResult:t}:{},...c(`Keyboard enter pressed`)}}function gn(e,t,n){return{kind:`keyboardDismissed`,action:e,state:t,...n?{backendResult:n}:{},...c(_n(t))}}function _n(e){return e.dismissed===!1?`Keyboard already hidden`:e.mechanism===`dismissKey`?`Keyboard dismissed via its dismiss key`:`Keyboard dismissed`}function vn(e,t,n){return{kind:`keyboardState`,action:e,state:t,...n?{backendResult:n}:{}}}function yn(t){if(t.kind!==`alertStatus`)throw new e(`COMMAND_FAILED`,`system.alert get returned an invalid backend result`);return{kind:`alertStatus`,action:`get`,alert:t.alert}}function bn(t){if(t.kind!==`alertWait`)throw new e(`COMMAND_FAILED`,`system.alert wait returned an invalid backend result`);return{kind:`alertWait`,action:`wait`,alert:t.alert,...t.waitedMs===void 0?{}:{waitedMs:t.waitedMs},...t.timedOut===void 0?{}:{timedOut:t.timedOut},...c(t.alert?`Alert visible`:`Alert wait timed out`)}}function xn(t,n){if(n.kind!==`alertHandled`)throw new e(`COMMAND_FAILED`,`system.alert ${t} returned an invalid backend result`);return{kind:`alertHandled`,action:t,handled:n.handled,...n.alert?{alert:n.alert}:{},...n.button?{button:n.button}:{},...c(n.handled?`Alert ${t}ed`:`No alert handled`)}}function Sn(e){return!!(e&&typeof e==`object`)}const Cn={back:rn,home:an,orientation:sn,keyboard:cn,clipboard:ln,settings:un,alert:dn,appSwitcher:fn,tvRemote:on};function wn(e){return{capture:ce(e),selectors:le(e),interactions:se(e),system:x(Cn,e),apps:We(e),admin:x(Ue,e),recording:x(nn,e),observability:x(lt,e)}}function Tn(e){let t=ue(e);return{...t,...wn(t)}}export{Tn as createAgentDevice};
|
|
1
|
+
import{H as e,J as t,Q as n,R as r}from"./sdk-contracts.js";import{a as i}from"./tv-remote.js";import{Q as a,dt as o}from"./sdk-io.js";import{i as s}from"./recording-export-quality.js";import"./command-metadata.js";import{r as c}from"./success-text.js";import{n as l,t as u}from"./app-inventory.js";import"./file.js";import"./command.js";import{r as d}from"./version.js";import{t as f}from"./keyboard-actions.js";import{m as p}from"./selector-pipeline-policy.js";import{i as ee}from"./png-worker-client.js";import{o as m}from"./png-worker-contract.js";import{t as te}from"./png-encode.js";import{n as ne}from"./png-resize.js";import{t as re}from"./png-size.js";import{i as h,n as ie,r as ae}from"./screenshot-overlay-draw.js";import{r as g}from"./artifact-paths.js";import{t as oe}from"./mp4-duration.js";import{a as se,c as _,i as v,l as y,n as ce,o as le,r as b,s as x,t as ue}from"./runtime-factory.js";import{c as de,o as fe,r as pe,s as me}from"./video.js";import S from"node:fs";import he from"node:os";import C from"node:path";function w(e,t){if(e!==void 0)return T(e,t)}function T(e,t){let n=e?.trim();if(!n)throw new r(`INVALID_ARGS`,`${t} must be a non-empty string`);return n}const ge=async(e,t={})=>{if(!e.backend.listDevices)throw new r(`UNSUPPORTED_OPERATION`,`admin.devices is not supported by this backend`);return{kind:`adminDevices`,devices:await e.backend.listDevices(y(e,t),t.filter)}},_e=async(e,t={})=>{if(!e.backend.bootDevice)throw new r(`UNSUPPORTED_OPERATION`,`admin.boot is not supported by this backend`);let n=O(t.target),i=await e.backend.bootDevice(y(e,t),n),a=_(i);return{kind:`deviceBooted`,...n?{target:n}:{},...a?{backendResult:a}:{},...c(`Booted device`)}},ve=async(e,t={})=>{if(!e.backend.shutdownDevice)throw new r(`UNSUPPORTED_OPERATION`,`admin.shutdown is not supported by this backend`);let n=O(t.target),i=await e.backend.shutdownDevice(y(e,t),n),a=_(i);return{kind:`deviceShutdown`,...n?{target:n}:{},...a?{backendResult:a}:{},...c(`Shutdown device`)}},ye=async(e,t)=>await E(e,t,`install`),be=async(e,t)=>await E(e,t,`reinstall`),xe=async(e,t)=>await E(e,t,`installFromSource`);async function E(e,t,n){let i=n===`reinstall`?`reinstallApp`:`installApp`,a=e.backend[i];if(!a)throw new r(`UNSUPPORTED_OPERATION`,`admin.${n} is not supported by this backend`);let o=`app`in t&&t.app!==void 0?T(t.app,`app`):void 0;if(n!==`installFromSource`&&!o)throw new r(`INVALID_ARGS`,`admin.${n} requires app`);let s=y(e,t),c=await Se(e,s,t.source);try{let t=await a.call(e.backend,s,{...o?{app:o}:{},source:c.source});return Te(n,o,c.source,t)}finally{await c.cleanup?.()}}async function Se(e,t,n){let r=await Ce(e,D(n));try{return{source:D(e.backend.resolveInstallSource?await e.backend.resolveInstallSource(t,r.source):r.source),...r.cleanup?{cleanup:r.cleanup}:{}}}catch(e){if(r.cleanup)try{await r.cleanup()}catch{}throw e}}async function Ce(e,t){if(t.kind===`url`)return{source:t};let n=await v(e,t,{usage:`admin.install`,field:`source`});return{source:{kind:`path`,path:n.path},...n.cleanup?{cleanup:n.cleanup}:{}}}function D(e){if(!e||typeof e!=`object`)throw new r(`INVALID_ARGS`,`install source is required`);if(e.kind===`path`)return{kind:`path`,path:T(e.path,`source.path`)};if(e.kind===`uploadedArtifact`)return{kind:`uploadedArtifact`,id:T(e.id,`source.id`)};if(e.kind===`url`){let t=T(e.url,`source.url`);return we(t),{kind:`url`,url:t}}throw new r(`INVALID_ARGS`,`install source kind must be path, uploadedArtifact, or url`)}function we(e){let t;try{t=new URL(e)}catch{throw new r(`INVALID_ARGS`,`Invalid install source URL: ${e}`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new r(`INVALID_ARGS`,`Install source URL must use http or https`)}function O(e){if(!e)return;let t=w(e.id,`target.id`),n=w(e.name,`target.name`),r={...t?{id:t}:{},...n?{name:n}:{},...e.platform?{platform:e.platform}:{},...e.target?{target:e.target}:{},...e.headless===void 0?{}:{headless:e.headless}};return Object.keys(r).length>0?r:void 0}function Te(e,t,n,r){let i=_(r),a=e===`reinstall`?`appReinstalled`:e===`installFromSource`?`appInstalledFromSource`:`appInstalled`,o=k(r,`appName`),s=k(r,`appId`),l=k(r,`bundleId`),u=k(r,`packageName`),d=k(r,`launchTarget`),f=k(r,`installablePath`),p=k(r,`archivePath`);return{kind:a,...t?{app:t}:{},source:n,...s?{appId:s}:{},...o?{appName:o}:{},...l?{bundleId:l}:{},...u?{packageName:u}:{},...d?{launchTarget:d}:{},...f?{installablePath:f}:{},...p?{archivePath:p}:{},...i?{backendResult:i}:{},...c(`${e===`reinstall`?`Reinstalled`:`Installed`}: ${o??d??t??Ee(n)}`)}}function k(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ee(e){return e.kind===`path`?e.path:e.kind===`uploadedArtifact`?e.id:e.url}const De=/^[A-Za-z0-9_.:-]{1,64}$/,Oe=async(e,t)=>{if(!e.backend.openApp)throw new r(`UNSUPPORTED_OPERATION`,`apps.open is not supported by this backend`);let n=Pe(t),i=await e.backend.openApp(j(e,t),n,{launchArgs:t.launchArgs,relaunch:t.relaunch}),a=_(i);return{kind:`appOpened`,target:n,relaunch:t.relaunch===!0,...a?{backendResult:a}:{},...c(`Opened: ${Ie(n)}`)}},ke=async(e,t={})=>{if(!e.backend.closeApp)throw new r(`UNSUPPORTED_OPERATION`,`apps.close is not supported by this backend`);let n=w(t.app,`app`),i=await e.backend.closeApp(j(e,t),n),a=_(i);return{kind:`appClosed`,...n?{app:n}:{},...a?{backendResult:a}:{},...c(n?`Closed: ${n}`:`Closed app`)}},Ae=async(e,t={})=>{if(!e.backend.listApps)throw new r(`UNSUPPORTED_OPERATION`,`apps.list is not supported by this backend`);return{kind:`appsList`,apps:await e.backend.listApps(j(e,t),u(t.filter))}},je=async(e,t)=>{if(!e.backend.getAppState)throw new r(`UNSUPPORTED_OPERATION`,`apps.state is not supported by this backend`);let n=T(t.app,`app`);return{kind:`appState`,app:n,state:await e.backend.getAppState(j(e,t),n)}},Me=async(e,t)=>{if(!e.backend.pushFile)throw new r(`UNSUPPORTED_OPERATION`,`apps.push is not supported by this backend`);let n=T(t.app,`app`),i=await Le(e,t.input);try{let r=await e.backend.pushFile(j(e,t),i.backendInput,n),a=_(r);return{kind:`appPushed`,app:n,inputKind:i.inputKind,...a?{backendResult:a}:{},...c(`Pushed to ${n}`)}}finally{await i.cleanup?.()}},Ne=async(e,t)=>{if(!e.backend.triggerAppEvent)throw new r(`UNSUPPORTED_OPERATION`,`apps.triggerEvent is not supported by this backend`);let n=Re(t.name);ze(t.payload,`apps.triggerEvent payload for "${n}"`);let i=await e.backend.triggerAppEvent(j(e,t),{name:n,...t.payload?{payload:t.payload}:{}}),a=_(i);return{kind:`appEventTriggered`,name:n,...t.payload?{payload:t.payload}:{},...a?{backendResult:a}:{},...c(`Triggered app event: ${n}`)}};function Pe(e){let t=w(e.app,`app`),n=w(e.appId,`appId`),i=w(e.bundleId,`bundleId`),a=w(e.packageName,`packageName`),o=w(e.url,`url`),s=w(e.activity,`activity`),c={...t?{app:t}:{},...n?{appId:n}:{},...i?{bundleId:i}:{},...a?{packageName:a}:{},...o?{url:o}:{},...s?{activity:s}:{}};if(!Fe(c))throw new r(`INVALID_ARGS`,`apps.open requires app, appId, bundleId, packageName, url, or activity`);return c}function Fe(e){return!!(e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity)}function Ie(e){return e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity??`app`}async function Le(e,t){if(!t||typeof t!=`object`)throw new r(`INVALID_ARGS`,`apps.push requires an input`);if(t.kind===`json`)return A(t.payload,`apps.push JSON payload`,8192),{backendInput:{kind:`json`,payload:t.payload},inputKind:`json`};let n=await v(e,t,{usage:`apps.push`,field:`input`});return{backendInput:{kind:`file`,path:n.path},inputKind:`file`,...n.cleanup?{cleanup:n.cleanup}:{}}}function Re(e){let t=T(e,`name`);if(!De.test(t))throw new r(`INVALID_ARGS`,`Invalid apps.triggerEvent name: ${t}`,{hint:`Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash.`});return t}function ze(e,t){e!==void 0&&A(e,t,8192)}function A(e,t,n){if(Be(e,t),Buffer.byteLength(Ve(e,t),`utf8`)>n)throw new r(`INVALID_ARGS`,`${t} exceeds ${n} bytes`)}function Be(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new r(`INVALID_ARGS`,`${t} must be a JSON object`)}function Ve(e,t){try{let n=JSON.stringify(e);if(typeof n!=`string`)throw new r(`INVALID_ARGS`,`${t} must be JSON-serializable`);return n}catch{throw new r(`INVALID_ARGS`,`${t} must be JSON-serializable`)}}function j(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}const He={open:Oe,close:ke,list:Ae,state:je,push:Me,triggerEvent:Ne},Ue={devices:ge,boot:_e,shutdown:ve,install:ye,reinstall:be,installFromSource:xe};function We(e){return{...x(He,e),list:(t={})=>He.list(e,{...t,filter:l(t.filter)})}}const Ge=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i,Ke=/\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g;function qe(e){let t=!1,n=e;return n=n.replaceAll(/(authorization|token|secret|password|passwd|api[-_]?key)=([^&\s]+)/gi,(e,n)=>(t=!0,`${String(n)}=[REDACTED]`)),n=n.replaceAll(/("(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)"\s*:\s*")([^"]*)(")/gi,(e,n,r,i)=>(t=!0,`${String(n)}[REDACTED]${String(i)}`)),n=n.replaceAll(/\b(Bearer\s+)([^\s",;]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`)),n=n.replaceAll(/((?:authorization|cookie|token|secret|password|passwd|api[-_]?key)\s*[:=]\s*)([^\s,;&]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`)),n=n.replaceAll(Ke,()=>(t=!0,`[REDACTED]`)),n=Ye(n,()=>{t=!0}),{value:n,redacted:t}}function Je(e){try{let t=new URL(e),n=Xe(t);return(t.username||t.password)&&(t.username=`REDACTED`,t.password=`REDACTED`,n=!0),{value:t.toString(),redacted:n}}catch{return}}function Ye(e,t){return/(https?:\/\/|token|secret|password|authorization|cookie|api[-_]?key)/i.test(e)?e.replaceAll(/https?:\/\/[^\s"'<>)]+/gi,e=>{let n=Je(e);return n?(n.redacted&&t(),n.value):e}):e}function Xe(e){let t=!1;for(let n of Array.from(e.searchParams.keys()))Ge.test(n)&&(e.searchParams.set(n,`[REDACTED]`),t=!0);return t}const M=2048,N=4096,P=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i;function Ze(e){let t=e.redacted===!0;return{kind:`diagnosticsLogs`,entries:e.entries.map(e=>{let n=z(e.message,N),r=L(e.metadata);return t||=n.redacted||r.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.level?{level:e.level}:{},message:n.value??``,...e.source?{source:e.source}:{},...r.value?{metadata:r.value}:{}}}),...e.nextCursor?{nextCursor:e.nextCursor}:{},...e.timeWindow?{timeWindow:e.timeWindow}:{},...e.backend?{backend:e.backend}:{},redacted:t,...e.notes?{notes:e.notes}:{}}}function Qe(e,t){let n=e.redacted===!0;return{kind:`diagnosticsNetwork`,entries:e.entries.map(e=>{let r=e.url?et(e.url):void 0,i=t===`headers`||t===`all`?F(e.requestHeaders):void 0,a=t===`headers`||t===`all`?F(e.responseHeaders):void 0,o=t===`body`||t===`all`?I(e.requestBody):void 0,s=t===`body`||t===`all`?I(e.responseBody):void 0,c=L(e.metadata);return n||=(r?.redacted??!1)||(i?.redacted??!1)||(a?.redacted??!1)||(o?.redacted??!1)||(s?.redacted??!1)||c.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.method?{method:e.method}:{},...r?{url:r.value}:{},...e.status===void 0?{}:{status:e.status},...e.durationMs===void 0?{}:{durationMs:e.durationMs},...i?.value?{requestHeaders:i.value}:{},...a?.value?{responseHeaders:a.value}:{},...o?.value===void 0?{}:{requestBody:o.value},...s?.value===void 0?{}:{responseBody:s.value},...c.value?{metadata:c.value}:{}}}),...e.nextCursor?{nextCursor:e.nextCursor}:{},...e.timeWindow?{timeWindow:e.timeWindow}:{},...e.backend?{backend:e.backend}:{},redacted:n,...e.notes?{notes:e.notes}:{}}}function $e(e){let t=e.redacted===!0;return{kind:`diagnosticsPerf`,metrics:e.metrics.map(e=>{let n=z(e.message,N),r=L(e.metadata);return t||=n.redacted||r.redacted,{name:e.name,...e.value===void 0?{}:{value:e.value},...e.unit?{unit:e.unit}:{},...e.status?{status:e.status}:{},...n.value===void 0?{}:{message:n.value},...r.value?{metadata:r.value}:{}}}),...e.startedAt?{startedAt:e.startedAt}:{},...e.endedAt?{endedAt:e.endedAt}:{},...e.backend?{backend:e.backend}:{},redacted:t,...e.notes?{notes:e.notes}:{}}}function F(e){if(!e)return{redacted:!1};let t=!1,n={};for(let[r,i]of Object.entries(e))if(P.test(r))n[r]=`[REDACTED]`,t=!0;else{let e=z(i,M);n[r]=e.value??``,t||=e.redacted}return{value:n,redacted:t}}function et(e){return Je(e)??z(e,M)}function I(e){return e===void 0?{redacted:!1}:tt(e)??z(e,M)}function tt(e){try{let t=R(JSON.parse(e),qe);return B(JSON.stringify(t.value),M,t.redacted)}catch{return}}function L(e){return R(e,e=>z(e,M))}function R(e,t){if(e===void 0)return{redacted:!1};if(typeof e==`string`)return t(e);if(!e||typeof e!=`object`)return{value:e,redacted:!1};if(Array.isArray(e)){let n=!1;return{value:e.map(e=>{let r=R(e,t);return n||=r.redacted,r.value}),redacted:n}}let n=!1,r={};for(let[i,a]of Object.entries(e)){if(P.test(i)){r[i]=`[REDACTED]`,n=!0;continue}let e=R(a,t);r[i]=e.value,n||=e.redacted}return{value:r,redacted:n}}function z(e,t){if(e===void 0)return{redacted:!1};let n=qe(e);return B(n.value,t,n.redacted)}function B(e,t,n){if(e===void 0)return{redacted:n};let r=e;return r.length>t&&(r=`${r.slice(0,t)}...[truncated]`,n=!0),{value:r,redacted:n}}const nt=async(e,t={})=>{if(!e.backend.readLogs)throw new r(`UNSUPPORTED_OPERATION`,`diagnostics.logs is not supported by this backend`);return Ze(await e.backend.readLogs(await V(e,t),at(t)))},rt=async(e,t={})=>{if(!e.backend.dumpNetwork)throw new r(`UNSUPPORTED_OPERATION`,`diagnostics.network is not supported by this backend`);let n=ot(t);return Qe(await e.backend.dumpNetwork(await V(e,t),n),n.include??`summary`)},it=async(e,t={})=>{if(!e.backend.measurePerf)throw new r(`UNSUPPORTED_OPERATION`,`diagnostics.perf is not supported by this backend`);return $e(await e.backend.measurePerf(await V(e,t),st(t)))};async function V(e,t){let n=y(e,t),r=t.session?await e.sessions.get(t.session):void 0;return{...n,...t.appId??r?.appId?{appId:t.appId??r?.appId}:{},...t.appBundleId??r?.appBundleId?{appBundleId:t.appBundleId??r?.appBundleId}:{}}}function at(e){return{...H(e,100,500,`logs limit`),...e.levels===void 0?{}:{levels:W(e.levels,`levels`)},...e.search===void 0?{}:{search:T(e.search,`search`)},...e.source===void 0?{}:{source:T(e.source,`source`)}}}function ot(e){return{...H(e,25,200,`network limit`),include:ct(e.include)}}function st(e){return{...U(e),...e.sampleMs===void 0?{}:{sampleMs:p(e.sampleMs,`sampleMs`,100,6e4)},...e.metrics===void 0?{}:{metrics:W(e.metrics,`metrics`,20)}}}function H(e,t,n,r){return{...U(e),...e.cursor===void 0?{}:{cursor:T(e.cursor,`cursor`)},limit:e.limit===void 0?t:p(e.limit,r,1,n)}}function U(e){return{...e.since===void 0?{}:{since:T(e.since,`since`)},...e.until===void 0?{}:{until:T(e.until,`until`)}}}function ct(e){if(e===void 0)return`summary`;if(e===`summary`||e===`headers`||e===`body`||e===`all`)return e;throw new r(`INVALID_ARGS`,`network include must be summary, headers, body, or all`)}function W(e,t,n=50){if(!Array.isArray(e))throw new r(`INVALID_ARGS`,`${t} must be an array of strings`);if(e.length>n)throw new r(`INVALID_ARGS`,`${t} must contain at most ${n} entries`);return e.map((e,n)=>T(e,`${t}[${n}]`))}const lt={logs:nt,network:rt,perf:it},G=`contact_sheet_frame_extraction_failed`,K=`contact_sheet_no_frames`;function q(e=process.platform){if(e!==`darwin`)throw new r(`UNSUPPORTED_OPERATION`,`Contact sheets can only be built on macOS hosts, which is where the frame decoder runs`,{reason:`contact_sheet_unsupported_host`,hostPlatform:e,hint:`Run this command on the macOS host that recorded the clip, or read the video artifact itself.`})}async function ut(e){if(q(e.hostPlatform??process.platform),e.timesMs.length===0)throw new r(`COMMAND_FAILED`,`Contact sheet sampling requested no frames`,{reason:K,videoPath:e.videoPath});gt(e.signal);let t=await ht(e);gt(e.signal);let n;try{n=await a(t,[`--input`,e.videoPath,`--output-dir`,e.scratchDir,`--times`,e.timesMs.join(`,`),`--max-width`,String(e.maxWidth)],{timeoutMs:9e4,env:fe(e.host.env),allowFailure:!0,...e.signal===void 0?{}:{signal:e.signal}})}catch(t){X(t,e.videoPath,`Failed to run the frame decoder`)}if(n.exitCode!==0)throw new r(`COMMAND_FAILED`,`Failed to extract frames from the recording: ${mt(n.stderr)||`exit ${n.exitCode}`}`,{reason:G,videoPath:e.videoPath,exitCode:n.exitCode});let i=dt(n.stdout,e.videoPath,e.scratchDir,e.timesMs.length);if(i.frames.length===0)throw new r(`COMMAND_FAILED`,`The recording returned no decodable frames for a contact sheet`,{reason:K,videoPath:e.videoPath,skippedSampleCount:i.skippedSampleCount});return i}function dt(e,t,n,r){let i;try{i=JSON.parse(e)}catch(e){throw Y(t,`invalid manifest: ${String(e)}`)}let a=Z(i).frames;if(!Array.isArray(a))throw Y(t,`manifest has no frames array`);let o=Z(i).skipped;if(a.length>r)throw Y(t,`returned ${a.length} frames for ${r} requested samples`);let s=a.flatMap(e=>{let r=Z(e),i=ft(r.path),a=pt(r.actualTimeMs);if(i===void 0||a===void 0||a<0)throw Y(t,`frame entry is missing a path or presentation time`);let o=C.resolve(n,C.basename(i));return S.existsSync(o)?[{requestedTimeMs:pt(r.requestedTimeMs)??a,actualTimeMs:a,path:o}]:[]});return{frames:s.sort((e,t)=>e.actualTimeMs-t.actualTimeMs),skippedSampleCount:Math.max(Array.isArray(o)?o.length:0,r-s.length)}}function J(e,t,n){return new r(`COMMAND_FAILED`,e,{reason:G,videoPath:t},n)}function Y(e,t){return J(`Frame extraction returned an unreadable manifest: ${t}`,e)}function X(e,i,a){throw n(e)||e instanceof r&&e.code===`COMMAND_FAILED`&&e.details?.reason?e:J(`${a} for ${i}: ${t(e)}`,i,e)}function Z(e){return typeof e==`object`&&e?e:{}}function ft(e){return typeof e==`string`&&e!==``?e:void 0}function pt(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function mt(e){return(e.trim().split(`
|
|
2
|
+
`).pop()??``).trim()}async function ht(e){let{cwd:t}=e.host;try{return await me({host:e.host,sourcePath:de(`recording-frames.swift`,d(),t),extraSourcePaths:[de(`RecordingExportSupport.swift`,d(),t)],cacheName:`recording-frames`,timeoutMs:12e4})}catch(t){X(t,e.videoPath,`Could not build the frame decoder`)}}function gt(t){if(t?.aborted)throw e()}function _t(e,t){if(e===void 0||!Number.isFinite(e)||e<0)throw new r(`COMMAND_FAILED`,`Cannot plan a contact sheet: the video timeline of ${t} could not be read`,{reason:`contact_sheet_duration_unknown`,videoPath:t,hint:`Retry once the recording finished finalizing; a clip whose container is still being written has no readable duration.`});if(e<=250)return{durationMs:e,timesMs:e>0?[0,Math.round(e)]:[0]};let n=Math.min(48,Math.floor(e/250)+1),i=e/(n-1);return{durationMs:e,timesMs:Array.from({length:n},(e,t)=>Math.round(t*i))}}const vt=[360,320,280,240,200,160],yt=[255,255,255,255],bt=[17,24,39,255],Q=ae(2)+8;function xt(e){let{cells:t}=e;if(t.length===0)throw new r(`COMMAND_FAILED`,`Contact sheet has no cells to render`);let n=Ct(t[0].image.height/Math.max(1,t[0].image.width),t.length,e),i=Et(n.width,n.height,bt);return t.forEach((e,t)=>{let r=t%n.columns,a=Math.floor(t/n.columns);St(i,8+r*(n.cellWidth+8),8+a*(Q+n.cellHeight+8),e,n.cellWidth,n.cellHeight)}),{bytes:te(i.data,n.width,n.height,4),width:n.width,height:n.height,cellWidth:n.cellWidth}}function St(e,t,n,r,i,a){ie(e,{x:t+4,y:n+4,text:kt(r.timeMs),color:yt,scale:2}),Dt(e,ne(Ot(r.image),i,a),t,n+Q)}function Ct(e,t,n){let i=wt(e,t,n.maxPixels);if(i)return i;let a=Tt(e,t,160);throw new r(`COMMAND_FAILED`,`Contact sheet would be ${a.width*a.height} pixels, above the configured maxImagePixels limit of ${n.maxPixels}`,{reason:`contact_sheet_pixel_budget_exceeded`,cellCount:n.cells.length,maxPixels:n.maxPixels,hint:`Shorten the recording or raise the command policy maxImagePixels limit.`})}function wt(e,t,n){for(let r of vt){let i=Tt(e,t,r);if(i.width*i.height<=n)return i}}function Tt(e,t,n){let r=Math.min(4,t),i=Math.ceil(t/r),a=Math.max(1,Math.round(n*e));return{columns:r,cellWidth:n,cellHeight:a,width:16+r*n+(r-1)*8,height:16+i*(Q+a)+(i-1)*8}}function Et(e,t,n){let r=new m.PNG({width:e,height:t});for(let i=0;i<t;i+=1)for(let t=0;t<e;t+=1)h(r,t,i,n);return r}function Dt(e,t,n,r){for(let i=0;i<t.height;i+=1)for(let a=0;a<t.width;a+=1){let o=(i*t.width+a)*4;h(e,n+a,r+i,[t.data[o],t.data[o+1],t.data[o+2],t.data[o+3]])}}function Ot(e){let t=new m.PNG({width:e.width,height:e.height});return Buffer.from(e.data.buffer,e.data.byteOffset,e.data.byteLength).copy(t.data),t}function kt(e){let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60,a=Math.floor(e%1e3);return`${[n,r,i].map(e=>String(e).padStart(2,`0`)).join(`:`)}.${String(a).padStart(3,`0`)}`}function At(e,t){if(e.width!==t.width||e.height!==t.height)return{status:`dimension_mismatch`};let n=e.width*e.height;if(n===0)return{status:`compared`,changedPixelRatio:0};if(e.data.length!==t.data.length)return{status:`dimension_mismatch`};let r=0;for(let n=0;n+3<e.data.length;n+=4)(e.data[n]!==t.data[n]||e.data[n+1]!==t.data[n+1]||e.data[n+2]!==t.data[n+2])&&(r+=1);return{status:`compared`,changedPixelRatio:r/n}}function jt(e,t=.02,n=24){let r=[],i;for(let n of e){let e=i?Nt(i,n.image):1;e<t||(r.push({timeMs:n.timeMs,changedPixelRatio:e,image:n.image}),i=n.image)}Mt(r,e);let a=r.length>n?Pt(r,n):r;return{cells:a,keptCellCount:r.length,thinned:a.length<r.length}}function Mt(e,t){let n=t.at(-1);if(!n)return;let r=e.at(-1);!r||r.timeMs===n.timeMs||e.push({timeMs:n.timeMs,changedPixelRatio:Nt(r.image,n.image),image:n.image})}function Nt(e,t){let n=At(e,t);return n.status===`compared`?n.changedPixelRatio:1}function Pt(e,t){if(t<=1)return[e.at(-1)];let n=(e.length-1)/(t-1);return Array.from({length:t},(t,r)=>e[Math.round(r*n)])}async function Ft(e){q(e.hostPlatform??process.platform);let t=C.resolve(e.videoPath),n=C.resolve(e.outputPath??g(t));Rt(t,n);let i=await pe(t);if(i!==`mp4`)throw new r(`INVALID_ARGS`,i===`webm`?`Contact sheets need an MP4 recording; ${t} is WebM, whose frames this decoder does not read`:`Contact sheets need an MP4 recording; ${t} is not a readable MP4`,{reason:`contact_sheet_container_unsupported`,videoPath:t,container:i??`unknown`,hint:`Re-record on a backend that exports MP4, or pass the MP4 artifact the recording produced.`});let a=_t(oe(t),t),o=S.mkdtempSync(C.join(he.tmpdir(),`agent-device-contact-sheet-`));try{let r=await ut({host:e.host,videoPath:t,scratchDir:o,timesMs:a.timesMs,maxWidth:360,hostPlatform:e.hostPlatform??process.platform,...e.signal===void 0?{}:{signal:e.signal}}),i=await It(r.frames,e.maxPixels);Lt(e.signal);let s=jt(i,e.changedPixelThreshold??.02),c=xt({cells:s.cells,maxPixels:e.maxPixels});return Ht(n,c.bytes),{path:n,videoPath:t,durationMs:a.durationMs,width:c.width,height:c.height,sampledFrameCount:a.timesMs.length,decodedFrameCount:r.frames.length,skippedSampleCount:r.skippedSampleCount,changedPixelThreshold:e.changedPixelThreshold??.02,cells:s.cells.map(Bt),...Vt(s,r)}}finally{S.rmSync(o,{recursive:!0,force:!0})}}async function It(e,t){let n=[];for(let i of e){let e=await re(i.path);if(e.width>360)throw new r(`COMMAND_FAILED`,`Frame extraction returned a ${e.width}px-wide frame when the sheet asked for 360px cells`,{reason:G,framePath:i.path,frameWidth:e.width,frameWidthLimit:360});if(e.width*e.height>t)throw new r(`COMMAND_FAILED`,`Frame extraction returned a ${e.width}x${e.height} frame, above the ${t}-pixel budget for the whole sheet`,{reason:G,framePath:i.path,framePixels:e.width*e.height,maxPixels:t});let a=await ee(S.readFileSync(i.path),`recording frame`);n.push({timeMs:i.actualTimeMs,image:a})}return n}function Lt(t){if(t?.aborted)throw e()}function Rt(e,t){if(zt(e,t)??t===e)throw new r(`INVALID_ARGS`,`A contact sheet cannot be written over the recording it describes: ${t}`,{reason:`contact_sheet_output_collides_with_input`,videoPath:e,outputPath:t,hint:`Choose a different --out path, or omit it to write beside the recording.`})}function zt(e,t){let n=$(e),r=$(t);if(n!==void 0&&r!==void 0)return n.dev===r.dev&&n.ino===r.ino}function $(e){try{return S.statSync(e)}catch{return}}function Bt(e){return{timeMs:e.timeMs,changedPixelRatio:e.changedPixelRatio}}function Vt(e,t){let n=[];return t.skippedSampleCount>0&&n.push(`${t.skippedSampleCount} sample times returned no frame, so the sheet covers less of the recording than it asked for`),e.thinned&&n.push(`${e.keptCellCount} changes were found and 24 cells are printed, so the sheet thins evenly across the recording instead of showing every change`),n.length===0?{}:{warning:n.join(`; `)}}function Ht(e,t){try{S.mkdirSync(C.dirname(e),{recursive:!0}),o({destination:e,contents:t})}catch(t){throw new r(`COMMAND_FAILED`,`Failed to write the contact sheet to ${e}: ${t instanceof Error?t.message:String(t)}`,{reason:`contact_sheet_output_write_failed`,outputPath:e})}}const Ut=async(e,t)=>{if(!t.video)throw new r(`INVALID_ARGS`,`record contact-sheet requires a recording to read`);Gt(t.changedPixelThreshold);let n=await v(e,t.video,{usage:`record contact-sheet`,field:`video`}),i;try{let r=Wt(t,t.video,n.path);i=await b(e,r,{field:`path`,ext:`.png`,artifactType:`screen-recording-contact-sheet`});let a=await Ft({host:t.host,videoPath:n.path,outputPath:i.path,maxPixels:e.policy.maxImagePixels,...t.changedPixelThreshold===void 0?{}:{changedPixelThreshold:t.changedPixelThreshold},signal:t.signal??e.signal}),o=await i.publish();return{...a,path:Kt(a.path,o),...o?{artifact:o}:{}}}catch(e){throw await i?.cleanup?.(),e}finally{await n.cleanup?.()}};function Wt(e,t,n){if(e.out)return e.out;if(t.kind===`path`)return{kind:`path`,path:C.resolve(g(t.path||n))};throw new r(`INVALID_ARGS`,`record contact-sheet needs an output path when the recording is an uploaded artifact`,{hint:"Pass --out <sheet.png> (CLI) or `out` (Node) to name where the sheet is written."})}function Gt(e){if(e!==void 0&&(!Number.isFinite(e)||e<0||e>1))throw new r(`INVALID_ARGS`,`record contact-sheet needs a changedPixelThreshold between 0 and 1, got ${e}`,{reason:`contact_sheet_threshold_invalid`,changedPixelThreshold:e,hint:`Omit it to use the calibrated default, or pass a share of the frame between 0 and 1.`})}function Kt(e,t){return t?t.kind===`localPath`?t.path:t.clientPath??e:e}const qt=async(e,t)=>{let n=Qt(t.action,`record`),i=n===`start`?e.backend.startRecording:e.backend.stopRecording;if(!i)throw new r(`UNSUPPORTED_OPERATION`,`record ${n} is not supported by this backend`);let a=t.out?await b(e,t.out,{field:`path`,ext:`.mp4`,artifactType:`screen-recording`}):void 0;try{let r=Yt(t,a?.path);return $t(n,await i.call(e.backend,y(e,t),r),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}},Jt=async(e,t)=>{let n=Qt(t.action,`trace`),i=n===`start`?e.backend.startTrace:e.backend.stopTrace;if(!i)throw new r(`UNSUPPORTED_OPERATION`,`trace ${n} is not supported by this backend`);let a=t.out?await b(e,t.out,{field:`outPath`,ext:`.trace`,artifactType:`trace-log`}):void 0;try{let r=a?.path?{outPath:a.path}:{};return en(n,await i.call(e.backend,y(e,t),r),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}};function Yt(e,t){let n={};t&&(n.outPath=t);let r=Xt(e.fps);r!==void 0&&(n.fps=r);let i=Zt(e.quality);return i!==void 0&&(n.quality=i),e.hideTouches!==void 0&&(n.showTouches=e.hideTouches!==!0),n}function Xt(e){return e===void 0?void 0:p(e,`fps`,1,60)}function Zt(e){if(e===void 0)return;let t=s(e);if(t===void 0)throw new r(`INVALID_ARGS`,`quality must be one of: medium, high (legacy numeric values 5-10 are accepted)`);return t}function Qt(e,t){if(e===`start`||e===`stop`)return e;throw new r(`INVALID_ARGS`,`${t} action must be start or stop`)}function $t(e,t,n){return{...typeof t.path==`string`?{path:t.path}:{},...typeof t.telemetryPath==`string`?{telemetryPath:t.telemetryPath}:{},...typeof t.warning==`string`?{warning:t.warning}:{},...tn(e,t,n,{startKind:`recordingStarted`,stopKind:`recordingStopped`,startMessage:`Recording started`,stopMessage:`Recording stopped`})}}function en(e,t,n){return{...typeof t.outPath==`string`?{outPath:t.outPath}:{},...tn(e,t,n,{startKind:`traceStarted`,stopKind:`traceStopped`,startMessage:`Trace started`,stopMessage:`Trace stopped`})}}function tn(e,t,n,r){return{kind:e===`start`?r.startKind:r.stopKind,action:e,...n?{artifact:n}:{},backendResult:t,...c(e===`start`?r.startMessage:r.stopMessage)}}const nn={record:qt,trace:Jt,contactSheet:Ut},rn=async(e,t={})=>{if(!e.backend.pressBack)throw new r(`UNSUPPORTED_OPERATION`,`system.back is not supported by this backend`);let n=t.mode??`in-app`;if(n!==`in-app`&&n!==`system`)throw new r(`INVALID_ARGS`,`system.back mode must be in-app or system`);let i=await e.backend.pressBack(y(e,t),{mode:n}),a=_(i);return{kind:`systemBack`,mode:n,...a?{backendResult:a}:{},...c(`Back`)}},an=async(e,t={})=>{if(!e.backend.pressHome)throw new r(`UNSUPPORTED_OPERATION`,`system.home is not supported by this backend`);let n=await e.backend.pressHome(y(e,t)),i=_(n);return{kind:`systemHome`,...i?{backendResult:i}:{},...c(`Home`)}},on=async(e,t)=>{if(!e.backend.pressTvRemote)throw new r(`UNSUPPORTED_OPERATION`,`system.tvRemote is not supported by this backend`);let n=i(t.button),a=t.durationMs===void 0?void 0:p(t.durationMs,`durationMs`,0,1e4),o=await e.backend.pressTvRemote(y(e,t),{button:n,...a===void 0?{}:{durationMs:a}}),s=_(o);return{kind:`tvRemotePressed`,button:n,...a===void 0?{}:{durationMs:a},...s?{backendResult:s}:{},...c(`Pressed TV remote ${n}`)}},sn=async(e,t)=>{if(!e.backend.setOrientation)throw new r(`UNSUPPORTED_OPERATION`,`system.orientation is not supported by this backend`);let n=pn(t.orientation),i=await e.backend.setOrientation(y(e,t),n),a=_(i);return{kind:`systemOrientationSet`,orientation:n,...a?{backendResult:a}:{},...c(`Rotated to ${n}`)}},cn=async(e,t={})=>{if(!e.backend.setKeyboard)throw new r(`UNSUPPORTED_OPERATION`,`system.keyboard is not supported by this backend`);let n=t.action??`status`;if(!f(n))throw new r(`INVALID_ARGS`,`system.keyboard action must be status, get, dismiss, enter, or return`);let i=await e.backend.setKeyboard(y(e,t),{action:n}),a=_(i),o=Sn(i)?i:{};return n===`enter`||n===`return`?hn(o,a):n===`dismiss`?gn(n,o,a):vn(n,o,a)},ln=async(e,t)=>{if(t.action===`read`){if(!e.backend.getClipboard)throw new r(`UNSUPPORTED_OPERATION`,`system.clipboard read is not supported by this backend`);let n=await e.backend.getClipboard(y(e,t));return{kind:`clipboardText`,action:`read`,text:typeof n==`string`?n:n.text}}if(t.action!==`write`)throw new r(`INVALID_ARGS`,`system.clipboard action must be read or write`);if(!e.backend.setClipboard)throw new r(`UNSUPPORTED_OPERATION`,`system.clipboard write is not supported by this backend`);if(typeof t.text!=`string`)throw new r(`INVALID_ARGS`,`system.clipboard write requires text`);let n=await e.backend.setClipboard(y(e,t),t.text),i=_(n);return{kind:`clipboardUpdated`,action:`write`,textLength:Array.from(t.text).length,...i?{backendResult:i}:{},...c(`Clipboard updated`)}},un=async(e,t={})=>{if(!e.backend.openSettings)throw new r(`UNSUPPORTED_OPERATION`,`system.settings is not supported by this backend`);let n=w(t.target,`target`),i=await e.backend.openSettings(y(e,t),n),a=_(i);return{kind:`settingsOpened`,...n?{target:n}:{},...a?{backendResult:a}:{},...c(n?`Opened settings: ${n}`:`Opened settings`)}},dn=async(e,t={})=>{if(!e.backend.handleAlert)throw new r(`UNSUPPORTED_OPERATION`,`system.alert is not supported by this backend`);let n=t.action??`get`;if(n!==`get`&&n!==`accept`&&n!==`dismiss`&&n!==`wait`)throw new r(`INVALID_ARGS`,`system.alert action must be get, accept, dismiss, or wait`);let i=t.timeoutMs===void 0?void 0:p(t.timeoutMs,`timeoutMs`,0,12e4);return mn(n,await e.backend.handleAlert(y(e,t),n,{timeoutMs:i}))},fn=async(e,t={})=>{if(!e.backend.openAppSwitcher)throw new r(`UNSUPPORTED_OPERATION`,`system.appSwitcher is not supported by this backend`);let n=await e.backend.openAppSwitcher(y(e,t)),i=_(n);return{kind:`appSwitcherOpened`,...i?{backendResult:i}:{},...c(`Opened app switcher`)}};function pn(e){switch(e){case`portrait`:case`portrait-upside-down`:case`landscape-left`:case`landscape-right`:return e;default:throw new r(`INVALID_ARGS`,`system.orientation must be portrait, portrait-upside-down, landscape-left, or landscape-right`)}}function mn(e,t){return e===`get`?yn(t):e===`wait`?bn(t):xn(e,t)}function hn(e,t){return{kind:`keyboardEnterPressed`,action:`enter`,state:e,...t?{backendResult:t}:{},...c(`Keyboard enter pressed`)}}function gn(e,t,n){return{kind:`keyboardDismissed`,action:e,state:t,...n?{backendResult:n}:{},...c(_n(t))}}function _n(e){return e.dismissed===!1?`Keyboard already hidden`:e.mechanism===`dismissKey`?`Keyboard dismissed via its dismiss key`:`Keyboard dismissed`}function vn(e,t,n){return{kind:`keyboardState`,action:e,state:t,...n?{backendResult:n}:{}}}function yn(e){if(e.kind!==`alertStatus`)throw new r(`COMMAND_FAILED`,`system.alert get returned an invalid backend result`);return{kind:`alertStatus`,action:`get`,alert:e.alert}}function bn(e){if(e.kind!==`alertWait`)throw new r(`COMMAND_FAILED`,`system.alert wait returned an invalid backend result`);return{kind:`alertWait`,action:`wait`,alert:e.alert,...e.waitedMs===void 0?{}:{waitedMs:e.waitedMs},...e.timedOut===void 0?{}:{timedOut:e.timedOut},...c(e.alert?`Alert visible`:`Alert wait timed out`)}}function xn(e,t){if(t.kind!==`alertHandled`)throw new r(`COMMAND_FAILED`,`system.alert ${e} returned an invalid backend result`);return{kind:`alertHandled`,action:e,handled:t.handled,...t.alert?{alert:t.alert}:{},...t.button?{button:t.button}:{},...c(t.handled?`Alert ${e}ed`:`No alert handled`)}}function Sn(e){return!!(e&&typeof e==`object`)}const Cn={back:rn,home:an,orientation:sn,keyboard:cn,clipboard:ln,settings:un,alert:dn,appSwitcher:fn,tvRemote:on};function wn(e){return{capture:ce(e),selectors:le(e),interactions:se(e),system:x(Cn,e),apps:We(e),admin:x(Ue,e),recording:x(nn,e),observability:x(lt,e)}}function Tn(e){let t=ue(e);return{...t,...wn(t)}}export{Tn as createAgentDevice};
|
package/dist/src/runtime2.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{tt 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};
|