agent-device 0.21.6 → 0.21.8
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.6.apk → agent-device-android-ime-helper-0.21.8.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.8.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.6.manifest.json → agent-device-android-ime-helper-0.21.8.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.6.apk → agent-device-android-snapshot-helper-0.21.8.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.8.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.6.manifest.json → agent-device-android-snapshot-helper-0.21.8.manifest.json} +6 -6
- package/apple/macos-helper/Package.swift +16 -1
- package/apple/macos-helper/Sources/AgentDeviceMacOSDeviceHub/DeviceHubPose.swift +47 -0
- package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/DeviceHubPose.swift +320 -0
- package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +66 -13
- package/apple/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickDelivery.swift +116 -0
- package/apple/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickSchedule.swift +61 -0
- package/apple/macos-helper/Tests/AgentDeviceMacOSDeviceHubTests/DeviceHubPoseTests.swift +30 -0
- package/apple/macos-helper/Tests/AgentDeviceMacOSInputTests/MouseClickScheduleTests.swift +58 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +4 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +20 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerScrollViewportPolicy.swift +1 -2
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +25 -12
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +56 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +1 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +36 -108
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +241 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +29 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +46 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +85 -26
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +134 -117
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotBackendCapabilities.swift +1 -3
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +25 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +1 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +3 -0
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotCoordinateSpace.swift +197 -0
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +30 -4
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentation.swift +0 -81
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationInvariant.swift +1 -9
- package/dist/src/absence-observation-errors.js +1 -1
- package/dist/src/adapter.js +1 -1
- package/dist/src/adb-executor.js +2 -2
- package/dist/src/adb-failure.js +1 -1
- package/dist/src/adb-transport.js +1 -1
- package/dist/src/adb.js +1 -1
- package/dist/src/agent-browser-lifecycle.js +1 -1
- package/dist/src/agent-browser-process-record.js +1 -1
- package/dist/src/agent-browser-provider.js +1 -1
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/ai-sdk.js +1 -1
- package/dist/src/alert-runtime.js +1 -1
- package/dist/src/android-adb.d.ts +29 -2
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android-input-ownership.js +1 -1
- package/dist/src/android.js +1 -1
- package/dist/src/app-catalog.js +1 -1
- package/dist/src/app-deployment-resolution.js +1 -1
- package/dist/src/app-helpers.js +1 -1
- package/dist/src/app-inventory.js +1 -1
- package/dist/src/app-launch.js +2 -2
- package/dist/src/app-lifecycle.js +2 -2
- package/dist/src/app-lifecycle2.js +2 -2
- package/dist/src/app-log-files.js +1 -1
- package/dist/src/app-log-runtime2.js +3 -3
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/app-state.js +1 -1
- package/dist/src/apple-runner-platform.js +1 -1
- package/dist/src/application-lifecycle-interaction.js +1 -1
- package/dist/src/archive.js +1 -1
- package/dist/src/artifact-download.js +1 -1
- package/dist/src/auth-session.js +1 -1
- package/dist/src/auth.js +1 -1
- package/dist/src/back-mode.js +1 -1
- package/dist/src/backend-snapshot-options.js +1 -1
- package/dist/src/boot-diagnostics.js +1 -1
- package/dist/src/capture-disclosure.js +1 -0
- package/dist/src/capture.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +18 -2
- package/dist/src/cli-output.js +1 -1
- package/dist/src/cli.js +4 -4
- package/dist/src/click-button.js +1 -1
- package/dist/src/client-metro.js +1 -1
- package/dist/src/client-types.d.ts +65 -3
- package/dist/src/clipboard-shell-response.js +1 -0
- package/dist/src/command-schema.js +1 -1
- package/dist/src/command-tools.js +4 -2
- package/dist/src/command.js +1 -1
- package/dist/src/config.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection.js +1 -1
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/contracts.js +1 -1
- package/dist/src/daemon-client-lifecycle.js +1 -1
- package/dist/src/daemon.js +1 -1
- package/dist/src/debug-symbols-facade.js +1 -1
- package/dist/src/device-boot.js +1 -1
- package/dist/src/device-claim-inspection.js +1 -1
- package/dist/src/device-claim-rule.js +2 -1
- package/dist/src/device-input-state.d.ts +5 -5
- package/dist/src/device-inventory-context.js +1 -1
- package/dist/src/device-rotation.js +1 -1
- package/dist/src/device-selection-resolver.js +1 -1
- package/dist/src/device-session.js +1 -1
- package/dist/src/device-shell.js +1 -0
- package/dist/src/device.js +1 -1
- package/dist/src/device2.js +1 -1
- package/dist/src/devicectl.js +1 -0
- package/dist/src/diagnostics.js +1 -1
- package/dist/src/dispatch-resolve.js +1 -1
- package/dist/src/display-inventory.js +1 -0
- package/dist/src/doctor-facade.js +1 -1
- package/dist/src/doctor2.js +1 -1
- package/dist/src/durable-resource.js +1 -1
- package/dist/src/engine-eval-script.js +1 -1
- package/dist/src/error.js +1 -1
- package/dist/src/exec.js +1 -1
- package/dist/src/file.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/format.js +2 -1
- package/dist/src/generic.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/harmonyos.js +1 -1
- package/dist/src/hdc.js +1 -1
- package/dist/src/helper.js +2 -2
- package/dist/src/host.js +1 -0
- package/dist/src/human-control-contract.js +1 -1
- package/dist/src/human-control.js +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions2.js +1 -1
- package/dist/src/install-artifact-facade.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-ref-policy.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -1
- package/dist/src/interactor-operation-binding.js +1 -0
- package/dist/src/interactor-operation-catalog.js +1 -1
- package/dist/src/interactor.js +4 -5
- package/dist/src/interactor2.js +1 -1
- package/dist/src/interactors.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +2 -2
- package/dist/src/internal/png-worker.d.ts +9 -1
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/internal/run-script-http-child.js +1 -1
- package/dist/src/inventory.js +4 -4
- package/dist/src/inventory2.js +1 -1
- package/dist/src/inventory3.js +2 -2
- package/dist/src/inventory5.js +1 -1
- package/dist/src/ios-snapshot-acquisition.js +1 -1
- package/dist/src/ios-snapshot-runtime.js +1 -1
- package/dist/src/ios-target-activation.js +1 -0
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease-scope.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun-download-file.js +1 -0
- package/dist/src/limrun-runtime-dependencies.js +1 -1
- package/dist/src/limrun.d.ts +10 -4
- package/dist/src/linux.js +1 -1
- package/dist/src/local-interactor-operation-set.js +1 -1
- package/dist/src/location-coordinates.js +1 -1
- package/dist/src/macos-facade.js +1 -1
- package/dist/src/managed-device-scope.js +1 -1
- package/dist/src/mechanics.js +17 -16
- package/dist/src/mobile-snapshot-semantics.js +1 -1
- package/dist/src/multitouch-support.js +1 -1
- package/dist/src/observation.js +2 -2
- package/dist/src/output-common.js +5 -2
- package/dist/src/parameterized-recorded-fill.js +1 -1
- package/dist/src/perf-facade.js +2 -2
- package/dist/src/perf-runtime-operation-builder.js +1 -1
- package/dist/src/perf-runtime-plan.js +1 -1
- package/dist/src/perf.js +1 -1
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/platform-request-scope.js +1 -1
- package/dist/src/platform-runtime-android-adb-host.js +1 -1
- package/dist/src/platform-runtime-host.js +1 -1
- package/dist/src/platform-runtime-managed-owner.js +1 -1
- package/dist/src/platform-runtime-open-target.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +4 -4
- package/dist/src/platform-runtime-runtime-hints.js +2 -2
- package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-transport.js +1 -1
- package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-harmony-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-process-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-crop-bytes.js +1 -1
- package/dist/src/png-worker-client.js +1 -0
- package/dist/src/png.js +1 -1
- package/dist/src/prepare-kind.js +1 -1
- package/dist/src/provider-session-ownership.js +1 -1
- package/dist/src/provider-webdriver.js +1 -1
- package/dist/src/proxy.js +1 -1
- package/dist/src/quality-warnings.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/rect-center.js +1 -1
- package/dist/src/register-builtins.js +1 -1
- package/dist/src/registry.js +35 -35
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/replay-divergence.js +1 -1
- package/dist/src/replay.js +1 -1
- package/dist/src/reporting.js +1 -1
- package/dist/src/request-admission.js +1 -1
- package/dist/src/request-cancel.js +1 -1
- package/dist/src/request-runtime-binding.js +1 -1
- package/dist/src/result-serialization.js +1 -1
- package/dist/src/retry.js +1 -1
- package/dist/src/runner-cache-metadata.js +2 -2
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-contract.js +3 -0
- package/dist/src/runner-dev-tools-security.js +1 -0
- package/dist/src/runner-device-readiness.js +1 -0
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-operations-facade.js +1 -1
- package/dist/src/runner-presentation.js +1 -1
- package/dist/src/runner.js +1 -1
- package/dist/src/runtime-transport-hints.js +1 -1
- package/dist/src/runtime.js +3 -3
- package/dist/src/runtime10.js +1 -1
- package/dist/src/runtime2.js +4 -4
- package/dist/src/runtime3.js +1 -1
- package/dist/src/runtime4.js +5 -5
- 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 +1 -1
- package/dist/src/screen-recording-admission-ledger.js +1 -0
- package/dist/src/screen-recording-completion.js +1 -1
- package/dist/src/screen-recording-options.js +1 -1
- package/dist/src/screen-recording-resource-recovery.js +1 -1
- package/dist/src/screen-recording-transport.js +1 -0
- package/dist/src/screenshot-density.js +1 -1
- package/dist/src/screenshot-image.js +1 -0
- package/dist/src/screenshot-runtime.js +1 -1
- package/dist/src/screenshot.js +1 -1
- package/dist/src/screenshot3.js +1 -1
- package/dist/src/script.js +1 -1
- package/dist/src/scroll-command.js +1 -1
- package/dist/src/scroll-gesture.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 +76 -1
- package/dist/src/sdk-contracts.js +2 -2
- package/dist/src/sdk-device.js +1 -1
- package/dist/src/sdk-finders.d.ts +1 -1
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-io.js +1 -1
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +29 -3
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selection.js +0 -0
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/semantic-index.js +1 -1
- package/dist/src/server.js +1 -1
- package/dist/src/session-allocation.js +1 -1
- package/dist/src/session-observation.js +1 -1
- package/dist/src/session-routing.js +1 -1
- package/dist/src/session-runtime-admission.js +1 -1
- package/dist/src/session-snapshot.js +1 -1
- package/dist/src/session-store.js +3 -3
- package/dist/src/session2.js +4 -5
- package/dist/src/settings.js +1 -1
- package/dist/src/simctl-facade.js +1 -1
- package/dist/src/simctl.js +1 -1
- package/dist/src/simulator-boot.js +1 -1
- package/dist/src/simulator-facade.js +1 -1
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-capture-annotations.js +1 -1
- package/dist/src/snapshot-diagnostics.js +1 -1
- package/dist/src/snapshot-quality-backend-capabilities.js +1 -1
- package/dist/src/snapshot-runtime-binding.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-state.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/snapshot3.js +1 -1
- package/dist/src/snapshot4.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src4.js +1 -1
- package/dist/src/src7.js +1 -1
- package/dist/src/src8.js +2 -2
- package/dist/src/stop-sequence.js +1 -1
- package/dist/src/string-enum.js +1 -1
- package/dist/src/takeover.js +1 -1
- package/dist/src/text-entry-focus.js +1 -1
- package/dist/src/tool-provider.js +1 -1
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/touch-runtime.js +1 -1
- package/dist/src/transport.js +1 -1
- package/dist/src/tree.js +1 -1
- package/dist/src/tv-remote.js +1 -1
- package/dist/src/type-text-runtime.js +1 -1
- package/dist/src/verified-file.js +1 -1
- package/dist/src/video.js +1 -1
- package/dist/src/viewport.js +1 -1
- package/dist/src/web.js +1 -1
- package/dist/src/web2.js +1 -1
- package/dist/src/webdriver-source.js +1 -1
- package/dist/src/window-state.js +1 -1
- package/package.json +4 -1
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.6.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.6.apk.sha256 +0 -1
- package/dist/src/session-target-evidence.js +0 -1
- package/dist/src/vars.js +0 -2
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import{C as e,T as t,o as n,w as r}from"./sdk-contracts.js";import"./capture.js";import{r as i}from"./sdk-batch-runner.js";import{p as a}from"./android-input-ownership.js";import{c as o,l as s,o as c,v as l}from"./sdk-device.js";import{d as u,l as d,n as f,r as p}from"./lease-scope.js";import{Mr as m,Sr as h,Tr as ee,Wt as te,Xt as ne,Yt as re,tr as ie,zr as g}from"./sdk-batch.js";import{a as ae,n as oe,r as se}from"./script.js";import"./session-store.js";import{r as ce}from"./format.js";import{r as _}from"./diagnostics.js";import"./diagnostics2.js";import{r as le}from"./command.js";import{n as v}from"./runtime-transport-hints.js";import{_ as ue,a as de,c as fe,d as y,f as b,g as pe,h as me,i as he,l as ge,m as _e,n as x,o as ve,p as ye,r as be,s as S,u as xe,v as Se}from"./human-control-contract.js";import{n as Ce,t as we,u as Te}from"./provider-session-ownership.js";import{i as Ee}from"./request-runtime-binding.js";import{r as De}from"./application-lifecycle-runtime.js";import{a as Oe,c as C,l as ke,n as Ae,o as je,r as Me,t as Ne}from"./device-claim-inspection.js";import{b as Pe,c as Fe,g as Ie,i as Le,p as Re,x as w}from"./perf-runtime-plan.js";import{n as ze,r as Be,t as Ve}from"./lease-context.js";import{d as He,g as Ue,u as We}from"./screenshot-runtime.js";import{a as Ge,c as Ke,d as T,l as qe,n as Je,o as Ye,r as Xe,u as E}from"./src8.js";import{n as Ze,t as Qe}from"./compatibility-policy.js";import{o as $e}from"./screen-recording-resource-recovery.js";import D from"node:path";import"node:fs";import et,{createHash as tt}from"node:crypto";import nt from"node:os";import O from"node:fs/promises";function rt(t,n){if(n?.replayBackend&&n.replayBackend!==`maestro`)throw new e(`INVALID_ARGS`,`Unsupported replay backend "${n.replayBackend}".`);return{...oe(t),metadata:se(t)}}function it(e,t){return k(e,t)?t:`${e}:${t}`}function k(e,t){return t.startsWith(`${e}:`)}function at(e,t){return!e.partitioned||k(e.tenant,t)}var ot=class{active=new Map;waiters=new Map;async run(e,t){this.active.set(e,(this.active.get(e)??0)+1);try{return await t()}finally{let t=(this.active.get(e)??1)-1;if(t>0)this.active.set(e,t);else{this.active.delete(e);let t=this.waiters.get(e);this.waiters.delete(e);for(let e of t??[])e()}}}async wait(e,t){if(t?.throwIfAborted(),!this.active.has(e))return;let n=this.waiters.get(e)??new Set,r=()=>{},i=()=>{};try{await new Promise((a,o)=>{r=a,i=()=>o(t?.reason),n.add(r),this.waiters.set(e,n),t?.addEventListener(`abort`,i,{once:!0})})}finally{t?.removeEventListener(`abort`,i),n.delete(r),n.size===0&&this.waiters.get(e)===n&&this.waiters.delete(e)}}},st=class{entriesByLeaseId=new Map;retain(e,t){let n={wanted:t,released:!1},r=this.entriesByLeaseId.get(e)??new Set;return r.add(n),this.entriesByLeaseId.set(e,r),{leaseId:e,release:()=>this.releasePass(e,r,n)}}forget(e){let t=this.entriesByLeaseId.get(e);if(t){for(let e of t)e.released=!0;this.entriesByLeaseId.delete(e)}}isDeferred(e){let t=this.entriesByLeaseId.get(e);if(!t)return!1;for(let e of t)e.wanted()||t.delete(e);return t.size>0||(this.entriesByLeaseId.delete(e),!1)}releasePass(e,t,n){return!n.released&&(n.released=!0,t.delete(n),t.size===0&&this.entriesByLeaseId.delete(e),n.wanted())}},ct=class{holdsByDevice=new Map;mutations=new ot;inFlightWork=new st;leases=new Map;runBindings=new Map;deviceBindings=new Map;maxActiveSimulatorLeases;resolveLeaseTtlMs;now;onLeaseExpired;providerSessionOwnership;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.resolveLeaseTtlMs=ge(e),this.now=e.now??(()=>Date.now()),this.onLeaseExpired=e.onLeaseExpired,this.providerSessionOwnership=new we({now:this.now,retentionMs:e.providerSessionRetentionMs})}allocateLease(e){let t=ye(e);this.cleanupExpiredLeases();let n=this.resolveLeaseTtlMs(t.ttlMs);this.assertHumanControlAdmission(t);let r=this.refreshExistingRunBinding(t,n);if(r)return r;this.assertDeviceAvailable(t),this.enforceCapacity(t.backend);let i=fe(t,n,this.now());return this.leases.set(i.leaseId,i),this.bindLease(i),{...i}}refreshExistingRunBinding(e,t){let n=b(e),r=this.runBindings.get(n);if(!r)return;let i=this.leases.get(r);if(!i){this.runBindings.delete(n);return}if(i.clientId===e.clientId)return this.refreshLease(i,t);if(i.deviceKey)throw xe(i);return S(i,e),this.refreshLease(i,t)}heartbeatLease(e){let t=pe(e.leaseId);this.cleanupExpiredLeases();let n=this.getActiveLease(t);ve(n,e),S(n,e);let r=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(n,r)}retainLeaseWork(e,t){let n=this.inFlightWork.retain(e.leaseId,t);return{leaseId:n.leaseId,release:()=>{let t=n.release();return t&&this.refreshProtectedLease(e.leaseId,this.now()),t}}}releaseLease(e){let t=this.getLease(e);return t?(this.leases.delete(t.leaseId),this.unbindLease(t),this.inFlightWork.forget(t.leaseId),{released:!0,lease:t}):{released:!1}}getLease(e){let t=pe(e.leaseId);this.cleanupExpiredLeases();let n=this.leases.get(t);if(n)return ve(n,e),S(n,e),{...n}}assertLeaseAdmission(e){let t=_e(e);this.cleanupExpiredLeases(),S(this.getActiveLease(t.leaseId),t)}listActiveLeases(){return this.cleanupExpiredLeases(),Array.from(this.leases.values()).map(e=>({...e}))}recordProviderSession(e,t){this.cleanupExpiredLeases();let n=e.expiresAt<=this.now()?e.expiresAt:void 0;this.providerSessionOwnership.record(e,t),this.leases.has(e.leaseId)||this.providerSessionOwnership.markLeaseReleased(e,n)}resolveProviderSession(e){return this.cleanupExpiredLeases(),this.providerSessionOwnership.resolve(e)}listHumanControlHolds(e){this.cleanupExpiredLeases();let t=e.kind===`lease`?y(this.requireHumanControlLease(e.leaseId)):void 0;return[...this.holdsByDevice.entries()].filter(([e])=>t===void 0||t===e).flatMap(([,e])=>[...e.values()].map(({hold:e})=>x(e))).sort((e,t)=>e.id.localeCompare(t.id))}async putHumanControlHold(t,n,r,i){i?.throwIfAborted();let a=he(n),o=de(r);this.cleanupExpiredLeases();let s=this.resolveHumanControlScope(t,o),c=y(s),l=this.findHumanControlHold(a);if(l&&(this.assertHoldAuthority(t,l),y(l.hold.scope)!==c))throw new e(`INVALID_ARGS`,`Release a hold before changing its device scope.`);let u=this.now(),d={...t.kind===`lease`?{ownerLeaseId:t.leaseId}:{},hold:{id:a,scope:s,state:`activating`,...o.reason?{reason:o.reason}:{},createdAt:l?.hold.createdAt??u,updatedAt:u}},f=this.holdsByDevice.get(c)??new Map;return this.holdsByDevice.set(c,f),f.set(a,d),await this.activateHumanControlHold(c,d,o.ttlMs,i)}async activateHumanControlHold(t,n,r,i){let a=this.holdsByDevice.get(t),{id:o}=n.hold;try{if(await this.mutations.wait(t,i),i?.throwIfAborted(),a.get(o)!==n)throw new e(`COMMAND_FAILED`,`Human-control hold changed before activation completed.`,{holdId:o});let s=this.now();return n.hold={...n.hold,state:`active`,updatedAt:s,...r===void 0?{}:{expiresAt:s+r}},this.refreshHeldLease(t,s),x(n.hold)}catch(e){throw a.get(o)===n&&this.deleteHumanControlHold(t,o),e}}removeHumanControlHold(e,t){let n=he(t);this.cleanupExpiredLeases();let r=this.findHumanControlHold(n);if(!r)return;this.assertHoldAuthority(e,r);let i=y(r.hold.scope);return this.deleteHumanControlHold(i,n),x(r.hold)}deleteHumanControlHold(e,t){let n=this.holdsByDevice.get(e);n.delete(t),n.size===0&&(this.holdsByDevice.delete(e),this.refreshHeldLease(e,this.now()))}assertHumanControlAdmission(e){this.expireHumanControlHolds();let t=y(e),n=t===void 0?void 0:this.holdsByDevice.get(t)?.values().next().value;if(n)throw be(n.hold)}async runDeviceMutation(e,t){if(!e)return await t();this.cleanupExpiredLeases();let n=this.getActiveLease(e.leaseId);this.assertHumanControlAdmission(n);let r=y(n);return r===void 0?await t():await this.mutations.run(r,t)}requireHumanControlLease(t){let n=this.getActiveLease(t);if(!n.deviceKey)throw new e(`UNSUPPORTED_OPERATION`,`Human control requires a device-scoped remote lease.`);return{...n,deviceKey:n.deviceKey}}resolveHumanControlScope(t,n){if(t.kind===`host`){if(!n.scope)throw new e(`INVALID_ARGS`,`Host human control requires a lease device scope.`);return n.scope}if(n.scope)throw new e(`INVALID_ARGS`,`Lease-owner human control uses the admitted lease device; do not supply scope.`);let r=this.requireHumanControlLease(t.leaseId);return{backend:r.backend,leaseProvider:r.leaseProvider,deviceKey:r.deviceKey}}assertHoldAuthority(t,n){if(t.kind===`host`)return;let r=this.requireHumanControlLease(t.leaseId);if(n.ownerLeaseId!==r.leaseId||y(r)!==y(n.hold.scope))throw new e(`UNAUTHORIZED`,`Human-control hold does not belong to the admitted lease.`,{reason:`LEASE_SCOPE_MISMATCH`})}findHumanControlHold(e){for(let t of this.holdsByDevice.values()){let n=t.get(e);if(n)return n}}hasHumanControl(e){let t=y(e);return t!==void 0&&this.holdsByDevice.has(t)}isLeaseProtected(e,t){return e.expiresAt>t||this.hasHumanControl(e)||this.inFlightWork.isDeferred(e.leaseId)}expireHumanControlHolds(){let e=this.now();for(let[t,n]of this.holdsByDevice){let r=0;for(let[t,{hold:i}]of n)i.expiresAt===void 0||i.expiresAt>e||(r=Math.max(r,i.expiresAt),n.delete(t));n.size===0&&(this.holdsByDevice.delete(t),this.refreshHeldLease(t,r))}}refreshHeldLease(e,t){this.refreshProtectedLease(this.deviceBindings.get(e),t)}refreshProtectedLease(e,t){let n=e?this.leases.get(e):void 0;n&&this.refreshLease(n,n.expiresAt-n.heartbeatAt,Math.max(t,n.heartbeatAt))}consumeExpiredLeases(){this.expireHumanControlHolds();let e=this.now(),t=[];for(let n of this.leases.values()){if(this.isLeaseProtected(n,e))continue;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};t.push(r),this.onLeaseExpired?.(r)}return t}consumeExpiredLease(e){this.expireHumanControlHolds();let t=me(e);if(!t)return;let n=this.leases.get(t);if(!n||this.isLeaseProtected(n,this.now()))return;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};return this.onLeaseExpired?.(r),r}cleanupExpiredLeases(){this.consumeExpiredLeases()}enforceCapacity(t){if(t!==`ios-simulator`||this.maxActiveSimulatorLeases<=0)return;let n=Array.from(this.leases.values()).filter(e=>e.backend===`ios-simulator`).length;if(!(n<this.maxActiveSimulatorLeases))throw new e(`DEVICE_IN_USE`,`No simulator lease capacity available`,{reason:`LEASE_CAPACITY_EXCEEDED`,activeLeases:n,maxActiveLeases:this.maxActiveSimulatorLeases,backend:t,hint:`Retry after releasing another simulator lease.`})}getActiveLease(t){let n=this.leases.get(t);if(n)return n;throw new e(`UNAUTHORIZED`,`Lease is not active`,{reason:`LEASE_NOT_FOUND`})}refreshLease(e,t,n=this.now()){let r={...e,heartbeatAt:n,expiresAt:n+t};return this.leases.set(r.leaseId,r),this.bindLease(r),{...r}}bindLease(e){this.runBindings.set(b(e),e.leaseId);let t=y(e);t&&this.deviceBindings.set(t,e.leaseId)}unbindLease(e,t=this.now()){this.runBindings.delete(b(e));let n=y(e);n&&this.deviceBindings.delete(n),this.providerSessionOwnership.markLeaseReleased(e,t)}assertDeviceAvailable(e){let t=y({backend:e.backend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey});if(!t)return;let n=this.deviceBindings.get(t);if(!n)return;let r=this.leases.get(n);if(!r){this.deviceBindings.delete(t);return}throw xe(r)}};function lt(t){let n=Se(t.meta?.sessionIsolation??t.flags?.sessionIsolation),r=t.meta?.tenantId??t.flags?.tenant,i=ue(r);if(r&&!i)throw new e(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(n!==`tenant`)return t;if(!i)throw new e(`INVALID_ARGS`,`session isolation mode tenant requires --tenant (or meta.tenantId).`);let a=t.session||`default`;return k(i,a)?{...t,meta:{...t.meta,tenantId:i,sessionIsolation:n}}:{...t,session:it(i,a),meta:{...t.meta,tenantId:i,sessionIsolation:n}}}function ut(t,n,r,i={}){if(He(t.command))return;let a=ze(t);pt(t,a);let o=r?.lease;if(r===void 0&&!a.leaseId&&dt(t,i.providerAppCatalog))return;if(t.command===`human_control`&&!o&&!a.leaseId)throw new e(`UNSUPPORTED_OPERATION`,`Takeover requires an active remote device lease. Local takeover is not supported.`);if(t.command!==`human_control`&&!o&&t.meta?.sessionIsolation!==`tenant`&&(!a.leaseId||!a.tenantId&&!a.runId))return;mt(a,o);let s=Be(t,r),c={...s,leaseTtlMs:s.leaseTtlMs??(p(s)?3e5:void 0)};n.assertLeaseAdmission(d(s));let l=n.heartbeatLease(d(c));return We(t)&&n.assertHumanControlAdmission(l),l}function dt(e,t){let n=Ue(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function ft(e){He(e.command)||pt(e,ze(e))}function pt(t,n){if(t.command!==`open`)return;let r=f(n);if(r.length!==0)throw new e(`INVALID_ARGS`,`Proxy open requires leaseId, tenantId, runId, clientId, and deviceKey lease metadata.`,{missing:r})}function mt(e,t){t&&(A(`leaseId`,e.leaseId,t.leaseId),A(`tenantId`,e.tenantId,t.tenantId),A(`runId`,e.runId,t.runId),A(`leaseProvider`,e.leaseProvider,t.leaseProvider),A(`clientId`,e.clientId,t.clientId),A(`deviceKey`,e.deviceKey,t.deviceKey))}function A(t,n,r){if(!(!n||!r||n===r))throw new e(`UNAUTHORIZED`,`Lease does not match session owner (${t})`,{reason:`LEASE_SESSION_MISMATCH`,field:t})}async function ht(e,t){if(!t.leaseProvider||!e)return!1;try{return await e(t),_({level:`info`,phase:`provider_lease_expired_released`,data:{leaseId:t.leaseId,provider:t.leaseProvider}}),!0}catch(e){return _({level:`error`,phase:`provider_lease_expiry_release_failed`,data:{leaseId:t.leaseId,provider:t.leaseProvider,error:e instanceof Error?e.message:String(e)}}),!1}}function gt(e){ft(e)}async function _t(e){let t=e.sessionStore.get(e.sessionName),n=t?.lease;return!t||!n||!e.leaseRegistry.consumeExpiredLease(n.leaseId)?!1:(_({level:`info`,phase:`leased_session_expired`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,deviceKey:n.deviceKey}}),await e.teardownSession(t,t.name).catch(e=>{_({level:`debug`,phase:`leased_session_expiry_cleanup_failed`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,error:e instanceof Error?e.message:String(e)}})}),await Pe(t.deviceClaim).catch(e=>{_({level:`warn`,phase:`leased_session_expiry_device_claim_clear_failed`,data:{session:t.name,deviceKey:t.deviceClaim?.deviceKey,error:e instanceof Error?e.message:String(e)}})}),e.sessionStore.delete(t.name),!0)}function vt(e){let{sessionName:t,sessionStore:n,leaseRegistry:r}=e,i=n.get(t),a=ut(e.req,r,i,{providerAppCatalog:e.providerAppCatalog});if(!a)return e.req;let o={...e.req,internal:{...e.req.internal,admittedLease:a}};return i?.lease&&n.set(t,{...i,lease:{...i.lease,leaseBackend:a.backend,expiresAt:a.expiresAt}}),o}function yt(e){return Ve(e.req,e.req.internal?.admittedLease)??e.existingLease}async function bt(e){let t=e.session.lease;if(!t)return;let n=u({leaseId:t.leaseId,tenantId:t.tenantId,runId:t.runId,leaseBackend:t.leaseBackend,leaseProvider:t.leaseProvider,deviceKey:t.deviceKey,clientId:t.clientId}),r=e.leaseRegistry.getLease(n),i=r?await e.leaseLifecycleProvider?.release?.(r):void 0,a=Ce(i);r&&a&&e.leaseRegistry.recordProviderSession(r,a);let o=e.leaseRegistry.releaseLease(n);return _({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:o.released}}),i}const xt=[`platform`,`target`],St=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function Ct(e){return c({deviceName:e?.device,udid:e?.udid,serial:e?.serial})}function wt(e){return Ct(e)||Dt(e,xt)}function Tt(e){return wt(e)||Dt(e,St)}function Et(e){return typeof e==`string`&&e.trim().length>0}function Dt(e,t){return e?t.some(t=>Et(e[t])):!1}function Ot(e){return{appleSimulatorAppTarget:kt(e)}}function kt(e){return e&&!i(e)?e:void 0}function At(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return tt(`sha256`).update(ie(t),`utf8`).digest(`hex`)}function jt(e,t,n){return new Bt(Nt(Mt(t.resolve(e))),n).parse()}function Mt(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Nt(t){let n=[],r=0;for(;r<t.length;){let i=t.slice(r),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){r+=a;continue}let o=Pt(i);if(!o)throw new e(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);n.push(o.value),r+=o.length}return n}function Pt(e){return Ft(e)??It(e)??Lt(e)??Rt(e)??zt(e)}function Ft(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function It(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Lt(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Rt(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function zt(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var Bt=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let t=this.parseOr();if(this.peek())throw new e(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return t}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let t=this.peek();if(!t)throw new e(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(t.type===`boolean`)return this.index+=1,t.value;if(t.type===`paren`&&t.value===`(`){this.index+=1;let t=this.parseOr();if(!this.consumeParen(`)`))throw new e(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return t}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new e(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let t=this.peek();if(t?.type!==`operator`||t.value!==`==`&&t.value!==`!=`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,t}consumeStringLiteral(){let t=this.peek();if(t?.type!==`string`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,t.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function Vt(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Ht(e,t){return{...N(e,t),source:e.source}}function j(t,n,r){if(t===void 0)return;let i=r??Ge[n]??{},a=Ye(i),o;if(typeof t==`number`)o=t;else{let r=t.trim();if(r===``)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);o=Number(r)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);return o}function Ut(e,t,n,r){return j(e===void 0?t:n.resolve(String(e)),r)}function M(e){if(e?.aborted)throw t()}async function Wt(t,n){if(t.include.kind===`commands`)return{kind:`program`,source:t.source,config:{},commands:t.include.commands};if(!n.loadProgram)throw new e(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return M(n.signal),n.signal?await n.loadProgram(t.include.path,t.source.path,n.signal):await n.loadProgram(t.include.path,t.source.path)}function Gt(e,t){if(e.include.kind===`file`)return D.resolve(t?D.dirname(t):process.cwd(),e.include.path)}function Kt(e){return e===void 0?void 0:D.resolve(e)}function qt(t,n){let r=Gt(t,t.source.path);if(r&&n.has(r))throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function Jt(t,n,r,i){let a=t.include.kind===`file`?Kt(n.source.path):void 0,o=new Set([r,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function Yt(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:jt(e.true,t,n.platform)}function Xt(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function N(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>N(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,N(n,t)])):e}async function Zt(e,t){M(t.signal);let n=Kt(e.source.path),r={options:t,context:Ke(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await Qt(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function Qt(e,t,n,r,i){M(i.options.signal);let a=ln(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await en(s,a,o,e.source.path??r,i));return n}finally{s()}}async function $t(e,t,n,r,i){let a=[];for(let o of e)a.push(...await en(o,t,n,r,i));return a}async function en(e,t,n,r,i){M(i.options.signal);let a=un(e,r);switch(a.kind){case`runFlow`:{let e=nn(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await tn(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[P(a,t,n,o)]}case`repeat`:return[P(a,t,n,await $t(a.commands,t,n,r,i))];case`retry`:return[P(a,t,n,await $t(a.commands,t,n,r,i))];default:return[sn(a,t,n)]}}async function tn(e,t,n,r,i){let a=an(e,i.context),o=qt(a,i.activeIncludePaths),s=await Wt(a,i.options);M(i.options.signal);let c=Jt(a,s,o,i.activeIncludePaths),l=ln(t,e.env),u=i.context.enter(e.env);try{return await Qt(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function nn(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:rn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function rn(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return on(t.context.resolveDeferred(e))?`opaque`:jt(e,t.context,t.options.platform)?void 0:`omit`}function an(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function on(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function sn(e,t,n){return T({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function P(e,t,n,r){return T({kind:`opaque`,command:cn(e),source:e.source,scopes:t,body:r,appId:n})}function cn(e){switch(e.kind){case`runFlow`:return T({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return{kind:e.kind,source:e.source,times:e.times};case`retry`:return T({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function ln(e,t){return t===void 0?e:[...e,t]}function un(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function dn(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await Zt(e,t),a=fn(t.runtimeHints),o=T({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=At(o);return pn({...o,digest:s})}function fn(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function pn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))pn(t);return Object.freeze(e)}function mn(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`||n.command.kind===`evalScript`)return{allowed:!1,reason:`step ${t+1} (${n.command.kind}) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function hn(t,n={}){let r=mn(t,n);if(!r.allowed)throw new e(`INVALID_ARGS`,r.reason);return r.startIndex}function gn(t,n){if(!Number.isInteger(n)||n<0||n>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${n} is out of range for a ${t.total}-step plan.`);return n}const _n=`maestro-test-failure`;function F(t,n={}){return new e(`COMMAND_FAILED`,t,{...n,reason:_n})}function vn(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&t.details?.reason===_n}const yn=new Set([``,`false`,`0`,`null`,`undefined`]);function bn(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!yn.has(e)}async function xn(e,t){M(t.options.signal);try{return await Pn(e,t.context,async()=>await Sn(e,t))}catch(t){throw R(t,e)}}async function Sn(e,t){if(e.kind===`command`)return await Cn(e.command,e.appId,t);await kn(e,t)}async function Cn(e,t,n){if(e.kind===`evalScript`)return await En(e,n);let r=Ht(e,n.context);try{return await Dn(r,t,n)}catch(e){if(M(n.options.signal),Tn(r)&&vn(e)){n.warnings.push(wn(r,e)),n.skipped+=1;return}throw Fn(e,r)}}function wn(t,n){let r=`${t.source.path?`${t.source.path}:`:``}line ${t.source.line}`,i=n instanceof e?n.message:String(n);return`Optional Maestro ${t.kind} skipped at ${r}: ${i}`}function Tn(e){return`optional`in e&&e.optional===!0}async function En(t,n){let{evaluateMaestroEvalScript:r}=await import(`./engine-eval-script.js`);if(n.options.trustedScripts===!1)throw new e(`UNAUTHORIZED`,`Maestro evalScript is not permitted for flows received over the remote daemon surface: node:vm is not a security sandbox, so an untrusted expression can escape to the host.`);let i=await r(t.script,n.context.values);n.context.replaceOutput(i),n.executed+=1}async function Dn(e,t,n){switch(e.kind){case`assertVisible`:await L({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await L({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!bn(e.condition))throw F(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await L(Nn(e),j(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await On(e,t,n)}}async function On(e,t,n){let r=T({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return M(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function kn(e,t){let n=Ht(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await jn(n.when,t)){t.skipped+=1;return}t.executed+=1,await I(e.body,t);return;case`repeat`:{let r=Ut(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)M(t.options.signal),await I(e.body,t);return}case`retry`:{let r=Math.min(Ut(n.maxRetries,1,t.context,`retry.maxRetries`),Ze.control.retryMaxRetries);t.executed+=1,await An(e.body,r,t);return}}}async function I(e,t){for(let n of e)await xn(n,t)}async function An(t,n,r){let i;for(let e=0;e<=n;e+=1){M(r.options.signal);try{await I(t,r);return}catch(e){if(M(r.options.signal),!vn(Ln(e)))throw e;i=R(e,t[0])}}throw i||new e(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function jn(e,t){if(!Yt(e,t.context,t.options))return!1;for(let n of Xt(e))if(M(t.options.signal),!(await Mn(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function L(e,t,n){if(!(await Mn(e,t,n)).matched)throw F(`Maestro ${e.kind} condition did not match.`)}async function Mn(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return M(n.options.signal),n.context.recordObservation(i),i}function Nn(t){if(t.visible)return{kind:`visible`,selector:t.visible};if(t.notVisible)return{kind:`notVisible`,selector:t.notVisible};throw new e(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function Pn(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function R(e,t){if(In(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Rn(e,t?.command),source:n,...t?{command:t.command}:{}}}function Fn(e,t){return{kind:`maestroPlanStepFailure`,error:Rn(e,t),source:t.source,command:t}}function In(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Ln(e){return In(e)?e.error:e}function Rn(t,n){if(!(t instanceof e)||!n||/\bline \d+\b/.test(t.message))return t;let r=n.source.path?`${n.source.path}:`:``;return new e(t.code,`${t.message} (${r}line ${n.source.line})`,t.details)}async function zn(t,n,r={}){M(r.signal);let i=r.startIndex??0;if(!Number.isInteger(i)||i<0||i>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${t.total}-step plan.`);let a={plan:t,port:n,options:r,context:Ke(r.defaults,r.env?{...r.env}:{}),timing:Qe,artifacts:new Set,warnings:[],executed:t.compatibility.staticallyExecutedControls,skipped:t.compatibility.staticallySkippedControls};for(let e=i;e<t.steps.length;e+=1)try{await Bn(t.steps[e],e,a)}catch(e){throw Ln(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Bn(e,t,n){M(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};z(()=>n.options.observer?.commandStarted?.(s));try{let t=await xn(e,n);M(n.options.signal),z(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Vn(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=R(t,e);throw z(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Vn(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts],warnings:[...n.warnings]})),o}}function Vn(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries,settleLatches:t.settleLatches-e.settleLatches,settleTimeouts:t.settleTimeouts-e.settleTimeouts}}}function z(e){try{e?.()}catch{}}async function Hn(e,t,n={}){let r=Un(e,n);return await zn(e,t,{...n,startIndex:r})}function Un(e,t){return t.from!==void 0||t.planDigest!==void 0?hn(e,{from:t.from,planDigest:t.planDigest}):gn(e,t.startIndex??0)}function Wn(e){return Vt(e)?{command:e.kind,...e.kind===`runFlow`?V(e.label??e.includePath):{}}:{command:e.kind,...Gn(e)}}function Gn(e){return`label`in e&&e.label?V(e.label):Kn(e)?V($n(e.target)):qn(e)?Jn(e):e.kind===`inputText`?V(`<text>`):Yn(e)}function Kn(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function qn(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Jn(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return V(B(e.target));case`extendedWaitUntil`:return V(B(e.visible??e.notVisible));case`scrollUntilVisible`:return V(B(e.element))}}function Yn(e){return Xn(e)?Zn(e):e.kind===`swipe`?Qn(e):e.kind===`runFlow`?V(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?V(String(e.condition)):{}}function Xn(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function Zn(e){switch(e.kind){case`openLink`:return V(e.link);case`takeScreenshot`:return V(e.path);case`runScript`:return V(e.file);case`pressKey`:return V(e.key)}}function Qn(e){return V(e.gesture.kind===`coordinates`?`${er(e.gesture.start)} to ${er(e.gesture.end)}`:e.gesture.direction)}function $n(e){return e.space===`target`?B(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function B(e){return e?.id??e?.text}function er(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function V(e){return e?{value:e}:{}}const tr=new Set(String.raw`^$\.*+?()[]{}|`);function nr(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function rr(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if(tr.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!tr.has(i))return;t+=i,n+=1}return t}function ir(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(g(e.rect))return t.isVisibleInEffectiveViewport(e);if(e.rect)return!1;if(n!==`android`&&e.hittable===!0)return!0;let r=t.findAncestor(e,e=>ee(e,n)?e:null);return r?g(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function ar(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function or(e,t){let n=[t.id===void 0?void 0:cr(e.identifier,t.id),t.text===void 0?void 0:lr(e,t.text)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function sr(e){return e.matches.filter(t=>ir(t,e.visibility,e.platform))}function cr(e,t){let n=e??``;return E(n)===E(t)||nr(n,t)}function lr(e,t){return[e.label,qe(e),e.identifier].filter(e=>!!e).some(e=>cr(e,t))}function ur(e){return e.index!==void 0||e.childOf!==void 0||e.below!==void 0||e.above!==void 0||e.leftOf!==void 0||e.rightOf!==void 0||e.containsChild!==void 0||e.containsDescendants!==void 0}function dr(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function fr(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=mr(a.rect,e.rect);n===void 0||!pr(t,a.rect,e.rect)||r.push({node:a,distance:n,order:i++})}return r.sort((e,t)=>e.distance-t.distance||e.order-t.order),r.map(({node:e})=>e)}function pr(e,t,n){switch(e){case`below`:return t.y>n.y;case`above`:return t.y<n.y;case`leftOf`:return t.x<n.x;case`rightOf`:return t.x>n.x}}function mr(e,t){if(!(!hr(e)||!hr(t)))return Math.fround(Math.hypot(H(e.x,e.width)-H(t.x,t.width),H(e.y,e.height)-H(t.y,t.height)))}function hr(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function H(e,t){return e+Math.trunc(t/2)}function gr(t,n={},r={}){let i=h(t.nodes,n);n.onVisibilityContextCreated?.();let a=new WeakMap,o=new WeakSet,s=new WeakMap,c=new Map,l=e=>e.parentIndex===void 0?void 0:i.nodeByIndex.get(e.parentIndex)??t.nodes[e.parentIndex],u=e=>{let t=s.get(e);if(t)return t;let n=new Set,r=new Set,i=l(e);for(;i&&!r.has(i.index);)r.add(i.index),n.add(i.index),i=l(i);return s.set(e,n),n},d=(e,r)=>{let i=c.get(e);i||(i=new WeakMap,c.set(e,i));let a=i.get(r);if(a)return a;n.onPositionComputed?.(e,r);let o=fr(t.nodes,e,m(r).indexed),s={ordered:o,candidateIndexes:new Set(o.map(e=>e.index))};return i.set(r,s),s},f=(e,t)=>d(e,t).ordered,p=(e,t)=>d(e,t).candidateIndexes,m=i=>{let s=a.get(i);if(s)return s;if(o.has(i))throw new e(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),n.onSelectorComputed?.(i);try{let e=_r(t,i,l,u,m,p),n={matches:e,indexed:xr(e,i.index,r.orderUnindexed)};return a.set(i,n),n}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function _r(e,t,n,r,i,a){let{index:o,childOf:s,below:c,above:l,leftOf:u,rightOf:d,containsChild:f,containsDescendants:p,...m}=t,h=dr(m)?e.nodes.filter(e=>or(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>yr(r(t),e))}if(f){let e=new Set(i(f).indexed.map(n).filter(e=>e!==void 0).map(e=>e.index));h=h.filter(t=>e.has(t.index))}if(p){let e=p.map(e=>vr(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of br(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function vr(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function yr(e,t){for(let n of e)if(t.has(n))return!0;return!1}function br(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function xr(e,t,n){if(t===void 0)return n?n(e):[...e];let r=Cr(e)[wr(t)];return r?[r]:[]}function Sr(e,t){return t===void 0?e[0]:Cr(e)[wr(t)]}function Cr(e){return[...e].sort((e,t)=>{let n=U(e.rect?.y),r=U(t.rect?.y);return n===r?U(e.rect?.x)-U(t.rect?.x):n-r})}function U(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function wr(t){let n=typeof t==`number`?t:Number(t.trim());if(!Number.isSafeInteger(n)||n<0)throw new e(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return n}const Tr={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Er(e,t){let n=Tr[t];if(n.kind===`divergence`)return n;let r=a(e);return r?r.kind!==`exact`||r.provider!==n.provider?{kind:`divergence`,provider:n.provider,reason:`unregistered-provider-evidence`}:r:{kind:`divergence`,provider:n.provider,reason:`exact-evidence-not-retained`}}function W(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Dr(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Dr(e){return e===!0?2:+(e===!1)}function Or(e,t,n,r={}){let i=Er(e,n),a=Ar(e,i,r),o=kr(t,a),s=sr({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:jr(s,t,n,a.visibility,i)}}function kr(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Ar(e,t,n={}){return gr(e,n,t?{orderUnindexed:e=>W(e,t)}:{})}function jr(e,t,n,r,i){let a=n!==`ios`||!Fr(t)?e:e.filter(n=>{if(Rr(n))return!0;let i=e.filter(e=>e!==n&&Ir(n,e,t));return!i.some(e=>Rr(e)&&ar(n,e,r))&&!i.some(e=>ar(e,n,r))});return t.index===void 0&&i?W(a,i):a}function Mr(e,t){let n=t===void 0?e.find(G):Nr(e,t);return!n||!G(n)?null:{node:n,rect:n.rect}}function Nr(e,t){return Sr(e,t)}function Pr(e){return G(e)?e.rect:void 0}function G(e){return g(e.rect)}function Fr(e){return e.id!==void 0||e.text!==void 0}function Ir(e,t,n){if(n.id!==void 0&&K(e.identifier)!==K(t.identifier))return!1;if(n.text!==void 0){let n=Lr(e),r=new Set(Lr(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Lr(e){return[e.label,e.value,e.identifier].map(K).filter(e=>e!==void 0)}function K(e){if(e)return E(e)||void 0}function Rr(e){let t=m(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const zr=Symbol(`maestroFlowProgram`),Br=Symbol(`maestroFailureCommand`),Vr=Symbol(`maestroFailurePlan`);function Hr(e,t){let n=Xe(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:Kr(n),[zr]:n}}async function Ur(e,t,n){let r;try{let i=Je(D.dirname(e.sourcePath),n.readSource),a=await dn(e[zr],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=hn(a,{from:n.from,planDigest:n.planDigest}),s=await Hn(a,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:i,signal:n.signal,startIndex:o,trustedScripts:n.trustedScripts,observer:Gr(a,n.observer,e=>{r=e})});return{ok:!0,replayed:a.total-o,planDigest:a.digest,startIndex:o,artifactPaths:s.artifactPaths,...s.warnings?{warnings:s.warnings}:{}}}catch(e){return{ok:!1,error:r?.error??e,...r?{failure:r}:{}}}}function Wr(e,t){let n=Jr(e[Br]),r=e[Vr].platform;return!n||r!==`android`&&r!==`ios`?[]:Or(t,n.selector,r).ranked.map(e=>({node:e,basis:Yr(n.selector,e)}))}function Gr(e,t,n){return{commandStarted:e=>t?.actionStarted?.(q(e)),commandCompleted:e=>t?.actionCompleted?.({...q(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=mn(e,{from:r.stepIndex,planDigest:e.digest}),a={...q(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,warnings:[...r.warnings],isControl:Vt(r.command),redactions:r.command.kind===`inputText`&&r.command.text.length>0?[{name:`inputText.text`,value:r.command.text}]:[],resume:i.allowed?{allowed:!0,from:r.stepIndex,planDigest:e.digest}:{allowed:!1,from:r.stepIndex,planDigest:e.digest,reason:i.reason},[Br]:r.command,[Vr]:e};n(a),t?.actionFailed?.(a)}}}function q(e){let t=Wn(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function Kr(e){return[e.config.appId,...[...e.config.onFlowStart??[],...e.commands].filter(e=>e.kind===`launchApp`).map(e=>e.kind===`launchApp`?e.appId:void 0)].find(qr)}function qr(e){return!!(e?.trim()&&!e.includes(`$`)&&!i(e))}function Jr(e){switch(e.kind){case`tapOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`doubleTapOn`:case`longPressOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element};case`swipe`:return e.gesture.kind===`target`?{selector:e.gesture.from}:void 0;default:return}}function Yr(e,t){return e.id!==void 0||e.text!==void 0&&or({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}const Xr=`This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.`;function Zr(t,n){let r=t.files[n];if(r===void 0)throw new e(`INVALID_ARGS`,`replay script source is missing ${n}; it was not part of the script sources sent with this request.`,{path:n,entry:t.entry});return r}function Qr(e){if(e.command!==`replay`||e.flags?.replayFrom!==void 0)return;let t=e.flags?.replayScriptSource;if(t)try{let n=t.entry,r=Zr(t,n);if(ce(n,e.flags?.replayBackend)===`maestro`){let t=Hr(r,n);return{flags:e.flags??{},options:$r(t.appTarget,e.flags?.platform)}}let i=rt(r,e.flags),a=ei(i.actions);if(!a.appTarget)return;let o=ti(e.flags,i.actions),s=o.platform??i.metadata.platform;return{flags:s&&o.platform===void 0?{...o,platform:s}:o,options:s===`ios`?ri(a.appTarget):void 0}}catch{return}}function $r(e,t){return t===`ios`?ri(e)??{}:{}}function ei(e){let t=ae(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return ni(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function ti(e,t){let n=ei(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function ni(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!i(e))}function ri(e){let t=kt(e);return t?{appleSimulatorAppTarget:t}:void 0}const ii={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},J=new Map;async function ai(e){let t=await O.mkdtemp(D.join(nt.tmpdir(),`agent-device-materialized-`));try{let n=await li(e.installablePath,D.join(t,`installable`)),r=e.archivePath?await li(e.archivePath,D.join(t,`archive`)):void 0,i=et.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{ci(i)},a);return J.set(i,{rootPath:t,installablePath:n,archivePath:r,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:i,installablePath:n,...r?{archivePath:r}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await O.rm(t,{recursive:!0,force:!0}),e}}async function oi(e,t){await Y(e,Te(J,e,t,ii))}async function si(e){let t=Array.from(J.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await Y(e,t)}))}async function ci(e){let t=J.get(e);if(t)try{await Y(e,t)}catch{}}async function Y(e,t){clearTimeout(t.timer),J.delete(e),await O.rm(t.rootPath,{recursive:!0,force:!0})}async function li(e,t){let n=await O.stat(e);await O.mkdir(t,{recursive:!0});let r=D.join(t,D.basename(e));return n.isDirectory()?(await O.cp(e,r,{recursive:!0}),r):(await O.copyFile(e,r),r)}function ui(e){return e.device.platform===`web`}function di(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function fi(e){let{session:t,sessionName:n,sessionStore:r}=e;t.appLog&&await Re({session:t,sessionName:n,sessionStore:r,resourcePath:Ie.resolvePath(r.resolveSessionDir(n))})}async function pi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.perfCapture&&await Le({...e,session:t,intent:`disposal`})}async function mi(e,t){await t.stopSnapshotHelper(e.device)}async function hi(e){let{session:t,sessionName:n,sessionStore:r,platformCleanup:i}=e;await i.closeManagedBrowser({device:t.device,sessionName:n,stateDir:r.resolveDaemonStateDir(),openSessionNames:()=>di(r)})}async function gi(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function _i(t){if(t.failures.length===0)return;let n=t.failures.map(({step:e})=>e),r=t.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return _({level:`error`,phase:t.phase,data:{session:t.sessionName,failedSteps:n,errors:r}}),new e(`COMMAND_FAILED`,`Session cleanup left ${t.failures.length} resource(s) unreleased: ${r.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:t.sessionName,failedSteps:n,hint:`Some session resources failed to release; inspect the session log for per-resource diagnostics. The session was still deleted, so retrying is safe.`})}async function vi(t){let{session:n,sessionName:r,sessionStore:i}=t;if(!t.platformCleanup)throw new e(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let a=t.platformCleanup,o=[{step:`recording`,run:()=>yi({session:n,sessionName:r,sessionStore:i})},...t.appLog===`run`?[{step:`app_log`,run:()=>fi({session:n,sessionName:r,sessionStore:i})}]:[],{step:`audio_probe`,run:()=>bi({session:n,sessionName:r,sessionStore:i})},{step:`perf_capture`,run:()=>pi({session:n,sessionName:r,sessionStore:i})},{step:`platform_snapshot_helper`,run:()=>mi(n,a)},{step:`web_browser`,run:()=>hi({session:n,sessionName:r,sessionStore:i,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>si(r)});let s=_i({sessionName:r,phase:`session_teardown_cleanup_failed`,failures:await gi(o)});if(s)throw s}async function yi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.screenRecording&&await $e({intent:`disposal`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}async function bi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.audioProbe&&await Fe({intent:`disposal`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}function xi(e){return s(e)&&e.kind===`simulator`}function Si(e){return e.platform===`android`&&e.kind===`emulator`}const Ci=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function X(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Z(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function Q(e){return De(Z(e))}function $(t,n){if(t!==void 0){if(typeof t!=`string`)throw new e(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return v(t)}}function wi(t){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(t)}. Use an integer between 1 and 65535.`);return t}}function Ti(t){if(t!==void 0){if(typeof t!=`number`)throw new e(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return wi(t)}}function Ei(t,r,i){if(t===void 0)return i;if(!n(t))throw new e(`INVALID_ARGS`,`Invalid open runtime platform: ${String(t)}. Use "ios", "android", or "harmonyos".`);if(i&&t!==i)throw new e(`INVALID_ARGS`,`open runtime targets ${t}, but session "${r}" is bound to ${i}.`);return t}function Di(e){if(n(e))return e}function Oi(e,t){return{platform:t,metroHost:v(e?.metroHost),metroPort:wi(e?.metroPort),bundleUrl:v(e?.bundleUrl),launchUrl:v(e?.launchUrl)}}function ki(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Ai(e){if(Si(e))return`10.0.2.2`;if(xi(e))return`127.0.0.1`}function ji(e,t){if(!e||v(e.metroHost)||v(e.bundleUrl)||e.metroPort===void 0)return e;let n=Ai(t);return n?{...e,metroHost:n}:e}function Mi(t){let{runtime:n,sessionName:r,platform:i}=t;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new e(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!Ci.includes(e));if(o)throw new e(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Ci.join(`, `)}.`);return{platform:Ei(a.platform,r,i),metroHost:$(a.metroHost,`metroHost`),metroPort:Ti(a.metroPort),bundleUrl:$(a.bundleUrl,`bundleUrl`),launchUrl:$(a.launchUrl,`launchUrl`)}}function Ni(e,t,n){if(n){if(X(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Pi(t,n,r,i){let a=t.getRuntimeHints(n);if(!a)return;let o=r?l(r):void 0,s=Di(o)??i;if(a.platform&&r&&!s)throw new e(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new e(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Fi(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?Di(l(i)):e.platform,o=n.getRuntimeHints(r),s=Mi({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=Pi(n,r,i,a);return{runtime:i?ji(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&X(s)>0?s:void 0;return{runtime:i?ji(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Ii(e){return Fi(e).runtime}function Li(e){try{return{ok:!0,data:Fi(e)}}catch(e){let t=r(e);return Ee(t.code,t.message,t.details)}}async function Ri(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!zi(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:Z(t)})}function zi(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Q(e.previousRuntime)&&!Q(e.runtime)}function Bi(e){let{device:t,owner:n,stateDir:r,intent:i}=e,a=i.kind===`exact-owner`&&ne(i.owner,n)?te(i.fence):null;if(!a)return{status:`binding-invalid`};let o=C(w(t)),s=Me(ke(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!Hi(c.stateDir,r)||!ne(je(c),n)?{status:`conflict`,conflict:s}:c.allocator.identityIncarnationId===a.identityIncarnationId?{status:`covered`}:{status:`incarnation-stale`,heldIncarnationId:c.allocator.identityIncarnationId}}function Vi(e){let t=C(w(e));return Oe(ke(t))}function Hi(e,t){return D.resolve(e)===D.resolve(t)}const Ui=new Set([`DEVICE_CLAIM_LIVE_OWNER`,`DEVICE_CLAIM_RECOVERY_PENDING`,`DEVICE_CLAIM_OWNER_UNCERTAIN`]);function Wi(e){return Ui.has(e)}function Gi(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=l(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=o(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${le(i)}`,`${a} ${le(e.id)}`,...n===`release`||Ae(t.classification)?[`--stale`]:[]].join(` `)}function Ki(t,n){if(n.classification===`allocator-held`)return Ji(t,n);let r=n.claim,i=Gi(t,n,Ne(n.classification)?`release`:`status`),a=l(r?{platform:r.device.family,appleOs:r.device.appleOs}:t);return new e(`DEVICE_IN_USE`,r?`${a} device ${t.id} is owned by session "${r.session}" in workspace "${r.workspace}".`:`${t.name} has an ownership claim that could not be verified.`,{reason:ta(n.classification),classification:n.classification,deviceKey:n.deviceKey,...r?{owner:{session:r.session,workspace:r.workspace,stateDir:r.stateDir}}:{},recovery:{command:i},hint:Ne(n.classification)?`The recorded owner can no longer release this device; settle its resources and release the claim with: ${i}`:`Inspect the owner with: ${i}`,retriable:!1})}function qi(e,t){return ea(Ki(e,t))}function Ji(t,n){let r=n.allocatorClaim,i=l({platform:r.device.family,appleOs:r.device.appleOs}),a=Gi(t,n);return new e(`DEVICE_IN_USE`,`${i} device ${t.id} is held by managed-device allocator "${r.allocator.instanceId}" for installation "${r.stateDir}".`,{reason:`DEVICE_CLAIM_ALLOCATOR_HELD`,classification:n.classification,deviceKey:n.deviceKey,owner:{kind:`allocator`,stateDir:r.stateDir,allocator:r.allocator},recovery:{command:a},hint:`This device belongs to a managed pool and is released only after its allocator proves the identity removed; inspect with: ${a}`,retriable:!1})}function Yi(t,n){return new e(`COMMAND_FAILED`,`${l(t)} device ${t.id} is a managed identity with no allocator-held execution claim for this installation.`,{reason:`allocator-claim-missing`,owner:re(n),deviceKey:C(w(t)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function Xi(t,n,r){return new e(`COMMAND_FAILED`,`${l(t)} device ${t.id} is held for identity incarnation "${r}", which is not the incarnation this binding fences.`,{reason:`allocator-claim-incarnation-stale`,owner:re(n),deviceKey:C(w(t)),heldIncarnationId:r,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function Zi(t,n){return new e(`COMMAND_FAILED`,`A managed local owner executes only under an exact-owner binding that carries a managed binding fence.`,{reason:`runtime-contract-invalid`,owner:re(n),deviceKey:C(w(t)),retriable:!1})}function Qi(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:Zi(e,t)};case`missing`:return{admitted:!1,error:Yi(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:Xi(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:Ki(e,n.conflict)}}}function $i(e,t,n){let r=Qi(e,t,n);return r.admitted?void 0:ea(r.error)}function ea(e){let{hint:t,retriable:n,...r}=e.details??{};return Ee(e.code,e.message,r,{hint:t,retriable:n})}function ta(e){switch(e){case`live`:return`DEVICE_CLAIM_LIVE_OWNER`;case`owner-process-dead`:case`owner-daemon-superseded`:return`DEVICE_CLAIM_RECOVERY_PENDING`;case`owner-process-reused`:case`owner-state-dir-gone`:case`unknown`:case`inconsistent`:case`allocator-inconsistent`:return`DEVICE_CLAIM_OWNER_UNCERTAIN`}}function na(e){switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{rr as $,si as A,Ar as B,fi as C,ui as D,vi as E,Xr as F,Nr as G,Or as H,Zr as I,Er as J,Pr as K,Wr as L,$r as M,ti as N,di as O,Qr as P,ir as Q,Ur as R,_i as S,mi as T,jr as U,kr as V,Mr as W,ur as X,gr as Y,sr as Z,zi as _,Ki as a,Tt as at,bi as b,Bi as c,gt as ct,Q as d,bt as dt,F as et,Ri as f,yt as ft,Ni as g,Z as h,at as ht,Qi as i,Ct as it,ai as j,oi as k,Oi as l,_t as lt,Ii as m,ct as mt,$i as n,Ot as nt,Wi as o,Et as ot,ki as p,lt as pt,W as q,qi as r,wt as rt,Vi as s,vt as st,na as t,j as tt,X as u,ht as ut,Di as v,pi as w,yi as x,Li as y,Hr as z};
|
|
1
|
+
import{D as e,F as t,L as n,O as r,W as i,_ as a,b as o,c as s,k as c,m as l,o as u,u as d}from"./sdk-contracts.js";import"./capture.js";import{O as f,f as p,r as m,t as h}from"./sdk-batch-runner.js";import{a as g,n as _,t as v}from"./snapshot-diagnostics.js";import{f as y,p as b}from"./android-input-ownership.js";import{f as x,l as S,s as C,u as w,v as ee,x as te,y as T}from"./sdk-device.js";import{d as ne,l as E,n as re,r as ie}from"./lease-scope.js";import{Bn as ae,Dr as oe,Gr as se,Kn as ce,Kt as le,Pr as ue,Qt as de,Rn as fe,Rr as pe,T as me,Tr as he,Un as ge,Ur as _e,Vn as ve,Vr as D,Zt as ye,_n as be,ar as xe,gn as Se,hn as Ce,in as we,ir as Te,mn as Ee,pn as De,rr as Oe,wr as ke}from"./sdk-batch.js";import{i as Ae}from"./back-mode.js";import{u as je}from"./scroll-gesture.js";import{a as Me,b as Ne,f as Pe,g as Fe,n as Ie,p as Le,r as Re,w as ze,y as Be}from"./script.js";import{a as Ve}from"./session-store.js";import{L as He,S as Ue,T as We,b as Ge,w as Ke,x as qe}from"./session-snapshot.js";import{a as Je,c as Ye,i as Xe,l as Ze,n as Qe,o as $e,r as et,s as tt,t as nt,u as rt}from"./format.js";import{A as it,j as at}from"./parameterized-recorded-fill.js";import{E as ot,F as st,N as ct,O as lt,P as ut,j as dt,w as ft}from"./runtime.js";import{n as pt}from"./success-text.js";import{d as mt,i as ht,u as gt}from"./absence-observation-errors.js";import{a as _t}from"./device.js";import{o as vt,r as O}from"./diagnostics.js";import{p as yt}from"./exec.js";import{t as bt}from"./timeouts.js";import"./diagnostics2.js";import{n as xt,r as St}from"./output-path.js";import"./command.js";import{a as Ct,n as wt,t as Tt}from"./replay-divergence.js";import{s as Et}from"./device-shell.js";import{n as Dt}from"./retry.js";import{t as Ot}from"./session-paths.js";import{n as k}from"./runtime-transport-hints.js";import{r as kt}from"./rect-center.js";import{o as At}from"./android-system-chrome.js";import{_ as jt,a as Mt,c as Nt,d as A,f as Pt,g as Ft,h as It,i as Lt,l as Rt,m as zt,n as Bt,o as Vt,p as Ht,r as Ut,s as Wt,u as Gt,v as Kt}from"./human-control-contract.js";import{a as qt,c as Jt,i as Yt,n as Xt,o as Zt,r as j}from"./request-cancel.js";import{t as Qt}from"./request.js";import{n as $t,t as en,u as tn}from"./provider-session-ownership.js";import{r as nn}from"./application-lifecycle-runtime.js";import{a as rn,c as an,l as on,n as sn,o as cn,r as ln,t as un}from"./device-claim-inspection.js";import{b as dn,c as fn,g as pn,i as mn,p as hn,x as gn}from"./perf-runtime-plan.js";import{n as _n,r as vn,t as yn}from"./lease-context.js";import{d as bn,g as xn,u as Sn}from"./screenshot-runtime.js";import{n as Cn,r as wn}from"./device-isolation.js";import{n as Tn}from"./device-inventory-context.js";import{n as En}from"./dispatch-resolve.js";import{t as Dn}from"./touch-reference-frame.js";import{n as On}from"./screen-recording-admission-ledger.js";import{a as kn,c as An,d as M,l as jn,n as Mn,o as Nn,r as Pn,u as Fn}from"./src8.js";import{i as In,n as N,r as Ln,t as Rn}from"./compatibility-policy.js";import{o as zn}from"./quality-warnings.js";import{t as Bn}from"./png-worker-client.js";import{t as Vn}from"./semantic-index.js";import{o as Hn}from"./screen-recording-resource-recovery.js";import P from"node:path";import F,{promises as Un}from"node:fs";import Wn,{createHash as Gn}from"node:crypto";import Kn from"node:os";import I from"node:fs/promises";import{fileURLToPath as qn}from"node:url";import{setTimeout as Jn}from"node:timers/promises";import Yn from"node:vm";function Xn(e,t){return Zn(e,t)?t:`${e}:${t}`}function Zn(e,t){return t.startsWith(`${e}:`)}function Qn(e,t){return!e.partitioned||Zn(e.tenant,t)}var $n=class{active=new Map;waiters=new Map;async run(e,t){this.active.set(e,(this.active.get(e)??0)+1);try{return await t()}finally{let t=(this.active.get(e)??1)-1;if(t>0)this.active.set(e,t);else{this.active.delete(e);let t=this.waiters.get(e);this.waiters.delete(e);for(let e of t??[])e()}}}async wait(e,t){if(t?.throwIfAborted(),!this.active.has(e))return;let n=this.waiters.get(e)??new Set,r=()=>{},i=()=>{};try{await new Promise((a,o)=>{r=a,i=()=>o(t?.reason),n.add(r),this.waiters.set(e,n),t?.addEventListener(`abort`,i,{once:!0})})}finally{t?.removeEventListener(`abort`,i),n.delete(r),n.size===0&&this.waiters.get(e)===n&&this.waiters.delete(e)}}},er=class{entriesByLeaseId=new Map;retain(e,t){let n={wanted:t,released:!1},r=this.entriesByLeaseId.get(e)??new Set;return r.add(n),this.entriesByLeaseId.set(e,r),{leaseId:e,release:()=>this.releasePass(e,r,n)}}forget(e){let t=this.entriesByLeaseId.get(e);if(t){for(let e of t)e.released=!0;this.entriesByLeaseId.delete(e)}}isDeferred(e){let t=this.entriesByLeaseId.get(e);if(!t)return!1;for(let e of t)e.wanted()||t.delete(e);return t.size>0||(this.entriesByLeaseId.delete(e),!1)}releasePass(e,t,n){return!n.released&&(n.released=!0,t.delete(n),t.size===0&&this.entriesByLeaseId.delete(e),n.wanted())}},tr=class{holdsByDevice=new Map;mutations=new $n;inFlightWork=new er;leases=new Map;runBindings=new Map;deviceBindings=new Map;maxActiveSimulatorLeases;resolveLeaseTtlMs;now;onLeaseExpired;providerSessionOwnership;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.resolveLeaseTtlMs=Rt(e),this.now=e.now??(()=>Date.now()),this.onLeaseExpired=e.onLeaseExpired,this.providerSessionOwnership=new en({now:this.now,retentionMs:e.providerSessionRetentionMs})}allocateLease(e){let t=Ht(e);this.cleanupExpiredLeases();let n=this.resolveLeaseTtlMs(t.ttlMs);this.assertHumanControlAdmission(t);let r=this.refreshExistingRunBinding(t,n);if(r)return r;this.assertDeviceAvailable(t),this.enforceCapacity(t.backend);let i=Nt(t,n,this.now());return this.leases.set(i.leaseId,i),this.bindLease(i),{...i}}refreshExistingRunBinding(e,t){let n=Pt(e),r=this.runBindings.get(n);if(!r)return;let i=this.leases.get(r);if(!i){this.runBindings.delete(n);return}if(i.clientId===e.clientId)return this.refreshLease(i,t);if(i.deviceKey)throw Gt(i);return Wt(i,e),this.refreshLease(i,t)}heartbeatLease(e){let t=Ft(e.leaseId);this.cleanupExpiredLeases();let n=this.getActiveLease(t);Vt(n,e),Wt(n,e);let r=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(n,r)}retainLeaseWork(e,t){let n=this.inFlightWork.retain(e.leaseId,t);return{leaseId:n.leaseId,release:()=>{let t=n.release();return t&&this.refreshProtectedLease(e.leaseId,this.now()),t}}}releaseLease(e){let t=this.getLease(e);return t?(this.leases.delete(t.leaseId),this.unbindLease(t),this.inFlightWork.forget(t.leaseId),{released:!0,lease:t}):{released:!1}}getLease(e){let t=Ft(e.leaseId);this.cleanupExpiredLeases();let n=this.leases.get(t);if(n)return Vt(n,e),Wt(n,e),{...n}}assertLeaseAdmission(e){let t=zt(e);this.cleanupExpiredLeases(),Wt(this.getActiveLease(t.leaseId),t)}listActiveLeases(){return this.cleanupExpiredLeases(),Array.from(this.leases.values()).map(e=>({...e}))}recordProviderSession(e,t){this.cleanupExpiredLeases();let n=e.expiresAt<=this.now()?e.expiresAt:void 0;this.providerSessionOwnership.record(e,t),this.leases.has(e.leaseId)||this.providerSessionOwnership.markLeaseReleased(e,n)}resolveProviderSession(e){return this.cleanupExpiredLeases(),this.providerSessionOwnership.resolve(e)}listHumanControlHolds(e){this.cleanupExpiredLeases();let t=e.kind===`lease`?A(this.requireHumanControlLease(e.leaseId)):void 0;return[...this.holdsByDevice.entries()].filter(([e])=>t===void 0||t===e).flatMap(([,e])=>[...e.values()].map(({hold:e})=>Bt(e))).sort((e,t)=>e.id.localeCompare(t.id))}async putHumanControlHold(t,n,r,i){i?.throwIfAborted();let a=Lt(n),o=Mt(r);this.cleanupExpiredLeases();let s=this.resolveHumanControlScope(t,o),c=A(s),l=this.findHumanControlHold(a);if(l&&(this.assertHoldAuthority(t,l),A(l.hold.scope)!==c))throw new e(`INVALID_ARGS`,`Release a hold before changing its device scope.`);let u=this.now(),d={...t.kind===`lease`?{ownerLeaseId:t.leaseId}:{},hold:{id:a,scope:s,state:`activating`,...o.reason?{reason:o.reason}:{},createdAt:l?.hold.createdAt??u,updatedAt:u}},f=this.holdsByDevice.get(c)??new Map;return this.holdsByDevice.set(c,f),f.set(a,d),await this.activateHumanControlHold(c,d,o.ttlMs,i)}async activateHumanControlHold(t,n,r,i){let a=this.holdsByDevice.get(t),{id:o}=n.hold;try{if(await this.mutations.wait(t,i),i?.throwIfAborted(),a.get(o)!==n)throw new e(`COMMAND_FAILED`,`Human-control hold changed before activation completed.`,{holdId:o});let s=this.now();return n.hold={...n.hold,state:`active`,updatedAt:s,...r===void 0?{}:{expiresAt:s+r}},this.refreshHeldLease(t,s),Bt(n.hold)}catch(e){throw a.get(o)===n&&this.deleteHumanControlHold(t,o),e}}removeHumanControlHold(e,t){let n=Lt(t);this.cleanupExpiredLeases();let r=this.findHumanControlHold(n);if(!r)return;this.assertHoldAuthority(e,r);let i=A(r.hold.scope);return this.deleteHumanControlHold(i,n),Bt(r.hold)}deleteHumanControlHold(e,t){let n=this.holdsByDevice.get(e);n.delete(t),n.size===0&&(this.holdsByDevice.delete(e),this.refreshHeldLease(e,this.now()))}assertHumanControlAdmission(e){this.expireHumanControlHolds();let t=A(e),n=t===void 0?void 0:this.holdsByDevice.get(t)?.values().next().value;if(n)throw Ut(n.hold)}async runDeviceMutation(e,t){if(!e)return await t();this.cleanupExpiredLeases();let n=this.getActiveLease(e.leaseId);this.assertHumanControlAdmission(n);let r=A(n);return r===void 0?await t():await this.mutations.run(r,t)}requireHumanControlLease(t){let n=this.getActiveLease(t);if(!n.deviceKey)throw new e(`UNSUPPORTED_OPERATION`,`Human control requires a device-scoped remote lease.`);return{...n,deviceKey:n.deviceKey}}resolveHumanControlScope(t,n){if(t.kind===`host`){if(!n.scope)throw new e(`INVALID_ARGS`,`Host human control requires a lease device scope.`);return n.scope}if(n.scope)throw new e(`INVALID_ARGS`,`Lease-owner human control uses the admitted lease device; do not supply scope.`);let r=this.requireHumanControlLease(t.leaseId);return{backend:r.backend,leaseProvider:r.leaseProvider,deviceKey:r.deviceKey}}assertHoldAuthority(t,n){if(t.kind===`host`)return;let r=this.requireHumanControlLease(t.leaseId);if(n.ownerLeaseId!==r.leaseId||A(r)!==A(n.hold.scope))throw new e(`UNAUTHORIZED`,`Human-control hold does not belong to the admitted lease.`,{reason:`LEASE_SCOPE_MISMATCH`})}findHumanControlHold(e){for(let t of this.holdsByDevice.values()){let n=t.get(e);if(n)return n}}hasHumanControl(e){let t=A(e);return t!==void 0&&this.holdsByDevice.has(t)}isLeaseProtected(e,t){return e.expiresAt>t||this.hasHumanControl(e)||this.inFlightWork.isDeferred(e.leaseId)}expireHumanControlHolds(){let e=this.now();for(let[t,n]of this.holdsByDevice){let r=0;for(let[t,{hold:i}]of n)i.expiresAt===void 0||i.expiresAt>e||(r=Math.max(r,i.expiresAt),n.delete(t));n.size===0&&(this.holdsByDevice.delete(t),this.refreshHeldLease(t,r))}}refreshHeldLease(e,t){this.refreshProtectedLease(this.deviceBindings.get(e),t)}refreshProtectedLease(e,t){let n=e?this.leases.get(e):void 0;n&&this.refreshLease(n,n.expiresAt-n.heartbeatAt,Math.max(t,n.heartbeatAt))}consumeExpiredLeases(){this.expireHumanControlHolds();let e=this.now(),t=[];for(let n of this.leases.values()){if(this.isLeaseProtected(n,e))continue;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};t.push(r),this.onLeaseExpired?.(r)}return t}consumeExpiredLease(e){this.expireHumanControlHolds();let t=It(e);if(!t)return;let n=this.leases.get(t);if(!n||this.isLeaseProtected(n,this.now()))return;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};return this.onLeaseExpired?.(r),r}cleanupExpiredLeases(){this.consumeExpiredLeases()}enforceCapacity(t){if(t!==`ios-simulator`||this.maxActiveSimulatorLeases<=0)return;let n=Array.from(this.leases.values()).filter(e=>e.backend===`ios-simulator`).length;if(!(n<this.maxActiveSimulatorLeases))throw new e(`DEVICE_IN_USE`,`No simulator lease capacity available`,{reason:`LEASE_CAPACITY_EXCEEDED`,activeLeases:n,maxActiveLeases:this.maxActiveSimulatorLeases,backend:t,hint:`Retry after releasing another simulator lease.`})}getActiveLease(t){let n=this.leases.get(t);if(n)return n;throw new e(`UNAUTHORIZED`,`Lease is not active`,{reason:`LEASE_NOT_FOUND`})}refreshLease(e,t,n=this.now()){let r={...e,heartbeatAt:n,expiresAt:n+t};return this.leases.set(r.leaseId,r),this.bindLease(r),{...r}}bindLease(e){this.runBindings.set(Pt(e),e.leaseId);let t=A(e);t&&this.deviceBindings.set(t,e.leaseId)}unbindLease(e,t=this.now()){this.runBindings.delete(Pt(e));let n=A(e);n&&this.deviceBindings.delete(n),this.providerSessionOwnership.markLeaseReleased(e,t)}assertDeviceAvailable(e){let t=A({backend:e.backend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey});if(!t)return;let n=this.deviceBindings.get(t);if(!n)return;let r=this.leases.get(n);if(!r){this.deviceBindings.delete(t);return}throw Gt(r)}};function nr(t){let n=Kt(t.meta?.sessionIsolation??t.flags?.sessionIsolation),r=t.meta?.tenantId??t.flags?.tenant,i=jt(r);if(r&&!i)throw new e(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(n!==`tenant`)return t;if(!i)throw new e(`INVALID_ARGS`,`session isolation mode tenant requires --tenant (or meta.tenantId).`);let a=t.session||`default`;return Zn(i,a)?{...t,meta:{...t.meta,tenantId:i,sessionIsolation:n}}:{...t,session:Xn(i,a),meta:{...t.meta,tenantId:i,sessionIsolation:n}}}function rr(t,n,r,i={}){if(bn(t.command))return;let a=_n(t);or(t,a);let o=r?.lease;if(r===void 0&&!a.leaseId&&ir(t,i.providerAppCatalog))return;if(t.command===`human_control`&&!o&&!a.leaseId)throw new e(`UNSUPPORTED_OPERATION`,`Takeover requires an active remote device lease. Local takeover is not supported.`);if(t.command!==`human_control`&&!o&&t.meta?.sessionIsolation!==`tenant`&&(!a.leaseId||!a.tenantId&&!a.runId))return;sr(a,o);let s=vn(t,r),c={...s,leaseTtlMs:s.leaseTtlMs??(ie(s)?3e5:void 0)};n.assertLeaseAdmission(E(s));let l=n.heartbeatLease(E(c));return Sn(t)&&n.assertHumanControlAdmission(l),l}function ir(e,t){let n=xn(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function ar(e){bn(e.command)||or(e,_n(e))}function or(t,n){if(t.command!==`open`)return;let r=re(n);if(r.length!==0)throw new e(`INVALID_ARGS`,`Proxy open requires leaseId, tenantId, runId, clientId, and deviceKey lease metadata.`,{missing:r})}function sr(e,t){t&&(L(`leaseId`,e.leaseId,t.leaseId),L(`tenantId`,e.tenantId,t.tenantId),L(`runId`,e.runId,t.runId),L(`leaseProvider`,e.leaseProvider,t.leaseProvider),L(`clientId`,e.clientId,t.clientId),L(`deviceKey`,e.deviceKey,t.deviceKey))}function L(t,n,r){if(!(!n||!r||n===r))throw new e(`UNAUTHORIZED`,`Lease does not match session owner (${t})`,{reason:`LEASE_SESSION_MISMATCH`,field:t})}async function cr(e,t){if(!t.leaseProvider||!e)return!1;try{return await e(t),O({level:`info`,phase:`provider_lease_expired_released`,data:{leaseId:t.leaseId,provider:t.leaseProvider}}),!0}catch(e){return O({level:`error`,phase:`provider_lease_expiry_release_failed`,data:{leaseId:t.leaseId,provider:t.leaseProvider,error:e instanceof Error?e.message:String(e)}}),!1}}function lr(e){ar(e)}async function ur(e){let t=e.sessionStore.get(e.sessionName),n=t?.lease;return!t||!n||!e.leaseRegistry.consumeExpiredLease(n.leaseId)?!1:(O({level:`info`,phase:`leased_session_expired`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,deviceKey:n.deviceKey}}),await e.teardownSession(t,t.name).catch(e=>{O({level:`debug`,phase:`leased_session_expiry_cleanup_failed`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,error:e instanceof Error?e.message:String(e)}})}),await dn(t.deviceClaim).catch(e=>{O({level:`warn`,phase:`leased_session_expiry_device_claim_clear_failed`,data:{session:t.name,deviceKey:t.deviceClaim?.deviceKey,error:e instanceof Error?e.message:String(e)}})}),e.sessionStore.delete(t.name),!0)}function dr(e){let{sessionName:t,sessionStore:n,leaseRegistry:r}=e,i=n.get(t),a=rr(e.req,r,i,{providerAppCatalog:e.providerAppCatalog});if(!a)return e.req;let o={...e.req,internal:{...e.req.internal,admittedLease:a}};return i?.lease&&n.set(t,{...i,lease:{...i.lease,leaseBackend:a.backend,expiresAt:a.expiresAt}}),o}function fr(e){return yn(e.req,e.req.internal?.admittedLease)??e.existingLease}async function pr(e){let t=e.session.lease;if(!t)return;let n=ne({leaseId:t.leaseId,tenantId:t.tenantId,runId:t.runId,leaseBackend:t.leaseBackend,leaseProvider:t.leaseProvider,deviceKey:t.deviceKey,clientId:t.clientId}),r=e.leaseRegistry.getLease(n),i=r?await e.leaseLifecycleProvider?.release?.(r):void 0,a=$t(i);r&&a&&e.leaseRegistry.recordProviderSession(r,a);let o=e.leaseRegistry.releaseLease(n);return O({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:o.released}}),i}const mr=[`platform`,`target`],hr=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function gr(e){return C({deviceName:e?.device,udid:e?.udid,serial:e?.serial})}function _r(e){return gr(e)||br(e,mr)}function vr(e){return _r(e)||br(e,hr)}function yr(e){return typeof e==`string`&&e.trim().length>0}function br(e,t){return e?t.some(t=>yr(e[t])):!1}function xr(e){return{appleSimulatorAppTarget:Sr(e)}}function Sr(e){return e&&!m(e)?e:void 0}function Cr(){return On({displayName:`audio probe`})}function wr(){return On({displayName:`perf capture`})}function Tr(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return Gn(`sha256`).update(Oe(t),`utf8`).digest(`hex`)}function Er(e,t,n){return new Fr(Or(Dr(t.resolve(e))),n).parse()}function Dr(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Or(t){let n=[],r=0;for(;r<t.length;){let i=t.slice(r),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){r+=a;continue}let o=kr(i);if(!o)throw new e(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);n.push(o.value),r+=o.length}return n}function kr(e){return Ar(e)??jr(e)??Mr(e)??Nr(e)??Pr(e)}function Ar(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function jr(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Mr(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Nr(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function Pr(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var Fr=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let t=this.parseOr();if(this.peek())throw new e(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return t}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let t=this.peek();if(!t)throw new e(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(t.type===`boolean`)return this.index+=1,t.value;if(t.type===`paren`&&t.value===`(`){this.index+=1;let t=this.parseOr();if(!this.consumeParen(`)`))throw new e(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return t}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new e(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let t=this.peek();if(t?.type!==`operator`||t.value!==`==`&&t.value!==`!=`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,t}consumeStringLiteral(){let t=this.peek();if(t?.type!==`string`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,t.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function Ir(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Lr(e,t){return{...Kr(e,t),source:e.source}}function R(t,n,r){if(t===void 0)return;let i=r??kn[n]??{},a=Nn(i),o;if(typeof t==`number`)o=t;else{let r=t.trim();if(r===``)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);o=Number(r)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);return o}function Rr(e,t,n,r){return R(e===void 0?t:n.resolve(String(e)),r)}function z(e){if(e?.aborted)throw c()}async function zr(t,n){if(t.include.kind===`commands`)return{kind:`program`,source:t.source,config:{},commands:t.include.commands};if(!n.loadProgram)throw new e(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return z(n.signal),n.signal?await n.loadProgram(t.include.path,t.source.path,n.signal):await n.loadProgram(t.include.path,t.source.path)}function Br(e,t){if(e.include.kind===`file`)return P.resolve(t?P.dirname(t):process.cwd(),e.include.path)}function Vr(e){return e===void 0?void 0:P.resolve(e)}function Hr(t,n){let r=Br(t,t.source.path);if(r&&n.has(r))throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function Ur(t,n,r,i){let a=t.include.kind===`file`?Vr(n.source.path):void 0,o=new Set([r,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function Wr(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:Er(e.true,t,n.platform)}function Gr(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function Kr(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>Kr(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Kr(n,t)])):e}async function qr(e,t){z(t.signal);let n=Vr(e.source.path),r={options:t,context:An(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await Jr(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function Jr(e,t,n,r,i){z(i.options.signal);let a=ai(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await Xr(s,a,o,e.source.path??r,i));return n}finally{s()}}async function Yr(e,t,n,r,i){let a=[];for(let o of e)a.push(...await Xr(o,t,n,r,i));return a}async function Xr(e,t,n,r,i){z(i.options.signal);let a=oi(e,r);switch(a.kind){case`runFlow`:{let e=Qr(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await Zr(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[ri(a,t,n,o)]}case`repeat`:return[ri(a,t,n,await Yr(a.commands,t,n,r,i))];case`retry`:return[ri(a,t,n,await Yr(a.commands,t,n,r,i))];default:return[ni(a,t,n)]}}async function Zr(e,t,n,r,i){let a=ei(e,i.context),o=Hr(a,i.activeIncludePaths),s=await zr(a,i.options);z(i.options.signal);let c=Ur(a,s,o,i.activeIncludePaths),l=ai(t,e.env),u=i.context.enter(e.env);try{return await Jr(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function Qr(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:$r(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function $r(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return ti(t.context.resolveDeferred(e))?`opaque`:Er(e,t.context,t.options.platform)?void 0:`omit`}function ei(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function ti(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function ni(e,t,n){return M({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function ri(e,t,n,r){return M({kind:`opaque`,command:ii(e),source:e.source,scopes:t,body:r,appId:n})}function ii(e){switch(e.kind){case`runFlow`:return M({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return{kind:e.kind,source:e.source,times:e.times};case`retry`:return M({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function ai(e,t){return t===void 0?e:[...e,t]}function oi(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function si(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await qr(e,t),a=ci(t.runtimeHints),o=M({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=Tr(o);return li({...o,digest:s})}function ci(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function li(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))li(t);return Object.freeze(e)}function ui(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`||n.command.kind===`evalScript`)return{allowed:!1,reason:`step ${t+1} (${n.command.kind}) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function di(t,n={}){let r=ui(t,n);if(!r.allowed)throw new e(`INVALID_ARGS`,r.reason);return r.startIndex}function fi(t,n){if(!Number.isInteger(n)||n<0||n>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${n} is out of range for a ${t.total}-step plan.`);return n}const pi=`maestro-test-failure`;function mi(t,n={}){return new e(`COMMAND_FAILED`,t,{...n,reason:pi})}function hi(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&t.details?.reason===pi}const gi=new Set([``,`false`,`0`,`null`,`undefined`]);function _i(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!gi.has(e)}async function vi(e,t){z(t.options.signal);try{return await Ni(e,t.context,async()=>await yi(e,t))}catch(t){throw Pi(t,e)}}async function yi(e,t){if(e.kind===`command`)return await bi(e.command,e.appId,t);await Ei(e,t)}async function bi(e,t,n){if(e.kind===`evalScript`)return await Ci(e,n);let r=Lr(e,n.context);try{return await wi(r,t,n)}catch(e){if(z(n.options.signal),Si(r)&&hi(e)){n.warnings.push(xi(r,e)),n.skipped+=1;return}throw Fi(e,r)}}function xi(t,n){let r=`${t.source.path?`${t.source.path}:`:``}line ${t.source.line}`,i=n instanceof e?n.message:String(n);return`Optional Maestro ${t.kind} skipped at ${r}: ${i}`}function Si(e){return`optional`in e&&e.optional===!0}async function Ci(t,n){let{evaluateMaestroEvalScript:r}=await import(`./engine-eval-script.js`);if(n.options.trustedScripts===!1)throw new e(`UNAUTHORIZED`,`Maestro evalScript is not permitted for flows received over the remote daemon surface: node:vm is not a security sandbox, so an untrusted expression can escape to the host.`);let i=await r(t.script,n.context.values);n.context.replaceOutput(i),n.executed+=1}async function wi(e,t,n){switch(e.kind){case`assertVisible`:await Ai({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await Ai({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!_i(e.condition))throw mi(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await Ai(Mi(e),R(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await Ti(e,t,n)}}async function Ti(e,t,n){let r=M({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return z(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function Ei(e,t){let n=Lr(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await ki(n.when,t)){t.skipped+=1;return}t.executed+=1,await Di(e.body,t);return;case`repeat`:{let r=Rr(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)z(t.options.signal),await Di(e.body,t);return}case`retry`:{let r=Math.min(Rr(n.maxRetries,1,t.context,`retry.maxRetries`),N.control.retryMaxRetries);t.executed+=1,await Oi(e.body,r,t);return}}}async function Di(e,t){for(let n of e)await vi(n,t)}async function Oi(t,n,r){let i;for(let e=0;e<=n;e+=1){z(r.options.signal);try{await Di(t,r);return}catch(e){if(z(r.options.signal),!hi(Li(e)))throw e;i=Pi(e,t[0])}}throw i||new e(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function ki(e,t){if(!Wr(e,t.context,t.options))return!1;for(let n of Gr(e))if(z(t.options.signal),!(await ji(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function Ai(e,t,n){if(!(await ji(e,t,n)).matched)throw mi(`Maestro ${e.kind} condition did not match.`)}async function ji(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return z(n.options.signal),n.context.recordObservation(i),i}function Mi(t){if(t.visible)return{kind:`visible`,selector:t.visible};if(t.notVisible)return{kind:`notVisible`,selector:t.notVisible};throw new e(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function Ni(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function Pi(e,t){if(Ii(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Ri(e,t?.command),source:n,...t?{command:t.command}:{}}}function Fi(e,t){return{kind:`maestroPlanStepFailure`,error:Ri(e,t),source:t.source,command:t}}function Ii(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Li(e){return Ii(e)?e.error:e}function Ri(t,n){if(!(t instanceof e)||!n||/\bline \d+\b/.test(t.message))return t;let r=n.source.path?`${n.source.path}:`:``;return new e(t.code,`${t.message} (${r}line ${n.source.line})`,t.details)}async function zi(t,n,r={}){z(r.signal);let i=r.startIndex??0;if(!Number.isInteger(i)||i<0||i>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${t.total}-step plan.`);let a={plan:t,port:n,options:r,context:An(r.defaults,r.env?{...r.env}:{}),timing:Rn,artifacts:new Set,warnings:[],executed:t.compatibility.staticallyExecutedControls,skipped:t.compatibility.staticallySkippedControls};for(let e=i;e<t.steps.length;e+=1)try{await Bi(t.steps[e],e,a)}catch(e){throw Li(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Bi(e,t,n){z(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};Hi(()=>n.options.observer?.commandStarted?.(s));try{let t=await vi(e,n);z(n.options.signal),Hi(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Vi(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=Pi(t,e);throw Hi(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Vi(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts],warnings:[...n.warnings]})),o}}function Vi(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries,settleLatches:t.settleLatches-e.settleLatches,settleTimeouts:t.settleTimeouts-e.settleTimeouts}}}function Hi(e){try{e?.()}catch{}}async function Ui(e,t,n={}){let r=Wi(e,n);return await zi(e,t,{...n,startIndex:r})}function Wi(e,t){return t.from!==void 0||t.planDigest!==void 0?di(e,{from:t.from,planDigest:t.planDigest}):fi(e,t.startIndex??0)}function Gi(e){return Ir(e)?{command:e.kind,...e.kind===`runFlow`?B(e.label??e.includePath):{}}:{command:e.kind,...Ki(e)}}function Ki(e){return`label`in e&&e.label?B(e.label):qi(e)?B(ea(e.target)):Ji(e)?Yi(e):e.kind===`inputText`?B(`<text>`):Xi(e)}function qi(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function Ji(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Yi(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return B(ta(e.target));case`extendedWaitUntil`:return B(ta(e.visible??e.notVisible));case`scrollUntilVisible`:return B(ta(e.element))}}function Xi(e){return Zi(e)?Qi(e):e.kind===`swipe`?$i(e):e.kind===`runFlow`?B(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?B(String(e.condition)):{}}function Zi(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function Qi(e){switch(e.kind){case`openLink`:return B(e.link);case`takeScreenshot`:return B(e.path);case`runScript`:return B(e.file);case`pressKey`:return B(e.key)}}function $i(e){return B(e.gesture.kind===`coordinates`?`${na(e.gesture.start)} to ${na(e.gesture.end)}`:e.gesture.direction)}function ea(e){return e.space===`target`?ta(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function ta(e){return e?.id??e?.text}function na(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function B(e){return e?{value:e}:{}}const ra=new Set(String.raw`^$\.*+?()[]{}|`);function ia(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function aa(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if(ra.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!ra.has(i))return;t+=i,n+=1}return t}function oa(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(D(e.rect))return t.isVisibleInEffectiveViewport(e);if(e.rect)return!1;if(n!==`android`&&e.hittable===!0)return!0;let r=t.findAncestor(e,e=>oe(e,n)?e:null);return r?D(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function sa(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function ca(e,t){let n=[t.id===void 0?void 0:ua(e.identifier,t.id),t.text===void 0?void 0:da(e,t.text)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function la(e){return e.matches.filter(t=>oa(t,e.visibility,e.platform))}function ua(e,t){let n=e??``;return Fn(n)===Fn(t)||ia(n,t)}function da(e,t){return[e.label,jn(e),e.identifier].filter(e=>!!e).some(e=>ua(e,t))}function fa(e){return e.index!==void 0||e.childOf!==void 0||e.below!==void 0||e.above!==void 0||e.leftOf!==void 0||e.rightOf!==void 0||e.containsChild!==void 0||e.containsDescendants!==void 0}function pa(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function ma(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=ga(a.rect,e.rect);n===void 0||!ha(t,a.rect,e.rect)||r.push({node:a,distance:n,order:i++})}return r.sort((e,t)=>e.distance-t.distance||e.order-t.order),r.map(({node:e})=>e)}function ha(e,t,n){switch(e){case`below`:return t.y>n.y;case`above`:return t.y<n.y;case`leftOf`:return t.x<n.x;case`rightOf`:return t.x>n.x}}function ga(e,t){if(!(!_a(e)||!_a(t)))return Math.fround(Math.hypot(va(e.x,e.width)-va(t.x,t.width),va(e.y,e.height)-va(t.y,t.height)))}function _a(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function va(e,t){return e+Math.trunc(t/2)}function ya(t,n={},r={}){let i=ke(t.nodes,n);n.onVisibilityContextCreated?.();let a=new WeakMap,o=new WeakSet,s=new WeakMap,c=new Map,l=e=>e.parentIndex===void 0?void 0:i.nodeByIndex.get(e.parentIndex)??t.nodes[e.parentIndex],u=e=>{let t=s.get(e);if(t)return t;let n=new Set,r=new Set,i=l(e);for(;i&&!r.has(i.index);)r.add(i.index),n.add(i.index),i=l(i);return s.set(e,n),n},d=(e,r)=>{let i=c.get(e);i||(i=new WeakMap,c.set(e,i));let a=i.get(r);if(a)return a;n.onPositionComputed?.(e,r);let o=ma(t.nodes,e,m(r).indexed),s={ordered:o,candidateIndexes:new Set(o.map(e=>e.index))};return i.set(r,s),s},f=(e,t)=>d(e,t).ordered,p=(e,t)=>d(e,t).candidateIndexes,m=i=>{let s=a.get(i);if(s)return s;if(o.has(i))throw new e(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),n.onSelectorComputed?.(i);try{let e=ba(t,i,l,u,m,p),n={matches:e,indexed:wa(e,i.index,r.orderUnindexed)};return a.set(i,n),n}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function ba(e,t,n,r,i,a){let{index:o,childOf:s,below:c,above:l,leftOf:u,rightOf:d,containsChild:f,containsDescendants:p,...m}=t,h=pa(m)?e.nodes.filter(e=>ca(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>Sa(r(t),e))}if(f){let e=new Set(i(f).indexed.map(n).filter(e=>e!==void 0).map(e=>e.index));h=h.filter(t=>e.has(t.index))}if(p){let e=p.map(e=>xa(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of Ca(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function xa(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function Sa(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Ca(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function wa(e,t,n){if(t===void 0)return n?n(e):[...e];let r=Ea(e)[Oa(t)];return r?[r]:[]}function Ta(e,t){return t===void 0?e[0]:Ea(e)[Oa(t)]}function Ea(e){return[...e].sort((e,t)=>{let n=Da(e.rect?.y),r=Da(t.rect?.y);return n===r?Da(e.rect?.x)-Da(t.rect?.x):n-r})}function Da(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function Oa(t){let n=typeof t==`number`?t:Number(t.trim());if(!Number.isSafeInteger(n)||n<0)throw new e(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return n}const ka={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Aa(e,t){let n=ka[t];if(n.kind===`divergence`)return n;let r=b(e);return r?r.kind!==`exact`||r.provider!==n.provider?{kind:`divergence`,provider:n.provider,reason:`unregistered-provider-evidence`}:r:{kind:`divergence`,provider:n.provider,reason:`exact-evidence-not-retained`}}function ja(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Ma(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Ma(e){return e===!0?2:+(e===!1)}function Na(e,t,n,r={}){let i=Aa(e,n),a=Fa(e,i,r),o=Pa(t,a),s=la({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:Ia(s,t,n,a.visibility,i)}}function Pa(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Fa(e,t,n={}){return ya(e,n,t?{orderUnindexed:e=>ja(e,t)}:{})}function Ia(e,t,n,r,i){let a=n!==`ios`||!Va(t)?e:e.filter(n=>{if(Ga(n))return!0;let i=e.filter(e=>e!==n&&Ha(n,e,t));return!i.some(e=>Ga(e)&&sa(n,e,r))&&!i.some(e=>sa(e,n,r))});return t.index===void 0&&i?ja(a,i):a}function La(e,t){let n=t===void 0?e.find(Ba):Ra(e,t);return!n||!Ba(n)?null:{node:n,rect:n.rect}}function Ra(e,t){return Ta(e,t)}function za(e){return Ba(e)?e.rect:void 0}function Ba(e){return D(e.rect)}function Va(e){return e.id!==void 0||e.text!==void 0}function Ha(e,t,n){if(n.id!==void 0&&Wa(e.identifier)!==Wa(t.identifier))return!1;if(n.text!==void 0){let n=Ua(e),r=new Set(Ua(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Ua(e){return[e.label,e.value,e.identifier].map(Wa).filter(e=>e!==void 0)}function Wa(e){if(e)return Fn(e)||void 0}function Ga(e){let t=ue(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const Ka=Symbol(`maestroFlowProgram`),qa=Symbol(`maestroFailureCommand`),Ja=Symbol(`maestroFailurePlan`);function Ya(e,t){let n=Pn(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:eo(n),[Ka]:n}}async function Xa(e,t,n){let r;try{let i=Mn(P.dirname(e.sourcePath),n.readSource),a=await si(e[Ka],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=di(a,{from:n.from,planDigest:n.planDigest}),s=await Ui(a,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:i,signal:n.signal,startIndex:o,trustedScripts:n.trustedScripts,observer:Qa(a,n.observer,e=>{r=e})});return{ok:!0,replayed:a.total-o,planDigest:a.digest,startIndex:o,artifactPaths:s.artifactPaths,...s.warnings?{warnings:s.warnings}:{}}}catch(e){return{ok:!1,error:r?.error??e,...r?{failure:r}:{}}}}function Za(e,t){let n=no(e[qa]),r=e[Ja].platform;return!n||r!==`android`&&r!==`ios`?[]:Na(t,n.selector,r).ranked.map(e=>({node:e,basis:ro(n.selector,e)}))}function Qa(e,t,n){return{commandStarted:e=>t?.actionStarted?.($a(e)),commandCompleted:e=>t?.actionCompleted?.({...$a(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=ui(e,{from:r.stepIndex,planDigest:e.digest}),a={...$a(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,warnings:[...r.warnings],isControl:Ir(r.command),redactions:r.command.kind===`inputText`&&r.command.text.length>0?[{name:`inputText.text`,value:r.command.text}]:[],resume:i.allowed?{allowed:!0,from:r.stepIndex,planDigest:e.digest}:{allowed:!1,from:r.stepIndex,planDigest:e.digest,reason:i.reason},[qa]:r.command,[Ja]:e};n(a),t?.actionFailed?.(a)}}}function $a(e){let t=Gi(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function eo(e){return[e.config.appId,...[...e.config.onFlowStart??[],...e.commands].filter(e=>e.kind===`launchApp`).map(e=>e.kind===`launchApp`?e.appId:void 0)].find(to)}function to(e){return!!(e?.trim()&&!e.includes(`$`)&&!m(e))}function no(e){switch(e.kind){case`tapOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`doubleTapOn`:case`longPressOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element};case`swipe`:return e.gesture.kind===`target`?{selector:e.gesture.from}:void 0;default:return}}function ro(e,t){return e.id!==void 0||e.text!==void 0&&ca({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}function V(e,t){return M({appId:e.appId,env:e.env,generation:e.generation,invalidateObservation:e.invalidateObservation,source:t?.source,cachedObservation:e.cachedObservation,signal:e.signal})}function io(e){return M({env:e.env,generation:e.generation,cachedObservation:e.cachedObservation,signal:e.signal})}async function ao(e,t){let n=uo(await t.observe({condition:e.condition,timeoutMs:e.timeoutMs},io(e)),e.generation),r={kind:`selector`,selector:e.condition.selector,visible:n.visible,candidateCount:n.candidateCount,...n.ref?{ref:n.ref}:{}};return{generation:e.generation,matched:oo(e.condition,n),candidateCount:n.candidateCount,evidence:r}}function oo(e,t){return e.kind===`visible`?t.matched&&t.visible:!t.matched||!t.visible}async function so(e,t,n,r){let i=uo(await r.resolveTarget({selector:e,...t},V(n,n.command)),n.generation);if(!i.matched||!i.visible||!i.rect)throw mi(`Maestro target did not resolve to a visible element.`,{selector:e,candidateCount:i.candidateCount});return{kind:`selector`,selector:e,query:{selector:e,...t},...i,rect:i.rect}}function co(e){let t={kind:`selector`,selector:e.selector,visible:e.visible,candidateCount:e.candidateCount,...e.ref?{ref:e.ref}:{}};return{generation:e.generation,matched:e.matched&&e.visible,candidateCount:e.candidateCount,evidence:t}}function lo(e){if(!e||typeof e!=`object`)return!1;let t=e;return[`x`,`y`,`width`,`height`].every(e=>typeof t[e]==`number`&&Number.isFinite(t[e]))}function uo(e,t){return fo(e,t),po(e),mo(e),ho(e),e}function fo(t,n){if(t.generation!==n)throw new e(`COMMAND_FAILED`,`Maestro target evidence generation ${t.generation} does not match ${n}.`)}function po(t){if(!Number.isInteger(t.candidateCount)||t.candidateCount<0)throw new e(`COMMAND_FAILED`,`Maestro target evidence has an invalid candidate count.`)}function mo(t){if(t.rect!==void 0&&!lo(t.rect)||t.viewport!==void 0&&!lo(t.viewport))throw new e(`COMMAND_FAILED`,`Maestro target evidence has invalid geometry.`)}function ho(t){if(t.surfaceSignature!==void 0&&typeof t.surfaceSignature!=`string`)throw new e(`COMMAND_FAILED`,`Maestro target evidence has an invalid surface signature.`)}function go(e,t,n,r,i,a={}){let o=_o(e,t,n,i,a);if(!o)return;let{start:s,end:c}=So(o,n);return{gesture:{from:s,to:c,durationMs:r},viewport:o}}function _o(e,t,n,r,i){let a=n===`up`||n===`down`,o=Fa(e,Aa(e,r),i),s=o.visibility,c=la({visibility:s,matches:e.nodes.filter(e=>pe(e)),platform:r}),l=_e(s.viewportRects)??yo(c);if(!l||!D(l))return;let u=c.flatMap(e=>{if(!D(e.rect))return[];let t=bo(e.rect,l);return!t||(a?t.height<=t.width:t.width<t.height)?[]:[{node:e,viewport:t}]}),d=new Map(u.map(e=>[e.node.index,e]));for(let e of o.resolve(t).indexed){let t=vo(e,s.nodeByIndex),n=t?d.get(t.index):void 0;if(n)return n.viewport}return u.sort(xo)[0]?.viewport}function vo(e,t){return pe(e)?e:he(e,t)}function yo(e){let t;for(let n of e)D(n.rect)&&(!t||n.rect.width*n.rect.height>t.width*t.height)&&(t=n.rect);return t}function bo(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width)-n,a=Math.min(e.y+e.height,t.y+t.height)-r;return i>0&&a>0?{x:n,y:r,width:i,height:a}:void 0}function xo(e,t){return t.viewport.width*t.viewport.height-e.viewport.width*e.viewport.height}function So(e,t){let n=H(e,.5,.5),r=N.scrollUntilVisibleSwipe.nearEdgeFraction,i=N.scrollUntilVisibleSwipe.farEdgeFraction;switch(t){case`up`:return{start:n,end:H(e,.5,i)};case`down`:return{start:n,end:H(e,.5,r)};case`left`:return{start:n,end:H(e,i,.5)};case`right`:return{start:n,end:H(e,r,.5)}}}async function Co(t,n,r){let i=R(t.duration,`swipe.duration`);if(t.kind===`coordinates`){if(t.start.space!==t.end.space)throw new e(`INVALID_ARGS`,`Maestro swipe endpoints must use the same coordinate space.`);let a=t.start.space===`percent`?await r.resolveGestureViewport(V(n,n.command)):void 0;return{authored:t,gesture:To(await wo(t.start,n,r,a),await wo(t.end,n,r,a),i),...a?{viewport:a}:{}}}if(t.kind===`screen`){let e=await r.resolveGestureViewport(V(n,n.command)),{start:a,end:o}=Eo(e,t.direction,r.platform);return{authored:t,gesture:To(a,o,i),viewport:e}}let a=await so(t.from,{purpose:`swipe`,timeoutMs:`optional`in n.command&&n.command.optional===!0?N.command.optionalTargetLookupTimeoutMs:N.command.targetLookupTimeoutMs},n,r),o=a.viewport??await r.resolveGestureViewport(V(n,n.command)),{start:s,end:c}=Do(a,t.direction,o);return{authored:t,gesture:To(s,c,i),target:a,viewport:o}}async function wo(e,t,n,r){if(e.space===`absolute`)return{x:e.x,y:e.y};let i=r??await n.resolveGestureViewport(V(t,t.command));return{x:i.x+Math.trunc(i.width*e.x/100),y:i.y+Math.trunc(i.height*e.y/100)}}function To(e,t,n){return{from:e,to:t,durationMs:n??N.command.swipeDurationMs}}function Eo(e,t,n){if(t===`left`||t===`right`){let n=je(t,{referenceWidth:e.width,referenceHeight:e.height});return{start:{x:e.x+n.x1,y:e.y+n.y1},end:{x:e.x+n.x2,y:e.y+n.y2}}}let r=N.screenSwipe,i=H(e,r.centerFraction,r.nearEdgeFraction),a=H(e,r.centerFraction,r.farEdgeFraction),o=H(e,r.centerFraction,r.downStartFraction),s=H(e,r.centerFraction,r.upStartFraction[n]);return t===`up`?{start:s,end:i}:{start:o,end:a}}function H(e,t,n){return{x:e.x+Math.trunc(e.width*t),y:e.y+Math.trunc(e.height*n)}}function Do(e,t,n){let r=kt(e.rect),i=n.x+Math.trunc(n.width*N.targetSwipe.nearEdgeFraction),a=n.y+Math.trunc(n.height*N.targetSwipe.nearEdgeFraction),o=n.x+Math.trunc(n.width*N.targetSwipe.farEdgeFraction),s=n.y+Math.trunc(n.height*N.targetSwipe.farEdgeFraction);switch(t){case`up`:return{start:r,end:{x:r.x,y:a}};case`down`:return{start:r,end:{x:r.x,y:s}};case`left`:return{start:r,end:{x:i,y:r.y}};case`right`:return{start:r,end:{x:o,y:r.y}}}}const Oo={launchApp:U,stopApp:U,setPermissions:U,clearState:U,openLink:U,tapOn:Fo,doubleTapOn:Fo,longPressOn:Fo,swipe:Bo,inputText:Vo,eraseText:Vo,scroll:W,scrollUntilVisible:W,hideKeyboard:W,pressKey:W,back:W,waitForAnimationToEnd:W,takeScreenshot:Wo,runScript:Wo,evalScript:Ko,assertVisible:Go,assertNotVisible:Go,assertTrue:Go,extendedWaitUntil:Go},ko={launchApp:!0,stopApp:!0,setPermissions:!0,clearState:!0,openLink:!0,tapOn:!0,doubleTapOn:!0,longPressOn:!0,swipe:!0,inputText:!0,eraseText:!0,scroll:!0,scrollUntilVisible:!0,hideKeyboard:!0,pressKey:!0,back:!0,waitForAnimationToEnd:!0,takeScreenshot:!1,runScript:!1,evalScript:!1,assertVisible:!1,assertNotVisible:!1,assertTrue:!1,extendedWaitUntil:!1};function Ao(e){return ko[e.kind]}async function jo(e,t){let n=e.command;return await Mo(n,e,t,V(e,n))}function Mo(e,t,n,r){let i=Oo[e.kind];return i(e,t,n,r)}async function U(e,t,n,r){switch(e.kind){case`launchApp`:return await G(n.launchApp,No(e,t),r,`invalidate`);case`stopApp`:return await G(n.stopApp,{appId:e.appId??t.appId},r,`invalidate`);case`setPermissions`:return await G(n.setPermissions,{appId:e.appId??t.appId,permissions:Po(e.permissions)},r,`invalidate`);case`clearState`:return await G(n.clearState,{appId:e.appId??t.appId},r,`invalidate`);case`openLink`:return await G(n.openLink,{link:e.link},r,`invalidate`)}}function No(e,t){return M({appId:e.appId??t.appId,stopApp:e.stopApp,clearState:e.clearState,permissions:e.permissions?Po(e.permissions):void 0,arguments:e.arguments,launchArguments:e.launchArguments})}function Po(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.toLowerCase()]))}async function Fo(e,t,n,r){switch(e.kind){case`tapOn`:return await Io(e,t,n,r);case`doubleTapOn`:{let i=await es(e.target,{purpose:`doubleTap`,timeoutMs:Ro(e)},t,n),a=R(e.delay,`doubleTapOn.delay`)??N.command.repeatDelayMs;return await G(n.doubleTapOn,{target:i,delay:a},r,`invalidate`,i.resolution?co(i.resolution):void 0)}case`longPressOn`:{let i=await es(e.target,{purpose:`longPress`,timeoutMs:Ro(e)},t,n);return await G(n.longPressOn,{target:i},r,`invalidate`,i.resolution?co(i.resolution):void 0)}}}async function Io(e,t,n,r){let i=await Lo(e,t,n);return await G(n.tapOn,zo(e,i),r,`invalidate`,i.resolution?co(i.resolution):void 0)}async function Lo(e,t,n){let r={purpose:`tap`,timeoutMs:Ro(e),allowAtomicSelectorDispatch:e.repeat===void 0&&e.delay===void 0,...e.retryTapIfNoChange===!0?{includeSurfaceSignature:!0}:{}};return await es(e.target,r,t,n)}function Ro(e){return e.optional===!0?N.command.optionalTargetLookupTimeoutMs:N.command.targetLookupTimeoutMs}function zo(e,t){let n=R(e.repeat,`tapOn.repeat`),r=R(e.delay,`tapOn.delay`),i=n===void 0?r:r??N.command.repeatDelayMs;return M({target:t,retryTapIfNoChange:e.retryTapIfNoChange,repeat:n,delay:i})}async function Bo(e,t,n,r){let i=await Co(e.gesture,t,n);return await G(n.gesture,i.gesture,{...r,...i.viewport?{gestureViewport:i.viewport}:{}},`invalidate`,i.target?co(i.target):void 0)}async function Vo(e,t,n,r){switch(e.kind){case`inputText`:return await G(n.inputText,M({text:e.text,label:e.label}),r,`invalidate`);case`eraseText`:return await G(n.eraseText,M({charactersToErase:R(e.charactersToErase,`eraseText.charactersToErase`)}),r,`invalidate`)}}async function W(e,t,n,r){switch(e.kind){case`scroll`:return await G(n.scroll,{direction:`down`},r,`invalidate`);case`scrollUntilVisible`:return await G(n.scrollUntilVisible,Ho(e),r,`invalidate`);case`hideKeyboard`:return await G(n.hideKeyboard,{},r,`invalidate`);case`pressKey`:return await G(n.pressKey,{key:e.key},r,`invalidate`);case`back`:return await G(n.back,{},r,`invalidate`);case`waitForAnimationToEnd`:return await G(n.waitForAnimationToEnd,Uo(e),r,`preserve`)}}function Ho(e){return{selector:e.element,direction:e.direction??`down`,timeoutMs:R(e.timeout,`scrollUntilVisible.timeout`)??N.command.scrollUntilVisibleTimeoutMs,durationMs:In(N.command.scrollUntilVisibleSpeed)}}function Uo(e){return M({timeoutMs:R(e.timeout,`waitForAnimationToEnd.timeout`)})}async function Wo(e,t,n,r){switch(e.kind){case`takeScreenshot`:return Jo(await n.takeScreenshot({path:e.path},r),[],void 0,r.generation);case`runScript`:return await G(n.runScript,M({file:e.file,env:e.env}),r,`preserve`)}}async function Go(t){throw new e(`COMMAND_FAILED`,`Maestro ${t.kind} must be executed by the observation engine.`)}function Ko(t){throw new e(`COMMAND_FAILED`,`Maestro evalScript must be executed by the compute engine at ${t.source.path??``}line ${t.source.line}.`)}async function G(e,t,n,r,i){let a=qo(n,r);return Jo(await e(t,a),[],r===`preserve`?i:void 0,a.generation)}function qo(e,t){return t===`preserve`?e:(e.invalidateObservation(),{...e,generation:e.generation+1})}function Jo(e,t,n,r){let i=e?.observation;return Yo(i,r),{...Xo(n??i),...Zo(e?.outputEnv),...Qo(t,e?.artifactPaths),...$o(e?.data),...e?.visualStabilityReached===void 0?{}:{visualStabilityReached:e.visualStabilityReached}}}function Yo(t,n){if(!(!t||n===void 0||t.generation===n))throw new e(`COMMAND_FAILED`,`Maestro operation evidence generation ${t.generation} does not match ${n}.`)}function Xo(e){return e?{observation:e}:{}}function Zo(e){return e?{outputEnv:{...e}}:{}}function Qo(e,t){let n=[...new Set([...e,...t??[]])];return n.length>0?{artifactPaths:n}:{}}function $o(e){return e&&Object.keys(e).length>0?{data:{...e}}:{}}async function es(e,t,n,r){if(e.space===`target`){let i=await so(e.selector,t,n,r);return{authored:e,point:kt(i.rect),resolution:i}}return{authored:e,point:await wo(e,n,r)}}function ts(e,t,n,r={}){let i=n===`ios`&&r.presentation?rs(r.presentation):void 0,a=i?is(e,t,i):Na(e,t.selector,n);if(!a.parentMatched)return{ok:!1,message:`Maestro childOf parent did not match.`,evidence:cs(t,a.matches,[],void 0)};let{matches:o,ranked:s}=a,c=i?Ra(s,t.selector.index):La(s,t.selector.index)?.node,l=cs(t,o,s,c);if(!c)return as(t,o,s,l);let u=i?La(i.visibleForSource(c),void 0):null,d=za(c),f=r.interactiveBounds?u?.rect??d:d??u?.rect;return f?{ok:!0,node:c,rect:f,matches:s.length,dispatchCandidates:n===`ios`&&t.allowAtomicSelectorDispatch&&!ns(t.selector)&&i?os(d,s,u):0,evidence:l}:as(t,o,s,l)}const ns=fa;function rs(e){let t=ke(e.snapshot.nodes),n=t.nodeByIndex,r=new Map,i=t=>(e.presentedIndexesBySourceIndex.get(t.index)??[]).flatMap(e=>{let t=n.get(e);return t?[t]:[]}),a=e=>{let n=r.get(e.index);if(n)return n;let a=i(e).filter(e=>oa(e,t,`ios`));return r.set(e.index,a),a};return{visibleForSource:a,isVisible:e=>a(e).length>0}}function is(e,t,n){let r=Aa(e,`ios`),i=ya(e,{},{orderUnindexed:e=>ja(e,r)}),a=Pa(t.selector,i),o=a.matches.filter(n.isVisible);return{...a,visible:o,clickability:r,ranked:Ia(o,t.selector,`ios`,i.visibility,r)}}function as(e,t,n,r){return t.length>0&&n.length===0?{ok:!1,message:`Maestro selector matched ${t.length} element(s), but none were visible.`,evidence:r}:{ok:!1,message:`Maestro selector did not match${e.selector.index===void 0?``:` index ${e.selector.index}`}.`,evidence:r}}function os(e,t,n){return t.length===1?e&&n&&n.node.hittable!==!1&&ss(n.rect,e)?1:0:t.length}function ss(e,t){let n=kt(e),r=kt(t);return n.x===r.x&&n.y===r.y}function cs(e,t,n,r){return M({selector:e.selector,matched:t.length>0,visible:n.length>0,candidateCount:t.length,ref:r?.ref})}const K={settleTimeoutMs:Ln,retryTapMaxAttempts:N.command.retryTapMaxAttempts,longPressDurationMs:N.command.longPressDurationMs,eraseTextMaxCharacters:N.command.eraseTextMaxCharacters,scrollUntilVisiblePercentage:N.command.scrollUntilVisiblePercentage,animationWaitTimeoutMs:N.command.waitForAnimationToEndTimeoutMs,animationDifferencePercent:N.command.waitForAnimationToEndDifferencePercent,observationPollMs:N.observation.pollIntervalMs};function ls(e,t={}){return{execute:async n=>{let r=V(n,n.command),i=n.command.kind===`waitForAnimationToEnd`;await t.beforeExecute?.({context:r,requiresSettledPredecessor:Ao(n.command)&&!i,visualStabilityBarrier:i});let a=await jo(n,e);return t.afterExecute?.({context:r,visualStabilityReached:i&&a.visualStabilityReached===!0}),delete a.visualStabilityReached,a},observe:async n=>{let r=await ao(n,e);return t.bindObservation?.(r)??r},...t.readMetrics?{readMetrics:t.readMetrics}:{}}}const us=`This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.`;function q(t,n){let r=t.files[n];if(r===void 0)throw new e(`INVALID_ARGS`,`replay script source is missing ${n}; it was not part of the script sources sent with this request.`,{path:n,entry:t.entry});return r}function ds(e){let t=fs(e),n=Oe(t);return Gn(`sha256`).update(n,`utf8`).digest(`hex`)}function fs(e){let{actions:t,actionLines:n,actionSourcePaths:r,metadata:i}=e;return{platform:i.platform??null,target:i.target??null,steps:t.map((e,t)=>ps(e,n[t]??null,r?.[t]??null))}}function ps(e,t,n){return{command:e.command,positionals:e.positionals??[],flags:e.flags??{},runtime:e.runtime??null,targetEvidence:e.targetEvidence??null,targetEvidences:e.targetEvidences??null,source:{path:n,line:t}}}function ms(e,t,n){let{from:r,digest:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e;if(r===void 0&&i===void 0)return{ok:!0,value:0};if(r===void 0||i===void 0)return{ok:!1,message:`replay --from requires --plan-digest (and --plan-digest requires --from).`};let s=hs({from:r,digest:i,planDigest:n,actionCount:t,pendingRecordAndHeal:a,sessionActionsLength:o});return s?{ok:!1,message:s}:{ok:!0,value:r-1}}function hs(e){let{from:t,digest:n,planDigest:r,actionCount:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e,s=[()=>gs({from:t,actionCount:i,pendingRecordAndHeal:a}),()=>_s({from:t,pendingRecordAndHeal:a,sessionActionsLength:o}),()=>vs(n,r)];for(let e of s){let t=e();if(t)return t}}function gs(e){let{from:t,actionCount:n,pendingRecordAndHeal:r}=e,i=t===n+1&&r!==void 0&&r.expectedFrom===t;return Number.isInteger(t)&&t>=1&&(t<=n||i)?void 0:`replay --from ${t} is out of range for a ${n}-step plan.`}function _s(e){let{from:t,pendingRecordAndHeal:n,sessionActionsLength:r}=e;if(n?.expectedFrom===t&&r===n.actionsCountAtDivergence)return`replay --from ${t} continues a record-and-heal-shaped repair, but no corrective action was recorded in this repair segment; press the correct control via a blessed @ref from the divergence's screen.refs (recorded, no --no-record) — or, if your corrective action was a read (get/is/find/snapshot), re-run it with --record so it lands in the heal — before resuming with --from ${t}.`}function vs(e,t){if(e!==t)return`replay --plan-digest does not match the current plan digest; the script, its includes, or its platform-conditioned expansion changed since the divergence report was generated. Run a fresh full replay to get a new digest.`}function ys(t,n){let r=t.trimStart()[0];if(r===`{`||r===`[`)throw new e(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`);let i=Ie(t),a=Re(t),o=ds({actions:i.actions,actionLines:i.actionLines,actionSourcePaths:i.actionSourcePaths,metadata:{platform:n?.platform??Me(i.actions)??a.platform,target:n?.target??a.target}}),s=i.actions.length;return{actions:i.actions,actionLines:i.actionLines,actionSourcePaths:i.actionSourcePaths,metadata:a,planDigest:o,resolveEntryIndex:e=>ms(e,s,o)}}function bs(e){let{recorded:t,isSelectorWait:n}=e;return n?t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`deferred-landmark`,landmark:t}:{kind:`skip`}}function xs(e){let{recorded:t,token:n}=e;return n===void 0||!n.startsWith(`@`)&&Ce(`positional`,[n]).kind!==`expression`?{kind:`skip`}:t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`verify`,token:n}}function Ss(e,t){if(!(!e||!t)&&(e.documentOrder!==t.documentOrder||e.sibling!==t.sibling))return`position: recorded=doc${e.documentOrder}/sibling${e.sibling} observed=doc${t.documentOrder}/sibling${t.sibling}`}function Cs(e,t,n){let{observed:r,expectedStructural:i,observedStructural:a}=t,o=Ss(i,a);return{matchCount:n,observed:r,mismatches:[...r?ve(e,r):[],...o?[o]:[]],causeMessage:`Dispatch resolution (with occlusion/visibility guards) resolved a different element than pre-action verification isolated; the action was not sent.`}}function ws(e,t){let{matchCount:n,observed:r,observedAncestry:i}=t;return{matchCount:n,observed:r,mismatches:r?[...ve(e,r),...ae(e.ancestry,i)]:[],causeMessage:`Candidates matched the recorded wait selector during polling, but none carried the recorded landmark identity before the timeout; the wait did not report success.`}}async function Ts(e,t,n,r,i,a){if(n.targetEvidences)return Es(e,t,n,r,i,a);let o=n.targetEvidence;if(!o)return J(e,n,r,i,a);let s=e.beginTargetVerification(n,r,i);if(s.kind===`inactive`)return J(e,n,r,i,a);if(s.kind===`post-resolution`){let c=bs({recorded:o,isSelectorWait:s.isSelectorWait});switch(c.kind){case`skip`:return J(e,n,r,i,a);case`recorded-unverifiable`:return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};case`deferred-landmark`:return Os(e,t,n,r,i,a,{kind:`landmark`,landmark:c.landmark})}}let c=xs({recorded:o,token:s.token});if(c.kind===`skip`)return J(e,n,r,i,a);if(c.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};let l=c.token,u=await e.captureObservation(n,i,{retryLaunchRace:!0});if(u.state!==`available`)return{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,Ds(u),a,t)};let d=e.classifyTarget({action:n,index:i,token:l,nodes:u.nodes});return d.verified?Os(e,t,n,r,i,a,{kind:`target`,guard:d.guard}):{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,{kind:d.kind,matchCount:d.matchCount,observed:d.observed,candidateNodes:d.candidateNodes,mismatches:d.mismatches,causeCode:d.causeCode,causeMessage:d.causeMessage},a,t)}}async function Es(e,t,n,r,i,a){let o=n.targetEvidences,s={};for(let c of[`source`,`destination`]){let l={...n,targetEvidence:o[c]},u=e.beginTargetVerification(l,r,i,c);if(u.kind!==`pre-dispatch`)return J(e,n,r,i,a);let d=xs({recorded:o[c],token:u.token});if(d.kind===`skip`)return J(e,n,r,i,a);if(d.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(l,i,a,t)};let f=await e.captureObservation(l,i,{retryLaunchRace:!0});if(f.state!==`available`)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,Ds(f),a,t)};let p=e.classifyTarget({action:l,index:i,token:d.token,nodes:f.nodes});if(!p.verified)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,{kind:p.kind,matchCount:p.matchCount,observed:p.observed,candidateNodes:p.candidateNodes,mismatches:p.mismatches,causeCode:p.causeCode,causeMessage:p.causeMessage},a,t)};s[c]=p.guard}return Os(e,t,n,r,i,a,{kind:`targets`,guards:{source:s.source,destination:s.destination}})}function Ds(e){return{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Could not capture a fresh snapshot to verify the recorded target before acting (${e.reason}).`,...e.hint===void 0?{}:{causeHint:e.hint}}}async function J(e,t,n,r,i){let a=await e.dispatchStep(t,n,r,i,void 0);switch(a.status){case`ok`:return{status:`ok`,artifactPaths:a.artifactPaths};case`failed`:return{status:`failed`,failure:a.failure};case`guard-mismatch`:case`landmark-mismatch`:return{status:`failed`,failure:a.plainFailure}}}async function Os(e,t,n,r,i,a,o){let s=await e.dispatchStep(n,r,i,a,o);if(s.status===`ok`)return{status:`ok`,artifactPaths:s.artifactPaths};if(s.status===`failed`)return{status:`failed`,failure:s.failure};let c=ks(n,o,s);if(!c)return{status:`failed`,failure:s.plainFailure};let l=As(c.recorded,c.matchCount,s);return{status:`failed`,failure:await e.buildPostDispatchTargetBindingFailure(c.reportAction,i,{kind:`identity-mismatch`,matchCount:l.matchCount,observed:l.observed,candidateNodes:[],mismatches:l.mismatches,causeCode:`IDENTITY_MISMATCH`,causeMessage:l.causeMessage},a,t)}}function ks(e,t,n){if(n.status!==`guard-mismatch`||t.kind!==`targets`)return e.targetEvidence?{recorded:e.targetEvidence,reportAction:e,matchCount:t.kind===`target`?t.guard.matchCount:0}:void 0;let r=n.evidence.targetRole??`source`,i=e.targetEvidences?.[r];return i?{recorded:i,reportAction:{...e,targetEvidence:i},matchCount:t.guards[r].matchCount}:void 0}function As(e,t,n){return n.status===`guard-mismatch`?Cs(e,n.evidence,t):ws(e,n.evidence)}async function js(e,t){let{actions:n,entryIndex:r,keepSession:i}=e,a=Xe(e.varSources),o=[],s=[],c=Fs(n),l=0;for(let u=r;u<n.length;u+=1){let r=n[u];if(!Ps(r)||(t.armStep(),u===c&&(i||t.isRepairArmed())))continue;if(l+=1,t.onStep){let e=t.describeStepValue(r);t.onStep(Is(u,n.length,r,e))}let d=rt(r,a,Ns(e,u)),f=Je(a),p=t.diagnosticsMarker(),m=await Ts(t,f,r,d,u,o);if(s.push(...t.diagnosticsSince(p)),m.status===`ok`){o=m.artifactPaths;continue}let h=await t.handleActionFailure({action:r,index:u,artifactPaths:Ms(o,m.failure.artifactPaths),snapshotDiagnosticSamples:s,scrubVars:f});return{status:`failed`,stepIndex:u,failure:h}}return{status:`completed`,replayed:l,artifactPaths:[...o],snapshotDiagnosticSamples:s}}function Ms(e,t){return t.length===0?e:[...new Set([...e,...t])]}function Ns(e,t){return{file:e.actionSourcePaths?.[t]??e.resolvedPath,line:e.actionLines[t]??1}}function Ps(e){return!!(e&&e.command!==`replay`)}function Fs(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(Ps(n))return n.command===`close`?t:void 0}}function Is(e,t,n,r){return{index:e+1,total:t,command:n.command,...r===void 0?{}:{value:r}}}function Ls(e){if(e.length===0)return{selectorExpression:null,selectorTimeout:null};let t=e.at(-1),n=t!==void 0&&/^\d+$/.test(t)?t:null,r=n===null?e.slice():e.slice(0,-1),i=Ce(`positional`,r);return i.kind!==`expression`||i.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:i.expression,selectorTimeout:n}}function Rs(e){let t=[],n=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];if(t.push(...n),Fe(e.command)){let n=zs(e),r=n[0]??``;r&&!r.startsWith(`@`)&&t.push(n.join(` `))}if(e.command===`fill`){let n=e.positionals?.[0]??``;n&&!n.startsWith(`@`)&&Number.isNaN(Number(n))&&t.push(n)}if(e.command===`get`){let n=e.positionals?.[1]??``;n&&!n.startsWith(`@`)&&t.push(e.positionals.slice(1).join(` `))}if(e.command===`is`){let n=Ce(`is`,[...e.positionals]);n.kind===`expression`&&t.push(n.expression)}if(e.command===`wait`){let{selectorExpression:n}=Ls([...e.positionals]);n&&t.push(n)}return xe(t).filter(e=>e.trim().length>0)}function zs(e){let t=e.positionals;if(e.command!==`longpress`)return t;let n=t.at(-1);return t.length>1&&Bs(n)?t.slice(0,-1):t}function Bs(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function Vs(e){let t=P.dirname(e),n=P.basename(e,P.extname(e));return P.join(t,`${n}.healed.ad`)}function Hs(e){let t=Us({failedIndex:e.failedIndex,actions:e.actions,planDigest:e.planDigest,repairHint:e.repairHint,sessionExists:e.resumeStamper.sessionExists()});return e.resumeStamper.stampCorrectiveWatermark({resume:t,repairHint:e.repairHint,failedIndex:e.failedIndex,actions:e.actions}),t}function Us(e){let{failedIndex:t,actions:n,planDigest:r,repairHint:i,sessionExists:a}=e,o=i===`record-and-heal`?t+1:t,s=Ws({failedIndex:t,actions:n,repairHint:i,sessionExists:a});return{allowed:!0,from:o,planDigest:r,...s===void 0?{}:{alternateFrom:s}}}function Ws(e){let{failedIndex:t,actions:n,repairHint:r,sessionExists:i}=e;if(r!==`caution`&&r!==`manual`)return;let a=t+1;if(!(a>n.length&&!i))return a}function Gs(e){let{kind:t,targetEvidence:n,capture:r}=e;if(t===`identity-mismatch`)return`caution`;if(t===`identity-unverifiable`||!n||r.state!==`available`||!Ks(n))return`manual`;let i=qs(n,r.nodes);return t===`selector-miss`?i?`record-and-heal`:`state-repair`:i?`record-and-heal`:`manual`}function Ks(e){return e.ancestry.length>0||e.scrollRegion!==void 0&&Js(e.scrollRegion)}function qs(e,t){let n=ut(t),r=Xs(e.ancestry,n,t),i=e.scrollRegion;return i&&Js(i)?r&&Ys(i,n,t):r}function Js(e){return e.id!==void 0||e.label!==void 0}function Ys(e,t,n){return n.some(n=>We(qe(n,t),e))}function Xs(e,t,n){return e.length===0?n.length>0:n.some(n=>{let r=ct(n,t,e.length);return!r.broken&&ge(r.chain,e)})}function Zs(e){let{sessionStore:t,observationStore:n,divergence:r,responseLevel:a}=e,o,s,c=Tt({divergence:r,level:a,writeOverflowArtifact:e=>{let n=i(e),r=ec(t,n);return`artifactPath`in r&&(o=n,s=r.artifactPath),r}}),l=(o??c).screen;if(l.state!==`available`||l.refs.length===0)return e.evidence&&n.bindAuthority(e.signal).finalize(e.evidence,{refsGeneration:l.state===`available`?l.refsGeneration:void 0,refs:[]}),c;if(!e.evidence)return $s(s),Qs(c,`missing-evidence`);let u=n.bindAuthority(e.signal).finalize(e.evidence,{refsGeneration:l.refsGeneration,refs:l.refs.map(e=>e.ref)});return u.published===!0?c:($s(s),Qs(c,u.reason))}function Qs(e,t){let{overflow:n,...r}=e;return{...r,screen:{state:`unavailable`,reason:`ref-publication-${t}`,hint:`The replay observation changed before its refs could be published. Take a new snapshot before targeting an element.`},suggestions:e.suggestions.map(({ref:e,...t})=>t),...e.targetBinding?{targetBinding:{...e.targetBinding,candidates:e.targetBinding.candidates.map(({ref:e,...t})=>t)}}:{}}}function $s(e){if(e)try{F.unlinkSync(e)}catch{}}function ec(e,t){try{let n=P.join(e.ensureSessionDir(),`replay-divergence`);F.mkdirSync(n,{recursive:!0});let r=`${Date.now()}-step${t.step.index}.json`,i=P.join(n,r);return F.writeFileSync(i,`${JSON.stringify(t,null,2)}\n`),{artifactPath:i}}catch{return{artifactUnavailable:!0}}}const tc={id:0,"role-label":1,label:2,other:3};function nc(e){let t=new Map;for(let n of e){let e=t.get(n.nodeIndex);(!e||rc(n.basis)<rc(e.basis))&&t.set(n.nodeIndex,n)}return[...t.values()].sort((e,t)=>rc(e.basis)-rc(t.basis)||e.nodeIndex-t.nodeIndex)}function rc(e){return tc[e]}async function ic(e){let{error:t,action:n,index:r,sourcePath:i,sourceLine:a,session:o,sessionStore:s,observationStore:c,resumeStamper:l,logPath:u,responseLevel:d,scrubVars:f=[],planActions:p,planDigest:m,signal:h}=e,g=wt(f),_={code:t.code,message:g(t.message),...t.hint?{hint:g(t.hint)}:{}},v=o?await sc({session:o,observationStore:c,logPath:u,action:n}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},y=dc(v,g),b=v.state===`available`&&o?gc({action:n,session:o,nodes:v.nodes,sanitize:g}):[],x=Gs({kind:`action-failure`,targetEvidence:n.targetEvidence,capture:ac(v)}),S=Hs({failedIndex:r+1,actions:p,planDigest:m,repairHint:x,resumeStamper:l});return Zs({sessionStore:s,observationStore:c,divergence:{version:1,kind:`action-failure`,step:{index:r+1,source:{path:g(i),line:a}},action:g(Pe(n)),cause:_,screen:y,suggestions:b.slice(0,5),suggestionCount:b.length,resume:S,repairHint:x},responseLevel:d,evidence:v.state===`available`?v.evidence:void 0,...h?{signal:h}:{}})}function ac(e){return e.state===`available`?{state:`available`,nodes:e.nodes}:{state:`unavailable`}}const oc=[300,500,800,1200,2e3,3e3,4e3];async function sc(e){let{session:t,observationStore:n,logPath:r,action:i,retryLaunchRace:a=!1}=e,o=lc(i),s=Date.now()+12e3,c=await cc({session:t,observationStore:n,logPath:r,flags:o});if(!a)return c.observation;for(let e of oc){if(c.observation.state===`available`||!c.retryable)break;let i=s-Date.now();if(i<=0)break;await bt(Math.min(e,i)),c=await cc({session:t,observationStore:n,logPath:r,flags:o})}return c.observation}async function cc(e){let{session:t,observationStore:n,logPath:r,flags:i}=e;try{let e=(await n.capture({flags:i,logPath:r})).snapshot;if(zn(e.snapshotQuality))return{observation:{state:`unavailable`,reason:`sparse-snapshot`,hint:`The post-failure snapshot was sparse or unavailable; run snapshot -i to observe the current screen.`},retryable:!0};let a=n.bindAuthority().store(e);return{observation:{state:`available`,nodes:e.nodes,refsGeneration:a.refsGeneration,evidence:a.evidence,appBundleId:t.appBundleId},retryable:!1}}catch(e){return{observation:{state:`unavailable`,reason:`capture-failed`,hint:`Post-failure snapshot capture failed (${e instanceof Error?e.message:String(e)}); the original replay failure is unaffected.`},retryable:At(e)}}}function lc(e){return{snapshotInteractiveOnly:uc(e)}}function uc(e){return!_c(e.command)||vc(e).requiresRect}function dc(e,t){if(e.state===`unavailable`)return{state:`unavailable`,reason:t(e.reason),hint:t(e.hint)};let{refs:n,truncated:r}=hc(e.nodes,t,e.appBundleId);return{state:`available`,refsGeneration:e.refsGeneration,refs:n,...r?{truncated:!0}:{}}}function fc(e){return!!gt(e,mt(e.type??`Element`))||e.hittable===!0}function pc(e,t){return t!==void 0&&e.bundleId!==void 0&&e.bundleId!==t&&e.hittable===!0}function mc(e,t){let n=dt(e,t),r=e.filter(e=>e.ref&&!n.has(e.ref)&&fc(e)),i=r.length>0?r:e.filter(e=>e.ref&&e.hittable===!0),a=i.filter(e=>e.interactionBlocked!==`covered`),o=a.length>0?a:i,s=[...o.filter(e=>pc(e,t)),...o.filter(e=>!pc(e,t))],c=s.slice(0,20);return{nodes:c,truncated:s.length>c.length}}function hc(e,t,n){let{nodes:r,truncated:i}=mc(e,n);return{refs:r.map(e=>{let n=mt(e.type??`Element`),r=gt(e,n);return{ref:e.ref,role:t(n),...r?{label:t(r)}:{}}}),truncated:i}}function gc(e){let{action:t,session:n,nodes:r,sanitize:i}=e;if(!_c(t.command))return[];let a=Rs(t);return a.length===0?[]:yc({candidates:a,nodes:r,session:n,action:t,matching:vc(t),sanitize:i})}function _c(e){return Fe(e)||[`fill`,`get`,`is`,`wait`].includes(e)}function vc(e){let t=Fe(e.command);return{requiresRect:t||e.command===`fill`,allowDisambiguation:t||e.command===`fill`||e.command===`get`&&e.positionals?.[0]===`text`}}function yc(e){let{candidates:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=[];for(let e of t){let t=bc({candidate:e,nodes:n,session:r,action:i,matching:a,sanitize:o});t&&s.push(t)}return nc(s).map(e=>e.suggestion)}function bc(e){let{candidate:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=be(t,n,{platform:r.device.platform,requireRect:a.requiresRect,allowDisambiguation:a.allowDisambiguation});if(s)return{suggestion:xc({node:s.node,nodes:n,session:r,action:i,basis:s.basis,sanitize:o}),basis:s.basis,nodeIndex:s.node.index}}function xc(e){let{node:t,nodes:n,session:r,action:i,basis:a,sanitize:o}=e,s=De(t,r.device.platform,{action:i.command===`fill`?`fill`:Fe(i.command)?`click`:`get`,nodes:n}),c=mt(t.type??`Element`),l=gt(t,c);return{selector:o(s.join(` || `)),basis:a,...t.ref?{ref:t.ref}:{},role:o(c),...l?{label:o(l)}:{}}}function Sc(e){return{...e,hint:e.hint??Tc(e.details,`hint`),diagnosticId:e.diagnosticId??Tc(e.details,`diagnosticId`),logPath:e.logPath??Tc(e.details,`logPath`)}}function Cc(e){let{error:t,action:n,step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c}=e;return wc({error:t,actionLabel:Pe(n),action:n.command,positionals:Ve(n)??[],step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c})}function wc(e){let{error:t,actionLabel:n,action:r,positionals:i,step:a,replayPath:o,artifactPaths:s,snapshotDiagnostics:c,divergence:l,scrubVars:u,warnings:d}=e;return{ok:!1,error:{code:`REPLAY_DIVERGENCE`,message:Ct(`Replay failed at step ${a} (${n}): ${t.message}`,u),hint:t.hint===void 0?void 0:Ct(t.hint,u),diagnosticId:t.diagnosticId,logPath:t.logPath,...t.retriable===void 0?{}:{retriable:t.retriable},...t.supportedOn===void 0?{}:{supportedOn:t.supportedOn},details:{...Dc(t.details),replayPath:o,step:a,action:r,positionals:i,artifactPaths:s,...c?{snapshotDiagnostics:c}:{},...d&&d.length>0?{warnings:d.map(e=>Ct(e,u))}:{},divergence:l}}}}function Tc(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}const Ec=[`reason`,`recovery`,`retriable`,`snapshotQuality`,`supportedOn`,`systemSurface`];function Dc(e){if(!e)return{};let t={};for(let n of Ec)e[n]!==void 0&&(t[n]=e[n]);return t}async function Oc(e){return await kc({...e,snapshotDiagnostics:g(e.snapshotDiagnosticSamples)})}async function kc(e){let{response:t,action:n,index:r,replayPath:i,sourcePath:a,sourceLine:o,artifactPaths:s=[],snapshotDiagnostics:c,scrubVars:l,req:u,sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,planActions:h,planDigest:g}=e;if(t.ok)return t;let _=Ac(t.error.details?.replaySource),v=Sc(t.error),y=await ic({error:v,action:n,index:r,sourcePath:_?.path??a,sourceLine:_?.line??o,session:f.get(),sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,responseLevel:u.meta?.responseLevel,scrubVars:l,planActions:h,planDigest:g,signal:j(u.meta?.requestId)});return Cc({error:v,action:n,step:r+1,replayPath:i,artifactPaths:s,snapshotDiagnostics:c,divergence:y,scrubVars:l})}function Ac(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=typeof t.path==`string`&&t.path.length>0?t.path:void 0,r=typeof t.line==`number`?t.line:void 0;if(n!==void 0||r!==void 0)return{path:n,line:r}}function jc(e,t){if(e)try{F.appendFileSync(e,`${JSON.stringify(i(t))}\n`)}catch(t){O({level:`warn`,phase:`replay_trace_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}}async function Mc(t){let{req:r,sessionName:i,action:a,resolved:o,filePath:s,line:c,step:l,sourcePath:u,tracePath:d,invoke:f,resolvedSessionScope:p,dependencies:m}=t,h=Date.now();jc(d,{type:`replay_action_start`,ts:new Date(h).toISOString(),replayPath:s,...u?{sourcePath:u}:{},line:c,step:l,command:o.command,positionals:Ve(o)??[]});let g;try{g=await Pc({req:r,sessionName:i,resolved:o,sourceAction:a,invoke:f,resolvedSessionScope:p,dependencies:m})}catch(t){if(!(t instanceof e))throw t;g={ok:!1,error:n(t)}}let _=Date.now();return jc(d,{type:`replay_action_stop`,ts:new Date(_).toISOString(),replayPath:s,...u?{sourcePath:u}:{},line:c,step:l,command:o.command,ok:g.ok,durationMs:_-h,resultTiming:g.ok?Ic(g.data):void 0,errorCode:g.ok?void 0:g.error.code}),Nc(g,u??s,c)}function Nc(e,t,n){return e.ok||e.error.details?.replaySource!==void 0?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},replaySource:{path:t,line:n}}}}}async function Pc(e){let{req:t,sessionName:n,resolved:r,sourceAction:i,invoke:a,resolvedSessionScope:o,dependencies:s}=e,c=Lc(t.flags,r.flags),l=i.command===`fill`?at(it(i)):void 0;return l&&(c.recordAs=l),await a(Fc({token:t.token,session:n,flags:c,runtime:r.runtime,meta:t.meta,dispatch:{...t.dispatch,replayPlanStep:!0,...r.command===`open`?{resolvedSessionScope:o??s.resolveSessionScope(t)}:{}}},r))}function Fc(e,t){let n=t.positionals??[];return t.command===`gesture`?{...e,command:t.command,positionals:[],input:Ne(n,e.flags?.pointerCount)}:t.command===`swipe`?{...e,command:t.command,positionals:[],input:ze(n,{count:e.flags?.count,pauseMs:e.flags?.pauseMs,pattern:e.flags?.pattern})}:{...e,command:t.command,positionals:n}}function Ic(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.timing;if(!(!t||typeof t!=`object`||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return t===`number`||t===`string`||t===`boolean`}))}function Lc(e,t){return h(e,{...t??{}})}function Rc(e){return Gc(e.ok?Bc(e.data):zc(e.error.details?.artifactPaths))}function zc(e){return Array.isArray(e)?e.filter(Wc):[]}function Bc(e){return e?[Uc(e.path),Uc(e.outPath),...Vc(e.artifacts)].filter(Wc):[]}function Vc(e){return Array.isArray(e)?e.map(Hc).filter(Wc):[]}function Hc(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;return Uc(t.localPath)??Uc(t.path)}function Uc(e){return typeof e==`string`?e:void 0}function Wc(e){return typeof e==`string`}function Gc(e){return[...new Set(e.filter(Kc))]}function Kc(e){try{return F.statSync(e).isFile()}catch{return!1}}function qc(e){let{recorded:t,token:n,nodes:r,platform:i,refLabel:a,requireRect:o,allowDisambiguation:s}=e,c=Jc({token:n,nodes:r,platform:i,refLabel:a,requireRect:o,allowDisambiguation:s}),l=ut(r),u=fe(t),d=st(c.matchedNodes,l,u,t.ancestry),f=d.filter(e=>Ue(r,e)===t.sibling),p=d.filter(e=>We(qe(e,l),t.scrollRegion)),m=Ke(p)[t.viewportOrder]?.ref,h=He({winnerRef:c.winnerRef,matchedRefs:c.matchedNodes.map(e=>e.ref),identitySetRefs:d.map(e=>e.ref),siblingMatchRefs:f.map(e=>e.ref),regionMemberRefs:p.map(e=>e.ref),viewportCandidateRef:m}),g=c.matchedNodes.find(e=>e.ref===c.winnerRef);return h.outcome===`verified`&&g?{verified:!0,winnerNode:g,matchCount:c.matchedNodes.length}:h.outcome===`verified`?{verified:!1,kind:`identity-unverifiable`,matchCount:c.matchedNodes.length,observedNode:void 0,candidateNodes:d.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Verification isolated a member that is not part of the matched-node domain (capture anomaly).`}:{verified:!1,...Zc({classification:h,matchCount:c.matchedNodes.length,winnerNode:g,identitySet:d,byIndex:l,recorded:t})}}function Jc(e){let{token:t,nodes:n,platform:r,refLabel:i,requireRect:a,allowDisambiguation:o}=e;return t.startsWith(`@`)?Yc(n,t,i,a):Xc(n,t,r,a,o)}function Yc(e,t,n,r){let i=e=>e!==null&&(!r||!!e.rect),s=o(t),c=s?a(e,s):null;if(i(c))return{matchedNodes:[c],winnerRef:c.ref};let l=n?ot(e,n):null;return i(l)?{matchedNodes:[l],winnerRef:l.ref}:{matchedNodes:[],winnerRef:``}}function Xc(e,t,n,r,i){let a=Se(t,e,{platform:n,requireRect:r,allowDisambiguation:i});if(a.kind===`resolved`)return{matchedNodes:[...a.matchedNodes],winnerRef:a.winner.ref};let o=ft(e,a.matchedNodes);return{matchedNodes:[...a.matchedNodes],winnerRef:o?.ref??``}}function Zc(e){let{classification:t,matchCount:n,winnerNode:r,identitySet:i,byIndex:a,recorded:o}=e;switch(t.reason){case`selector-miss`:return{kind:`selector-miss`,matchCount:0,observedNode:void 0,candidateNodes:[],mismatches:[],causeCode:`SELECTOR_MISS`,causeMessage:`The recorded target no longer matches any current element.`};case`identity-set-empty`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Qc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`The recorded selector/ref still matches, but nothing in the current tree carries the recorded identity.`};case`unique-but-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Qc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`Exactly one current element carries the recorded identity, but the resolved target is a different element.`};case`signal-isolated-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Qc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`A disambiguation signal (sibling or viewport position) isolated a different element than the resolved target.`};case`no-signal-isolation`:return{kind:`identity-unverifiable`,matchCount:n,observedNode:r,candidateNodes:i.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`${i.length} current elements carry the recorded identity and neither disambiguation signal isolated one.`}}}function Qc(e,t,n){let r=Ge(t),i=ct(t,n,Math.max(e.ancestry.length,1)).chain;return[...ve(e,r),...ae(e.ancestry,i)].slice(0,5)}function $c(e,t){let n=e.positionals??[];if(e.command===`gesture`){let e=Be(n);return e?e[t??`source`]:void 0}if(e.command===`get`)return n[1];if(e.command===`is`){let e=Ce(`is`,n);return e.kind===`expression`?e.expression:void 0}if(!Fe(e.command)&&e.command!==`fill`)return;let r=n[0];if(r!==void 0&&!(tl(r)&&tl(n[1])))return r}function el(e){let t=e.result?.refLabel;return typeof t==`string`&&t.length>0?t:void 0}function tl(e){return e!==void 0&&e.trim().length>0&&!Number.isNaN(Number(e))}function nl(e,t){let{recorded:n,action:r,step:i,sourcePath:a,sourceLine:o,replayPath:s,artifactPaths:c,sessionStore:l,resumeStamper:u,responseLevel:d,scrubVars:f,planActions:p,planDigest:m}=e,h=wt(f),g={classification:t.kind,...t.matchCount===void 0?{}:{matchCount:t.matchCount},recorded:fl(fe(n),h),...t.observed?{observed:fl(t.observed,h)}:{},mismatches:t.mismatches.slice(0,5).map(e=>h(e)),candidates:t.candidateNodes.slice(0,5).map(e=>pl(e,h))},_=Gs({kind:t.kind,targetEvidence:n,capture:t.repairCapture}),v=Hs({failedIndex:i,actions:p,planDigest:m,repairHint:_,resumeStamper:u}),y={version:1,kind:t.kind,step:{index:i,source:{path:h(a),line:o}},action:h(Pe(r)),cause:{code:t.causeCode,message:h(t.causeMessage),...t.causeHint?{hint:h(t.causeHint)}:{}},screen:t.screen,suggestions:[],suggestionCount:0,resume:v,repairHint:_,targetBinding:g},b=Zs({sessionStore:l,observationStore:e.observationStore,divergence:y,responseLevel:d,evidence:t.publicationEvidence,...e.signal?{signal:e.signal}:{}});return Cc({error:{code:t.causeCode,message:t.causeMessage},action:r,step:i,replayPath:s,artifactPaths:c,divergence:b,scrubVars:f})}function rl(e,t,n){let r=wt(e.scrubVars);return nl(e,{kind:t.kind,matchCount:t.matchCount,observed:t.observed,candidateNodes:t.candidateNodes,mismatches:t.mismatches,causeCode:t.causeCode,causeMessage:t.causeMessage,...t.causeHint===void 0?{}:{causeHint:t.causeHint},screen:dc(n,r),publicationEvidence:sl(n),repairCapture:ac(n)})}async function il(e){let{session:t,observationStore:n,logPath:r,action:i,unavailableHint:a}=e;return t?await sc({session:t,observationStore:n,logPath:r,action:i}):{state:`unavailable`,reason:`no-session`,hint:a}}async function al(e,t){return rl(e,{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`The recorded target evidence could not verify itself when it was captured (a structural capture anomaly), so replay cannot trust it before acting.`},await il({...t,unavailableHint:`The session closed before a screen could be captured to verify the recorded target evidence.`}))}async function ol(e,t,n){return rl(e,t,await il({...n,unavailableHint:`The session closed before a post-failure screen could be captured.`}))}function sl(e){return e.state===`available`?e.evidence:void 0}function cl(e){let{action:t,resolvedAction:n,sessionStore:r,targetRole:i}=e,a=r.get();return a?me(t.command)===`post-resolution`?{kind:`post-resolution`,isSelectorWait:we(n.positionals??[])?.kind===`selector`}:{kind:`pre-dispatch`,token:$c(n,i),platform:a.device.platform}:{kind:`inactive`}}function ll(e){let{recorded:t,token:n,action:r,nodes:i,platform:a}=e,o=vc(r),s=qc({recorded:t,token:n,nodes:i,platform:a,refLabel:el(r),requireRect:o.requiresRect,allowDisambiguation:o.allowDisambiguation});return s.verified?{verified:!0,guard:{expected:{identity:Ge(s.winnerNode),structural:ce(s.winnerNode,i)},matchCount:s.matchCount}}:{verified:!1,kind:s.kind,matchCount:s.matchCount,observed:s.observedNode?Ge(s.observedNode):void 0,candidateNodes:s.candidateNodes,mismatches:s.mismatches,causeCode:s.causeCode,causeMessage:s.causeMessage}}function ul(e){return!e.ok&&e.error.details?.reason===`replay_target_guard_mismatch`}function dl(e){return!e.ok&&e.error.details?.reason===lt}function fl(e,t){return{...e.id===void 0?{}:{id:t(e.id)},role:t(e.role),...e.label===void 0?{}:{label:t(e.label)}}}function pl(e,t){let n=mt(e.type??`Element`),r=gt(e,n);return{...e.ref?{ref:e.ref}:{},role:t(n),...r?{label:t(r)}:{}}}function ml(e,t){let n=t?.kind===`target`?{replayTargetGuard:t.guard.expected}:t?.kind===`targets`?{replayTargetGuards:{source:t.guards.source.expected,destination:t.guards.destination.expected}}:t?.kind===`landmark`?{replayLandmarkGuard:t.landmark}:void 0;return n?{...e,dispatch:{...e.dispatch,...n}}:e}function hl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.role==`string`)return{...typeof t.id==`string`?{id:t.id}:{},role:t.role,...typeof t.label==`string`?{label:t.label}:{}}}function gl(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))return[];let e=n;if(typeof e.role!=`string`)return[];t.push({role:e.role,...typeof e.label==`string`?{label:e.label}:{}})}return t}function _l(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.documentOrder==`number`&&typeof t.sibling==`number`)return{documentOrder:t.documentOrder,sibling:t.sibling}}function vl(e){return{...e?.targetRole===`source`||e?.targetRole===`destination`?{targetRole:e.targetRole}:{},observed:hl(e?.observed),expectedStructural:_l(e?.expectedStructural),observedStructural:_l(e?.observedStructural)}}function yl(e){return{matchCount:typeof e?.matchCount==`number`?e.matchCount:void 0,observed:hl(e?.observed),observedAncestry:gl(e?.observedAncestry)}}function bl(e,t){return{kind:e.error.code,message:e.error.message,artifactPaths:t}}function xl(e,t,n){let r=bl(e,n);return(t?.kind===`target`||t?.kind===`targets`)&&ul(e)?{status:`guard-mismatch`,evidence:vl(e.error.details),plainFailure:r,artifactPaths:n}:t?.kind===`landmark`&&dl(e)?{status:`landmark-mismatch`,evidence:yl(e.error.details),plainFailure:r,artifactPaths:n}:{status:`failed`,failure:r}}function Sl(e){let{ctx:t,req:n,artifactPaths:r,onStep:i,armSaveScript:a}=e,o,s,c=(e,n,r,i)=>({recorded:e.targetEvidence,action:e,step:n+1,sourcePath:t.actionSourcePaths?.[n]??t.resolved,sourceLine:t.actionLines[n]??1,replayPath:t.resolved,artifactPaths:[...r],sessionStore:t.sessionStore,observationStore:t.observationStore,resumeStamper:t.coordinator.resumeStamper,responseLevel:t.responseLevel,scrubVars:i,planActions:t.actions,planDigest:t.planDigest,signal:t.signal}),l=e=>(o=e,bl(Cl(e),Rc(e)));return{runtime:{beginTargetVerification(e,n,r,i){return cl({action:e,resolvedAction:n,sessionStore:t.sessionStore,targetRole:i})},async captureObservation(e,n,r){let i=t.observationStore.get(),a=i?await sc({session:i,observationStore:t.observationStore,logPath:t.logPath,action:e,retryLaunchRace:r.retryLaunchRace}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a screen could be captured to verify the recorded target.`};return s=a,a.state===`available`?{state:`available`,nodes:a.nodes}:{state:`unavailable`,reason:a.reason,hint:a.hint}},classifyTarget({action:e,token:n,nodes:r}){let i=t.sessionStore.get();return ll({recorded:e.targetEvidence,token:n,action:e,nodes:[...r],platform:i.device.platform})},async dispatchStep(e,n,i,a,s){let c=t.actionLines[i]??1,l=await Mc({req:ml(t.replayReq,s),sessionName:t.sessionName,action:e,resolved:n,filePath:t.resolved,line:c,sourcePath:t.actionSourcePaths?.[i],step:i+1,tracePath:t.actionTracePath,invoke:t.invoke,resolvedSessionScope:t.resolvedSessionScope,dependencies:t.dependencies});o=l,Rc(l).forEach(e=>r.add(e));let u=[...r];return l.ok?{status:`ok`,artifactPaths:u}:xl(l,s,u)},async buildRecordedUnverifiableFailure(e,n,r,i){let a=await al(c(e,n,r,i),{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(a)},async buildTargetBindingFailure(e,t,n,r,i){let a=s??{state:`unavailable`,reason:`observation-missing`,hint:`No capture was recorded before this target-binding failure.`},o=rl(c(e,t,r,i),n,a);return l(o)},async buildPostDispatchTargetBindingFailure(e,n,r,i,a){let o=await ol(c(e,n,i,a),r,{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(o)},async handleActionFailure({action:e,index:r,artifactPaths:i,snapshotDiagnosticSamples:a,scrubVars:s}){let c=Cl(o),u=await wl(t,n,e,r,c,[...i],[...a],s);return l(u)},armStep:()=>{s=void 0,a()},isRepairArmed:()=>t.coordinator.view()?.repairBoundary!==void 0,describeStepValue:e=>Tl(e),onStep:i,diagnosticsMarker:()=>Dl(t.sessionStore),diagnosticsSince:e=>Ol(t.sessionStore,e)},readLastResponse:()=>o}}function Cl(e){return e&&!e.ok?e:u(`COMMAND_FAILED`,`replay step reported failure with no recorded response`)}async function wl(e,t,n,r,i,a,o,s){let c=t=>e.coordinator.markSessionHeldIfArmed(t);return El(i)?c(i):c(await Oc({response:i,action:n,index:r,replayPath:e.resolved,sourcePath:e.actionSourcePaths?.[r]??e.resolved,sourceLine:e.actionLines[r]??1,artifactPaths:a,snapshotDiagnosticSamples:o,scrubVars:s,req:t,sessionStore:e.sessionStore,observationStore:e.observationStore,resumeStamper:e.coordinator.resumeStamper,logPath:e.logPath,planActions:e.actions,planDigest:e.planDigest}))}function Tl(e){let t=e.positionals??[],n=Ee(t[0]);if(n)return n;if(t.length!==0)return t.join(` `)}function El(e){if(e.ok||e.error.code!==`REPLAY_DIVERGENCE`)return!1;let t=e.error.details?.divergence,n=t&&typeof t==`object`?t.kind:void 0;return typeof n==`string`&&n!==`action-failure`}function Dl(e){return e.get()?.snapshotDiagnostics?.samples.length??0}function Ol(e,t){return e.get()?.snapshotDiagnostics?.samples.slice(t)??[]}function kl(e){let t=Me(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return Ml(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function Al(e,t){return t===`ios`?Nl(e)??{}:{}}function jl(e,t){let n=kl(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function Ml(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!m(e))}function Nl(e){let t=Sr(e);return t?{appleSimulatorAppTarget:t}:void 0}function Pl(e){let{req:t,sessionName:n,metadata:r,resolvedPath:i}=e,a=t.flags??{},o={AD_SESSION:n,AD_FILENAME:Fl(t,i)};return Ll(o,`AD_PLATFORM`,a.platform??r.platform),Ll(o,`AD_TARGET`,a.target??r.target),Ll(o,`AD_DEVICE`,a.device),Ll(o,`AD_DEVICE_ID`,Il(a)),Rl(o,`AD_SHARD_INDEX`,a.shardIndex),Rl(o,`AD_SHARD_COUNT`,a.shardCount),Ll(o,`AD_ARTIFACTS`,a.artifactsDir),o}function Fl(e,t){let n=e.meta?.cwd??process.cwd();return P.relative(n,t)||t}function Il(e){return typeof e.serial==`string`?e.serial:e.udid}function Ll(e,t,n){typeof n==`string`&&n.length>0&&(e[t]=n)}function Rl(e,t,n){typeof n==`number`&&(e[t]=String(n))}const zl=3e4,Bl=1e3;function Vl(t){let{scriptPath:r,env:i,publicNetworkOnly:a}=t,o=F.readFileSync(r,`utf8`),s=Object.create(null);try{Yn.runInNewContext(o,Hl(i,s,a),{filename:r,timeout:zl})}catch(t){let i=n(t);throw new e(i.code,`Maestro runScript failed: ${i.message}`,f({...i.details??{},hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,retriable:i.retriable,supportedOn:i.supportedOn,scriptPath:r}),t instanceof Error?t:void 0)}return Yl(s,r),Object.fromEntries(Object.entries(s).map(([e,t])=>[`output.${e}`,Xl(t)]))}function Hl(e,t,n){return{...e,output:t,json:Ul,http:{post:(e,t)=>Gl(`POST`,e,n,t)}}}function Ul(t){if(typeof t!=`string`)throw new e(`COMMAND_FAILED`,`Maestro runScript json() expected a string body, received ${typeof t}.`);if(t.trim().length===0)throw new e(`COMMAND_FAILED`,`Maestro runScript json() received an empty body.`,{hint:`Check the preceding HTTP response status and setup server output.`});try{return JSON.parse(t,Wl)}catch(n){throw new e(`COMMAND_FAILED`,`Maestro runScript json() could not parse response body: ${n instanceof Error?n.message:String(n)}`,{bodyPreview:t.slice(0,Bl)},n instanceof Error?n:void 0)}}function Wl(e,t){return e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t}function Gl(t,n,r,i){let a=yt(process.execPath,Kl(),{stdin:JSON.stringify(Jl(t,n,i,r)),timeoutMs:zl,allowFailure:!0});if(a.exitCode!==0)throw new e(`COMMAND_FAILED`,`Maestro runScript http.${t.toLowerCase()} failed for ${n}: ${Zl(a.stderr)}`,{exitCode:a.exitCode,stderr:a.stderr});try{return JSON.parse(a.stdout)}catch(r){throw new e(`COMMAND_FAILED`,`Maestro runScript http.${t.toLowerCase()} returned invalid JSON for ${n}`,{stdout:a.stdout.slice(0,Bl),stderr:a.stderr.slice(0,Bl)},r instanceof Error?r:void 0)}}function Kl(){let t=ql(import.meta.url);if(!t)throw new e(`COMMAND_FAILED`,`Maestro runScript http helper entrypoint is unavailable; rebuild the package`);return t.endsWith(`.ts`)?[`--experimental-strip-types`,t]:[t]}function ql(e){try{let t=qn(e),n=P.extname(t)||`.js`;return[P.join(P.dirname(t),`run-script-http-child`+n),P.join(P.dirname(t),`internal`,`run-script-http-child`+n)].find(e=>F.existsSync(e))??null}catch{return null}}function Jl(e,t,n,r){return{method:e,url:t,headers:n?.headers??{},body:n?.body??``,publicNetworkOnly:r}}function Yl(t,n){for(let r of Object.keys(t))if(r.includes(`.`))throw new e(`INVALID_ARGS`,`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:n,key:r})}function Xl(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function Zl(e){let t=e.trim();return t.length>0?t.slice(0,Bl):`request process exited without stderr`}async function Ql(e){return await $l(`tap`,async t=>{let n=P.join(t,`before.png`),r=P.join(t,`after.png`),i=await tu(e,n);return await e.run({matchesCurrent:async()=>{if(!(!i||!await tu(e,r)))return await eu(n,r,e.signal,`tap`)}})})}async function $l(e,t){let n=await Un.mkdtemp(P.join(Kn.tmpdir(),`agent-device-maestro-${e}-`));try{return await t(n)}finally{try{await Un.rm(n,{recursive:!0,force:!0})}catch{}}}async function eu(e,t,n,r){try{let[i,a]=await Promise.all([Un.readFile(e),Un.readFile(t)]);Y(n);let o=await Bn(i,a,`Maestro screenshot`);return Y(n),nu(o,r)}catch(e){iu(e,n),O({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:r,result:`error`,error:e instanceof Error?e.message:String(e)}});return}}async function tu(e,t){try{return await Un.rm(t,{force:!0}),Y(e.signal),await e.capture(t),Y(e.signal),!0}catch(t){return iu(t,e.signal),!1}}function nu(e,t){if(e.status!==`compared`)return ru(t,e.status,e),!1;let n=e.differencePercent<=K.animationDifferencePercent;return ru(t,n?`stable`:`changed`,e),n}function ru(e,t,n){O({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:e,result:t,first:n.first,second:n.second,...`differencePercent`in n?{differencePercent:n.differencePercent}:{}}})}function iu(e,n){if(n?.aborted||t(e))throw c()}function Y(e){if(e?.aborted)throw c()}async function au(e){su(e.timeoutMs),Y(e.signal);let t=e.now()+e.timeoutMs;return await $l(`animation`,async n=>{let r=P.join(n,`first.png`),i=P.join(n,`second.png`);for(;;){if(Y(e.signal),await ou(e,r,i))return!0;if(e.now()>=t)return!1}})}async function ou(e,t,n){let r=[await tu(e,t),await tu(e,n)];return!r[0]||!r[1]?!1:await eu(t,n,e.signal,`animation`)===!0}function su(t){if(!Number.isFinite(t)||t<0)throw new e(`INVALID_ARGS`,`waitForAnimationToEnd timeout must be a non-negative number.`)}const cu=K.observationPollMs;async function lu(e,t){for(;;){X(e.context.signal);try{return await e.snapshot(e.context)}catch(n){if(!Tu(n)||(X(e.context.signal),!await Cu(e.dependencies,t,cu,e.context.signal)))throw n}}}function uu(e){return du({...e,mode:e.query.purpose===`swipe`?`swipe`:`tap`})}function du(e){let t=Dn(e.snapshot),n=e.platform===`ios`?Vn(e.snapshot.nodes):void 0,r=n?{...e.snapshot,nodes:l(n.nodes)}:e.snapshot;return gu(ts(e.snapshot,e.query,e.platform,{interactiveBounds:e.mode===`tap`,presentation:n?{snapshot:r,presentedIndexesBySourceIndex:n.presentedIndexesBySourceIndex}:void 0}),e.snapshot,e.context.generation,t,e.query,e.platform,e.mode)}async function fu(e){wu(e.timeoutMs,`observation`);let t,n=e.dependencies.now()+e.timeoutMs;for(;;){X(e.context.signal);let r=await lu(e,n),i=du({query:{selector:e.condition.selector},context:e.context,snapshot:r,platform:e.platform,mode:`observe`});if(t=i,oo(e.condition,i))return i;if(e.dependencies.now()>=n)break;await Cu(e.dependencies,n,cu,e.context.signal)}return X(e.context.signal),Ou(t)}async function pu(e){wu(e.timeoutMs,`scrollUntilVisible`);let t=e.dependencies.now()+e.timeoutMs,n,r;for(;;){X(e.context.signal);let i=r??await lu(e,t);if(r=void 0,n=du({query:{selector:e.selector},context:e.context,snapshot:i,platform:e.platform,mode:`observe`}),n.visiblePercentage===K.scrollUntilVisiblePercentage)return n;if(e.dependencies.now()>=t)break;let a=t-e.dependencies.now();a>0&&(r=await e.scroll(a,i))}return X(e.context.signal),Ou(n)}async function mu(e){wu(e.timeoutMs,`waitForAnimationToEnd`);let t=e.dependencies.now()+e.timeoutMs,n=e.initialSnapshot??await lu(e,t),r=Eu(n);for(;;){X(e.context.signal),await Cu(e.dependencies,t,cu,e.context.signal);let i=await lu(e,t),a=Eu(i);if(a===r)return{snapshot:i,signature:a,settled:!0};if(n=i,r=a,e.dependencies.now()>=t)return{snapshot:n,signature:r,settled:!1}}}function hu(e){return e?{x:0,y:0,width:e.referenceWidth,height:e.referenceHeight}:void 0}function gu(e,t,n,r,i,a,o){if(!e.ok){let t=hu(r);return{generation:n,matched:e.evidence.matched,visible:e.evidence.visible,candidateCount:e.evidence.candidateCount,...e.evidence.ref?{ref:e.evidence.ref}:{},...t?{viewport:t}:{}}}let s=vu({query:i,platform:a,mode:o,dispatchCandidates:e.dispatchCandidates}),c=hu(r);return{generation:n,matched:!0,visible:!0,...c?{visiblePercentage:_u(e.rect,c)}:{},candidateCount:e.evidence.candidateCount,rect:e.rect,...e.evidence.ref?{ref:e.evidence.ref}:{},...c?{viewport:c}:{},...s?{dispatchSelector:s}:{},...i.includeSurfaceSignature?{surfaceSignature:Eu(t)}:{}}}function _u(e,t){return!D(e)||!D(t)?0:se(t,e)?100:Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))*100/(e.width*e.height)}function vu(e){let{query:t,platform:n,mode:r,dispatchCandidates:i}=e;if(!(!yu(t,n,r)||i!==1))return bu(t.selector)}function yu(e,t,n){return t===`ios`&&n===`tap`&&e.allowAtomicSelectorDispatch===!0&&!ns(e.selector)}function bu(e){let t=Object.entries(e).filter(([,e])=>e!==void 0);if(t.length!==1)return;let[n,r]=t[0];if(!xu(n)||typeof r!=`string`)return;let i=aa(r)?.trim();return i?{key:n,value:i}:void 0}function xu(e){return e===`id`||e===`label`||e===`text`}async function Su(e,t,n){try{await e.sleep(t,n)}catch(e){throw n?.aborted?c():e}X(n)}async function Cu(e,t,n,r){let i=t-e.now();return i<=0?!1:(await Su(e,Math.min(n,i),r),!0)}function X(e){if(e?.aborted)throw c()}function wu(t,n){if(!Number.isFinite(t)||t<0)throw new e(`INVALID_ARGS`,`${n} timeout must be a non-negative number.`)}function Tu(t){return t instanceof e&&t.details?.retriable===!0}function Eu(e){return Gn(`sha256`).update(JSON.stringify([...e.nodes].sort((e,t)=>e.index-t.index).map(e=>({index:e.index,parentIndex:e.parentIndex,identifier:e.identifier??``,label:e.label??``,value:e.value??``,enabled:e.enabled??!1,selected:e.selected??!1,focused:e.focused??!1,bounds:Du(e.rect)})))).digest(`hex`)}function Du(e){if(e)return{left:Math.trunc(e.x),top:Math.trunc(e.y),right:Math.trunc(e.x+e.width),bottom:Math.trunc(e.y+e.height)}}function Ou(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Maestro observation completed without a snapshot result.`)}function ku(e){return e.kind===`clearState`?Pu(e):Au(e)?ju(e):Yu(e)?Xu(e):e.kind===`settingsPermission`?Hu(e):Uu(e)}function Au(e){return e.kind===`launchApp`||e.kind===`stopApp`||e.kind===`openLink`}function ju(e){switch(e.kind){case`launchApp`:return Mu(e);case`stopApp`:return Nu(e);case`openLink`:return Fu(e)}}function Mu(e){return{command:`open`,positionals:e.appId?[e.appId]:[],flags:{...e.relaunch?{relaunch:!0}:{},...e.clearState?{clearAppState:!0}:{},...e.launchArgs.length>0?{launchArgs:e.launchArgs}:{}}}}function Nu(e){return{command:`close`,positionals:e.appId?[e.appId]:[],dispatch:{closeAppOnly:!0}}}function Pu(e){return{command:`settings`,positionals:e.appId?[`clear-app-state`,e.appId]:[`clear-app-state`]}}function Fu(e){return{command:`open`,positionals:e.appId?[e.appId,e.link]:[e.link],...e.prewarmRunner?{flags:{maestro:{prewarmRunnerBeforeOpen:!0}}}:{}}}const Iu={camera:`camera`,microphone:`microphone`,photos:`photos`,contacts:`contacts`,notifications:`notifications`,calendar:`calendar`,location:`location`,medialibrary:`media-library`,"media-library":`media-library`,motion:`motion`,reminders:`reminders`,siri:`siri`},Lu={allow:`grant`,deny:`deny`,unset:`reset`},Ru={location:{always:{state:`grant`,permission:`location-always`},inuse:{state:`grant`,permission:`location`},never:{state:`deny`,permission:`location`}},photos:{limited:{state:`grant`,permission:`photos`,mode:`limited`}}};function zu(t){let n=Object.entries(t).map(([e,t])=>[e.toLowerCase(),t]);if(n.length===0)throw new e(`INVALID_ARGS`,`Maestro setPermissions requires at least one permission.`);return[...n.filter(([e])=>e===`all`),...n.filter(([e])=>e!==`all`)].map(([e,t])=>Bu(e,t))}function Bu(t,n){let r=t===`all`?`all`:Vu(Iu,t);if(r===void 0)throw new e(`UNSUPPORTED_OPERATION`,`Maestro permission "${t}" is not supported.`,{hint:`Supported: all, ${Object.keys(Iu).join(`, `)}.`});let i=Ru[t],a=i?Vu(i,n):void 0;if(a)return a;let o=Vu(Lu,n);if(o)return{state:o,permission:r};throw new e(`INVALID_ARGS`,`Maestro permission "${t}" does not accept "${n}".`,{hint:`Use ${[`allow`,`deny`,`unset`,...Object.keys(i??{})].join(`|`)}.`})}function Vu(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function Hu(e){return{command:`settings`,positionals:[`permission`,e.state,e.permission,...e.mode?[e.mode]:[]],...e.appId?{dispatch:{settingsAppBundleId:e.appId}}:{}}}function Uu(e){switch(e.kind){case`gestureViewport`:return{command:`runtime`,positionals:[`gesture-viewport`]};case`typeText`:return{command:`type`,positionals:[e.text]};case`clickSelector`:return Wu(e);case`clickPoint`:return Gu(e);case`swipe`:return Ku(e);case`scroll`:return qu(e);case`pressKey`:return Ju(e)}}function Wu(e){return{command:`click`,positionals:[`${e.selector.key}=${JSON.stringify(e.selector.value)}`],flags:{...e.options,maestro:{allowNonHittableCoordinateFallback:!0,expectedTapPoint:e.expectedPoint}}}}function Gu(e){return{command:`click`,positionals:[String(e.point.x),String(e.point.y)],flags:{...e.options}}}function Ku(e){let{from:t,to:n,durationMs:r}=e.gesture;return{command:`gesture`,positionals:[],input:{kind:`pan`,origin:t,delta:{x:n.x-t.x,y:n.y-t.y},durationMs:r},flags:{postGestureStabilization:!1},dispatch:{gestureExecutionProfile:`endpoint-hold`,...e.viewport?{gestureViewport:e.viewport}:{}}}}function qu(e){return{command:`scroll`,positionals:[e.direction],...e.durationMs===void 0?{}:{input:{direction:e.direction,durationMs:e.durationMs}},flags:{postGestureStabilization:!1}}}function Ju(e){return e.key===`back`||e.key===`home`?{command:e.key,positionals:[]}:{command:`keyboard`,positionals:[e.key]}}function Yu(e){return e.kind===`screenshot`||e.kind===`snapshot`}function Xu(e){switch(e.kind){case`screenshot`:return{command:`screenshot`,positionals:[e.path],...e.stabilize===!1||e.captureBackend===`runner`?{flags:{...e.stabilize===!1?{screenshotNoStabilize:!0}:{},...e.captureBackend===`runner`?{maestro:{screenshotCaptureBackend:`runner`}}:{}}}:{}};case`snapshot`:return{command:`snapshot`,positionals:[],flags:{noRecord:!0},dispatch:{observationOnly:!0}}}}async function Zu(t,n){let r=ku(n),i=await t.invoke(f({...r,flags:Qu(t.flags,r.flags??{})}));if(!i.ok)throw id(i);if(n.kind===`gestureViewport`){let t=i.data?.viewport;if(typeof t!=`object`||!t||![`x`,`y`,`width`,`height`].every(e=>typeof t[e]==`number`))throw new e(`COMMAND_FAILED`,`runtime gesture-viewport returned no valid viewport.`);return t}return i.data}function Qu(e,t){let n=e?.maestro===void 0&&t.maestro===void 0?void 0:{...e?.maestro,...t.maestro},r=f({...e,...t,maestro:n});return Object.keys(r).length>0?r:void 0}function $u(e){return e?e.kind===`scalar`?[String(e.value)]:e.kind===`list`?e.values.map(String):Object.entries(e.values).flatMap(([e,t])=>[e,String(t)]):[]}function ed(e,t){return{generation:t.generation,matched:t.matched&&t.visible,candidateCount:t.candidateCount,evidence:{kind:`selector`,selector:e,visible:t.visible,candidateCount:t.candidateCount,...t.ref?{ref:t.ref}:{}}}}function td(e){if(!e)return[];let t=[];if(typeof e.path==`string`&&t.push(e.path),Array.isArray(e.artifactPaths)&&t.push(...e.artifactPaths.filter(e=>typeof e==`string`)),Array.isArray(e.artifacts))for(let n of e.artifacts)typeof n.localPath==`string`?t.push(n.localPath):typeof n.path==`string`&&t.push(n.path);return[...new Set(t)]}function nd(t,n,r){if(P.isAbsolute(t))return t;let i=n.source?.path??r;if(!i)throw new e(`INVALID_ARGS`,`Maestro runScript file paths require a source path.`);return P.resolve(P.dirname(i),t)}function rd(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function id(t){let n=t.error,r=f({...n.details??{},hint:n.hint??ad(n.details,`hint`),diagnosticId:n.diagnosticId??ad(n.details,`diagnosticId`),logPath:n.logPath??ad(n.details,`logPath`),retriable:n.retriable??od(n.details,`retriable`),supportedOn:n.supportedOn??ad(n.details,`supportedOn`)});return new e(n.code,n.message,Object.keys(r).length?r:void 0)}function ad(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function od(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}function sd(t){let n,r,i,a,o,s=0,c=0,l=async r=>{c+=1;let i=await Zu(t,{kind:`snapshot`});if(!i||!Array.isArray(i.nodes))throw new e(`COMMAND_FAILED`,`Maestro snapshot did not return node data.`);let a=y(i,i);return n={generation:r.generation,snapshot:a},a};return{capture:async e=>{if(r?.generation===e.generation){let t=r.snapshot;return r=void 0,n={generation:e.generation,snapshot:t},t}return r=void 0,await l(e)},bindObservation:e=>{if(n?.generation!==e.generation)return e;let t=`maestro-observation-${++s}`;return n.observationIdentity=t,{...e,identity:t}},reuseObservation:e=>{if(e.cachedObservation?.generation===e.generation&&e.cachedObservation.identity!==void 0&&n?.generation===e.generation&&e.cachedObservation.identity===n.observationIdentity)return n.snapshot},readMetrics:()=>({hierarchyCaptures:c}),invalidate:e=>{i=n?.generation===e-1?{generation:e,snapshot:n.snapshot}:void 0,n=void 0,r=void 0},requireStability:e=>{o=e,a=i?.generation===e?i:void 0,i=void 0,r=void 0},consumeStabilityFromVisualWait:t=>{if(o!==void 0){if(o!==t.generation)throw new e(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${t.generation}.`);o=void 0,a=void 0,i=void 0,r=void 0}},prime:(e,t)=>{r={generation:e,snapshot:t}},settlePending:async i=>{if(o===void 0)return;if(o!==i.generation)throw new e(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${i.generation}.`);let s=n?.generation===i.generation?n.snapshot:a?.snapshot,c=await mu({timeoutMs:K.settleTimeoutMs,context:i,snapshot:l,dependencies:t.dependencies,...s?{initialSnapshot:s}:{}});return o=void 0,a=void 0,r={generation:i.generation,snapshot:c.snapshot},c}}}async function cd(e){let{input:t,context:n,snapshots:r,options:i}=e,a=i.dependencies.now()+t.timeoutMs,o=e.allowObservationReuse===!1?void 0:r.reuseObservation(n);for(;;){let e=i.dependencies.now(),s=o!==void 0;o??=await lu({context:n,snapshot:r.capture,dependencies:i.dependencies},a);let c=uu({query:t,context:n,snapshot:o,platform:i.platform});if(md(c,s))return c;if(o=void 0,!s){if(e>=a)return c;await Cu(i.dependencies,a,cu,n.signal)}}}async function ld(e,t,n,r,i,a){let o=async()=>await fd(e,t,r,i,a.click);if(!a.retryIfNoChange){try{await o()}finally{t.requireStability(i.generation)}return}if(e.platform===`ios`){await Ql({signal:i.signal,capture:async t=>{n.screenshotCaptures+=1,await Zu(e,{kind:`screenshot`,path:t,stabilize:!1,captureBackend:`runner`})},run:async o=>await ud(e,t,n,r,i,a.click,o)});return}await ud(e,t,n,r,i,a.click)}async function ud(e,t,n,r,i,a,o){let s=async()=>await fd(e,t,r,i,a),c=r.resolution?.surfaceSignature??(o?void 0:Eu(await t.capture(i))),l=async()=>{let r=await mu({timeoutMs:K.settleTimeoutMs,context:i,snapshot:t.capture,dependencies:e.dependencies});return r.settled?n.settleLatches+=1:n.settleTimeouts+=1,r};try{let e=await dd({baselineSignature:c,screenshotBaseline:o,dispatch:s,settle:l,onRetry:()=>{n.tapRetries+=1}});t.prime(i.generation,e.snapshot)}catch(e){throw t.requireStability(i.generation),e}}async function dd(e){await e.dispatch();let t=await e.settle(),n=1;for(;(e.baselineSignature===void 0||t.signature===e.baselineSignature)&&n<K.retryTapMaxAttempts&&!(e.screenshotBaseline&&await e.screenshotBaseline.matchesCurrent()!==!0);)e.onRetry(),await e.dispatch(),n+=1,t=await e.settle();return t}async function fd(e,t,n,r,i){let a=n.resolution,o=a?.dispatchSelector;if(o&&n.point){t.invalidate(r.generation);try{await hd(e,o,n.point,i);return}catch(n){if(!gd(n))throw n;let o=await cd({input:a.query,context:r,snapshots:t,options:e,allowObservationReuse:!1});if(!pd(o))throw n;t.invalidate(r.generation),await _d(e,kt(o.rect),i);return}}t.invalidate(r.generation),await _d(e,n.point,i)}function pd(e){return e.matched&&e.visible&&e.rect!==void 0}function md(e,t){return pd(e)?!t||e.dispatchSelector!==void 0:!1}async function hd(e,t,n,r){O({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`selector`,selectorKey:t.key,expectedPoint:n}}),await Zu(e,{kind:`clickSelector`,selector:t,expectedPoint:n,options:r})}function gd(e){let t=r(e);return t.code===`AMBIGUOUS_MATCH`||t.code===`ELEMENT_NOT_FOUND`||t.code===`ELEMENT_OFFSCREEN`||t.details?.reason===ht.selectorNotFound}async function _d(t,n,r){if(!n)throw new e(`COMMAND_FAILED`,`Maestro target did not resolve to a point.`);O({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`point`,point:n}}),await Zu(t,{kind:`clickPoint`,point:n,options:r})}function vd(e){return`${e.state} ${e.permission}${e.mode?` ${e.mode}`:``}`}function yd(t){let n=sd(t),r={screenshotCaptures:0,tapRetries:0,settleLatches:0,settleTimeouts:0},i=e=>{e.settled?r.settleLatches+=1:r.settleTimeouts+=1},a=t.platform,o=e=>(e.kind===`screenshot`&&(r.screenshotCaptures+=1),Zu(t,e)),s=async(e,t,r=`none`)=>{n.invalidate(t.generation);try{return await e()}finally{r===`deferred`&&n.requireStability(t.generation)}},c=async(e,t,n=`none`)=>await s(()=>o(e),t,n),l=async(t,n,r)=>{let i=[];for(let a of n){try{await c({kind:`settingsPermission`,...t?{appId:t}:{},state:a.state,permission:a.permission,...a.mode?{mode:a.mode}:{}},r)}catch(t){throw t instanceof e?new e(t.code,t.message,{...t.details,appliedPermissionMutations:i,failedPermissionMutation:vd(a)}):t}i.push(vd(a))}},u=async(e,r)=>{vt(e),await c({kind:`typeText`,text:e},r);let a=await mu({timeoutMs:K.settleTimeoutMs,context:r,snapshot:n.capture,dependencies:t.dependencies});i(a),n.prime(r.generation,a.snapshot)};return{operations:{platform:a,resolveTarget:async(e,r)=>await cd({input:e,context:r,snapshots:n,options:t}),observe:async(e,r)=>await fu({condition:e.condition,timeoutMs:e.timeoutMs,context:r,snapshot:n.capture,dependencies:t.dependencies,platform:a}),resolveGestureViewport:async()=>await o({kind:`gestureViewport`}),launchApp:async(e,t)=>{let n=e.appId??t.appId,r=[...$u(e.arguments),...$u(e.launchArguments)],i=e.clearState===!0,a=!i&&e.stopApp!==!1;if(e.permissions){let r=zu(e.permissions);i&&await c({kind:`clearState`,...n?{appId:n}:{}},t),await l(n,r,t)}await c({kind:`launchApp`,...n?{appId:n}:{},relaunch:a,clearState:i&&!e.permissions,launchArgs:r},t,`deferred`)},stopApp:async(e,t)=>{let n=e.appId??t.appId;await c({kind:`stopApp`,...n?{appId:n}:{}},t)},setPermissions:async(e,t)=>{await l(e.appId??t.appId,zu(e.permissions),t)},clearState:async(e,t)=>{let n=e.appId??t.appId;await c({kind:`clearState`,...n?{appId:n}:{}},t)},openLink:async(e,t)=>{await c({kind:`openLink`,...t.appId?{appId:t.appId}:{},link:e.link,prewarmRunner:a===`ios`},t,`deferred`)},tapOn:async(e,i)=>await ld(t,n,r,e.target,i,{click:{count:e.repeat,intervalMs:e.delay},retryIfNoChange:e.retryTapIfNoChange===!0}),doubleTapOn:async(e,n)=>{await s(()=>_d(t,e.target.point,f({doubleTap:!0,intervalMs:e.delay})),n,`deferred`)},longPressOn:async(e,n)=>{await s(()=>_d(t,e.target.point,{holdMs:K.longPressDurationMs}),n,`deferred`)},gesture:async(e,t)=>{let n=await c({kind:`swipe`,gesture:e,...t.gestureViewport?{viewport:t.gestureViewport}:{}},t,`deferred`);return n?{data:n}:void 0},inputText:async(e,t)=>await u(e.text,t),eraseText:async(e,t)=>await u(`\b`.repeat(e.charactersToErase??K.eraseTextMaxCharacters),t),scroll:async(e,t)=>{await c({kind:`scroll`,direction:e.direction},t,`deferred`)},scrollUntilVisible:async(e,r)=>{let i=await pu({selector:e.selector,direction:e.direction,timeoutMs:e.timeoutMs,context:r,snapshot:n.capture,dependencies:t.dependencies,platform:a,scroll:async(i,o)=>{let s=go(o,e.selector,e.direction,e.durationMs,a);return await c(s?{kind:`swipe`,...s}:{kind:`scroll`,direction:e.direction,durationMs:e.durationMs},r),(await mu({timeoutMs:Math.min(K.settleTimeoutMs,i),context:r,snapshot:n.capture,dependencies:t.dependencies})).snapshot}});if(i.visiblePercentage!==K.scrollUntilVisiblePercentage)throw mi(`Maestro scrollUntilVisible target did not become visible.`,{selector:e.selector,timeoutMs:e.timeoutMs});return{observation:n.bindObservation(ed(e.selector,i))}},pressKey:async(e,t)=>{await c({kind:`pressKey`,key:e.key},t,`deferred`)},back:async(e,t)=>{await c({kind:`pressKey`,key:`back`},t,`deferred`)},hideKeyboard:async(e,t)=>{await c({kind:`pressKey`,key:`dismiss`},t,`deferred`)},waitForAnimationToEnd:async(e,n)=>({visualStabilityReached:await au({timeoutMs:e.timeoutMs??K.animationWaitTimeoutMs,now:t.dependencies.now,signal:n.signal,capture:async e=>{await o({kind:`screenshot`,path:e,stabilize:!1,...t.platform===`ios`?{captureBackend:`runner`}:{}})}})}),takeScreenshot:async e=>({artifactPaths:td(await o({kind:`screenshot`,path:e.path}))}),runScript:async(e,n)=>({outputEnv:Vl({scriptPath:nd(e.file,n,t.sourcePath),publicNetworkOnly:t.publicNetworkOnly,env:{...n.env,...e.env?rd(e.env):{}}})})},snapshots:n,readMetrics:()=>({...n.readMetrics(),...r}),recordSettle:i}}function bd(e){let{operations:t,snapshots:n,readMetrics:r,recordSettle:i}=yd(e);return ls(t,{beforeExecute:async({context:e,requiresSettledPredecessor:t})=>{if(t){let t=await n.settlePending(e);t&&i(t)}},afterExecute:({context:e,visualStabilityReached:t})=>{t&&n.consumeStabilityFromVisualWait(e)},bindObservation:n.bindObservation,readMetrics:r})}function xd(e){let{filePath:t,tracePath:n,onStep:r}=e,i=new Map;return{actionStarted:e=>{i.set(e.stepIndex,e),Sd(()=>Td(r,e)),Sd(()=>Ed(n,t,e))},actionCompleted:e=>{let r=Cd(i,e.stepIndex);Sd(()=>Dd(n,t,wd(r,e),!0))},actionFailed:e=>{let r=Cd(i,e.stepIndex);Sd(()=>Dd(n,t,wd(r,e),!1))}}}function Sd(e){try{e()}catch{}}function Cd(e,t){let n=e.get(t);return e.delete(t),n}function wd(e,t){return f({...e??t,durationMs:t.durationMs,runtimeMetrics:t.runtimeMetrics,data:`data`in t?t.data:void 0,error:`error`in t?t.error:void 0})}function Td(e,t){e?.({index:t.stepIndex,total:t.stepTotal,command:t.action,...t.value?{value:t.value}:{}})}function Ed(e,t,n){jc(e,{type:`replay_action_start`,ts:new Date().toISOString(),replayPath:t,...n.source.path&&n.source.path!==t?{sourcePath:n.source.path}:{},line:n.source.line,step:n.stepIndex,command:n.action,positionals:n.value?[n.value]:[]})}function Dd(t,n,r,i){let a=Od(r);jc(t,{type:`replay_action_stop`,ts:new Date().toISOString(),replayPath:n,...r.source.path&&r.source.path!==n?{sourcePath:r.source.path}:{},line:r.source.line,step:r.stepIndex,command:r.action,ok:i,durationMs:r.durationMs,...Object.keys(a).length>0?{resultTiming:a}:{},...!i&&`error`in r&&r.error instanceof e?{errorCode:r.error.code}:{}})}function Od(e){let t=`data`in e?e.data:void 0,n=kd(t?.timing)?t.timing:void 0;return f({...e.runtimeMetrics??{},...typeof n?.executionProfile==`string`?{executionProfile:n.executionProfile}:{},...typeof n?.gestureDurationMs==`number`?{gestureDurationMs:n.gestureDurationMs}:{}})}function kd(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ad(e,t){let n=f({...e.dispatch,...jd(t.dispatch)});return f({...e,command:t.command,positionals:t.positionals,input:t.input,flags:t.flags,dispatch:Object.keys(n).length>0?n:void 0})}function jd(e){return f({closeAppOnly:e?.closeAppOnly,observationOnly:e?.observationOnly,gestureViewport:e?.gestureViewport,gestureExecutionProfile:e?.gestureExecutionProfile,settingsAppBundleId:e?.settingsAppBundleId})}function Md(e,t){let n={command:e.action,...e.value?{value:e.value}:{}};return{command:{kind:e.action},source:e.source,progress:n,action:{command:Id(e.action),positionals:Ld(e.action,e.value),flags:t.flags??{}}}}async function Nd(e){let{failure:t,replayPath:n,req:r,sessionStore:i,observationStore:a,logPath:o}=e,s=j(r.meta?.requestId),c=Md(t,r),l=Sc(e.error),u=[...t.redactions],d=wt(u),f={...l,message:d(l.message),...l.hint?{hint:d(l.hint)}:{}},p=a.get(),m=p?await sc({session:p,observationStore:a,logPath:o,action:c.action}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},h=p&&m.state===`available`&&!t.isControl?Pd({failure:t,action:c.action,session:p,nodes:m.nodes,sanitize:d}):[],g=[t.action,Fd(t.value)].filter(Boolean).join(` `),_=Zs({sessionStore:i,observationStore:a,divergence:{version:1,kind:`action-failure`,step:{index:t.stepIndex,source:{path:d(t.source.path??n),line:t.source.line}},action:d(g),cause:{code:f.code,message:f.message,...f.hint?{hint:f.hint}:{}},screen:dc(m,d),suggestions:h.slice(0,5),suggestionCount:h.length,resume:t.resume,repairHint:Gs({kind:`action-failure`,targetEvidence:void 0,capture:ac(m)})},responseLevel:r.meta?.responseLevel,evidence:m.state===`available`?m.evidence:void 0,...s?{signal:s}:{}});return wc({error:f,actionLabel:g,action:t.action,positionals:[...c.action.positionals],step:t.stepIndex,replayPath:n,artifactPaths:[...t.artifactPaths],snapshotDiagnostics:e.snapshotDiagnostics,divergence:_,scrubVars:u,warnings:t.warnings})}function Pd(e){let t={createdAt:Date.now(),nodes:e.nodes};return nc(Za(e.failure,t).map(({node:e,basis:t})=>({node:e,nodeIndex:e.index,basis:t}))).map(({node:t,basis:n})=>xc({node:t,nodes:e.nodes,session:e.session,action:e.action,basis:n,sanitize:e.sanitize}))}function Fd(e){return!e||e===`<text>`?e??``:Le(e)}function Id(e){return e===`tapOn`||e===`doubleTapOn`?`click`:e===`longPressOn`?`longpress`:e===`assertVisible`||e===`assertNotVisible`||e===`extendedWaitUntil`||e===`scrollUntilVisible`?`wait`:e}function Ld(e,t){return!t||e===`inputText`?[]:[t]}function Rd(e){let{command:t,outcome:n,startedAt:r,snapshotStart:i}=e,{session:{name:a,store:o}}=t,s=Bd(o,i),c=n.replayed;return{ok:!0,data:{replayed:c,healed:0,session:a,sessionActive:o.get()!==void 0,artifactPaths:n.artifactPaths,...n.warnings?{warnings:n.warnings}:{},...s?{snapshotDiagnostics:s}:{},message:Vd(c,Date.now()-r)}}}async function zd(e){let{command:t,replayPath:r,state:i,outcome:a}=e,{request:o,session:{store:s,observationStore:c,logPath:l}}=t,{failure:u}=a,d=n(a.error);return u?await Nd({error:d,failure:u,replayPath:r,req:o,sessionStore:s,observationStore:c,logPath:l,snapshotDiagnostics:Bd(s,i.snapshotStart)}):{ok:!1,error:d}}function Bd(e,t){let n=e.get()?.snapshotDiagnostics?.samples.slice(t)??[];return g(n)}function Vd(e,t){return`Replayed ${e} ${e===1?`step`:`steps`} in ${(t/1e3).toFixed(1)}s`}async function Hd(e){let{request:t}=e,n=t.flags?.replayScriptSource;if(!n)return u(`INVALID_ARGS`,us);if(t.flags?.saveScript!==void 0)return u(`INVALID_ARGS`,`Maestro YAML does not support --save-script; ADR 0012 repair recording applies only to .ad scripts.`);let r=Date.now(),i={snapshotStart:0};try{return await Ud({command:e,bundle:n,startedAt:r,state:i})}catch(t){return await zd({command:e,replayPath:n.entry,state:i,outcome:{ok:!1,error:t}})}}async function Ud(e){let{command:t,bundle:n,startedAt:r,state:i}=e,{request:a,session:{store:o},tracePath:s,onStep:c}=t,l=await Wd({command:t,bundle:n}),u=t.publicNetworkOnly===!0,d=Zd({command:t,device:l.device,platform:l.platform,runtimeHints:l.runtimeHints,sourcePath:l.filePath,publicNetworkOnly:u});i.snapshotStart=o.get()?.snapshotDiagnostics?.samples.length??0;let f=await Xa(l.flow,d,{defaults:l.defaults,env:l.env,platform:l.platform,target:l.target,runtimeHints:l.runtimeHints,signal:l.signal,from:a.flags?.replayFrom,planDigest:a.flags?.replayPlanDigest,trustedScripts:!u,readSource:e=>q(n,e),observer:xd({filePath:l.filePath,tracePath:s,onStep:c})});return f.ok?Rd({outcome:f,command:t,startedAt:r,snapshotStart:i.snapshotStart}):await zd({command:t,replayPath:n.entry,state:i,outcome:f})}async function Wd(e){let{command:t,bundle:n}=e,{request:r,session:{name:i,store:a}}=t,o=n.entry,s=Ya(q(n,o),o),c=a.lookup(),l=c?.session;c&&a.assertSelectorMatches(r.flags);let u=await Gd({req:r,sessionStore:a,sessionName:i,session:l,flow:s});return{filePath:o,flow:s,...u,defaults:Yd({req:r,sessionName:i,filePath:o,platform:u.platform,target:u.target}),env:Xd(r),signal:j(r.meta?.requestId)}}async function Gd(e){let{req:t,sessionStore:n,sessionName:r,session:i,flow:a}=e,o=t.flags?.platform,s=i?.device??(o===`android`||o===`ios`?void 0:await En(t.flags??{},Al(a.appTarget,o))),c=nf(t,s),l=qd({req:t,sessionStore:n,sessionName:r,device:s,platform:c});return await Kd({req:t,sessionStore:n,sessionName:r,device:s,platform:c,target:rf(t,s),runtimeHints:l,flow:a})}async function Kd(e){if(e.device||!Jd(e.runtimeHints))return e;let t=await En(e.req.flags??{},Al(e.flow.appTarget,e.platform));return{device:t,platform:e.platform,target:rf(e.req,t),runtimeHints:qd({req:e.req,sessionStore:e.sessionStore,sessionName:e.sessionName,device:t,platform:e.platform})}}function qd(e){return e.sessionStore.resolveOpenRuntimeHints({request:e.req,device:e.device,platform:e.platform})}function Jd(e){return e?.metroPort!==void 0&&e.metroHost===void 0&&e.bundleUrl===void 0}function Yd(e){return{...Pl({req:e.req,sessionName:e.sessionName,metadata:{},resolvedPath:e.filePath}),AD_PLATFORM:e.platform,AD_TARGET:e.target}}function Xd(e){return{...$e(Ze(e.flags?.replayShellEnv)),...tt(Ye(e.flags?.replayEnv))}}function Zd(e){let{command:t,device:n,platform:r,runtimeHints:i,sourcePath:a,publicNetworkOnly:o}=e,{request:s,invoke:c}=t,l={...s,runtime:i,...t.dispatch?{dispatch:t.dispatch}:{}};return bd({invoke:e=>c(Ad(l,e)),flags:Qd(n,r,s.flags),publicNetworkOnly:o,platform:r,sourcePath:a,dependencies:{now:Date.now,sleep:async(e,t)=>{await Jn(e,void 0,{signal:t})}}})}function Qd(e,t,n){if(!e)return $d(t,n);let r={platform:t,target:e.target,noRecord:!0};return t===`android`?{...r,serial:e.id}:{...r,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}}}function $d(e,t){let n={platform:e,target:t?.target??`mobile`,noRecord:!0};return t?.device&&(n.device=t.device),e===`android`?ef(n,t):tf(n,t)}function ef(e,t){return t?.serial&&(e.serial=t.serial),t?.androidDeviceAllowlist&&(e.androidDeviceAllowlist=t.androidDeviceAllowlist),e}function tf(e,t){return t?.udid&&(e.udid=t.udid),t?.iosSimulatorDeviceSet&&(e.iosSimulatorDeviceSet=t.iosSimulatorDeviceSet),e}function nf(t,n){let r=t.flags?.platform;if(r===`android`||r===`ios`)return r;if(n?.platform===`android`)return`android`;if(n?.platform===`apple`&&n.appleOs===`ios`)return`ios`;throw new e(`INVALID_ARGS`,`Maestro replay requires --platform android|ios or an active mobile session.`)}function rf(e,t){return typeof e.flags?.target==`string`?e.flags.target:t?.target??`mobile`}async function af(e){let{resolved:t,keepSession:n,coordinator:r,command:i}=e,{request:a}=i;if(et(t,a.flags?.replayBackend)===`maestro`)return n?u(`INVALID_ARGS`,`--keep-session is supported only for native .ad replay; Maestro YAML owns its lifecycle.`):r.view()?.repairBoundary===void 0?await Hd(i):u(`INVALID_ARGS`,`This session has an active .ad --save-script repair run; finish it with replay --from or close before running Maestro YAML.`)}function of(e){let{req:t,sessionName:n,sessionStore:r,tracePath:i,resolved:a,script:o,coordinator:s,dispatch:c}=e,l=sf(t);if(l)return{ok:!1,response:l};let{manifest:u,replayReq:d}=cf(t,o,c),{metadata:f,actions:p,actionLines:m,actionSourcePaths:h,planDigest:g}=u,_=r.get(),v=lf({req:t,coordinator:s,manifest:u,preEntrySession:_});return v.ok?{ok:!0,value:{replayReq:d,actions:p,actionLines:m,actionSourcePaths:h,planDigest:g,preEntrySession:_,entryIndex:v.value,varSources:df({req:t,replayReq:d,sessionName:n,resolved:a,metadata:f}),actionTracePath:i??_?.trace?.outPath}}:{ok:!1,response:v.response}}function sf(e){if(e.flags?.replayBackend&&e.flags.replayBackend!==`maestro`)return u(`INVALID_ARGS`,`Unsupported replay backend "${e.flags.replayBackend}".`)}function cf(e,t,n){let r=ys(t,{platform:e.flags?.platform,target:e.flags?.target});return{manifest:r,replayReq:uf({...e,flags:jl(e.flags,r.actions),...n?{dispatch:n}:{}},r.metadata)}}function lf(e){let{req:t,coordinator:n,manifest:r,preEntrySession:i}=e,a=r.resolveEntryIndex({from:t.flags?.replayFrom,digest:t.flags?.replayPlanDigest,pendingRecordAndHeal:n.view()?.pendingRecordAndHeal,sessionActionsLength:i?.actions.length??0});return a.ok?{ok:!0,value:a.value}:{ok:!1,response:u(`INVALID_ARGS`,a.message)}}function uf(e,t){return!t.platform&&!t.target?e:{...e,flags:ff(e.flags,t)}}function df(e){let{req:t,replayReq:n,sessionName:r,resolved:i,metadata:a}=e;return{builtins:Pl({req:n,sessionName:r,metadata:a,resolvedPath:i}),fileEnv:a.env,shellEnv:$e(Ze(t.flags?.replayShellEnv)),cliEnv:tt(Ye(t.flags?.replayEnv))}}function ff(e,t){return{...e??{},...t.platform!==void 0&&e?.platform===void 0?{platform:t.platform}:{},...t.target!==void 0&&e?.target===void 0?{target:t.target}:{}}}const pf={kind:`none`,status:void 0,targetPath:void 0,targetForce:!1};function mf(e){let{req:t,entryIndex:n,sessionStore:r,sourcePath:i,coordinator:a}=e,o=hf({entryIndex:n,sessionStore:r,coordinator:a});return o?{ok:!1,response:o}:(vf({req:t,coordinator:a}),_f({req:t,sessionStore:r,sourcePath:i,coordinator:a}))}function hf(e){let t=yf(e);if(t)return t;if(e.entryIndex>0&&!e.sessionStore.get())return d()}function gf(e){let{saveScript:t,force:n,preRunState:r,sourcePath:i}=e;return t&&r.kind===`authoring`?u(`INVALID_ARGS`,`replay --save-script cannot re-arm an ordinary recording in terminal/active state ${r.status}. Close this session and use a fresh one for repair authoring.`):bf({saveScript:t,liveForce:n,persistedForce:r.targetForce||void 0,sourcePath:i,existingSaveScriptPath:r.targetPath})}function _f(e){let{req:t,sourcePath:n,coordinator:r}=e,{saveScript:i,force:a}=t.flags??{},o=gf({saveScript:i,force:a,preRunState:r.view()?.scriptPublication??pf,sourcePath:n});return o?{ok:!1,response:o}:(r.demoteForRerunIfArmed(),{ok:!0,armSaveScript:xf({saveScript:i,force:a,coordinator:r,sourcePath:n})})}function vf(e){let{req:t,coordinator:n}=e;n.clearCorrectiveWatermarkIfExpected(t.flags?.replayFrom),t.flags?.saveScript&&n.clearTombstone()}function yf(e){let{entryIndex:t,coordinator:n}=e;if(!(t>0)&&n.view()?.repairBoundary!==void 0)return u(`INVALID_ARGS`,`This session has an active --save-script repair run; continue it with replay --from <n> --plan-digest <sha256>, or finish with close, before starting a fresh full replay.`)}function bf(e){let{saveScript:t,liveForce:n,persistedForce:r,sourcePath:i,existingSaveScriptPath:a}=e;if(!t)return;let o=typeof t==`string`?Ot(t):a??Vs(i);if(!(n||r&&o===a)&&F.existsSync(o))return u(`COMMAND_FAILED`,`A file already exists at ${o}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`)}function xf(e){let{saveScript:t,force:n,coordinator:r,sourcePath:i}=e;if(!t)return()=>{};let a=!0;return()=>{r.armStep({saveScript:t,force:n,sourcePath:i,firstArm:a}),a=!1}}async function Sf(e){let{request:t,session:{name:n,logPath:i,store:a,observationStore:o,coordinator:s},tracePath:c,onStep:l,invoke:d}=e,f=t.flags?.replayScriptSource;if(!f)return u(`INVALID_ARGS`,us);let p=Date.now(),m=t.flags?.replayKeepSession===!0,h=``,g=new Set;try{if(h=f.entry,nt(h)&&t.flags?.replayBackend!==`maestro`)return u(`INVALID_ARGS`,Qe(`replay`,h));let r=await af({resolved:h,keepSession:m,coordinator:s,command:e});if(r)return r;let _=of({req:t,sessionName:n,sessionStore:a,tracePath:c,resolved:h,script:q(f,h),coordinator:s,dispatch:e.dispatch});if(!_.ok)return _.response;let{replayReq:v,actions:y,actionLines:b,actionSourcePaths:x,planDigest:S,entryIndex:C,varSources:w,actionTracePath:ee}=_.value,te=mf({req:t,entryIndex:C,sessionStore:a,sourcePath:h,coordinator:s});if(!te.ok)return te.response;let{runtime:T,readLastResponse:ne}=Sl({ctx:{replayReq:v,sessionName:n,sessionStore:a,observationStore:o,logPath:i,resolved:h,actions:y,actionLines:b,actionSourcePaths:x,planDigest:S,actionTracePath:ee,responseLevel:t.meta?.responseLevel,invoke:d,signal:j(t.meta?.requestId),coordinator:s,resolvedSessionScope:e.resolvedSessionScope,dependencies:e.dependencies},req:t,artifactPaths:g,onStep:l,armSaveScript:te.armSaveScript}),E=await js({actions:y,entryIndex:C,keepSession:m,actionLines:b,actionSourcePaths:x,resolvedPath:h,varSources:w},T);return E.status===`failed`?ne()??u(`COMMAND_FAILED`,`replay step failed with no recorded response`):Cf({startedAt:p,sessionName:n,sessionStore:a,replayed:E.replayed,artifactPaths:E.artifactPaths,snapshotDiagnosticSamples:E.snapshotDiagnosticSamples,armSaveScript:te.armSaveScript,coordinator:s,keepSession:m})}catch(e){let t=r(e);return u(t.code,t.message,g.size>0?{artifactPaths:[...g]}:void 0)}}function Cf(e){let{startedAt:t,sessionName:n,sessionStore:r,replayed:i,artifactPaths:a,snapshotDiagnosticSamples:o,armSaveScript:s,coordinator:c,keepSession:l}=e;s(),c.markCompleteIfArmed();let u=r.get(),d=Tf({keepSession:l,sessionName:n,completedSession:u,artifactPaths:a});if(d)return d;let f=g([...o]);return{ok:!0,data:{replayed:i,healed:0,session:n,sessionActive:u!==void 0,artifactPaths:[...a],...f?{snapshotDiagnostics:f}:{},message:wf(i,Date.now()-t)}}}function wf(e,t){let n=(t/1e3).toFixed(1);return`Replayed ${e} ${e===1?`step`:`steps`} in ${n}s`}function Tf(e){let{keepSession:t,sessionName:n,completedSession:r,artifactPaths:i}=e;if(!(!t||r))return u(`COMMAND_FAILED`,`Replay completed but --keep-session could not preserve session "${n}". Run the script again after checking which action closed the session.`,i.length>0?{artifactPaths:[...i]}:void 0)}function Ef(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=P.resolve(n??`.`,t??`.agent-device/test-artifacts`);return P.join(i,r)}function Df(e,t){let n=t?P.relative(t,e):P.basename(e),r=n.length===0||n.startsWith(`..`)?P.basename(e):n;return Te(r.toLowerCase().replaceAll(/[\\/]+/g,`__`).replaceAll(/[^a-z0-9._-]+/g,`-`))||`test`}function Of(e,t){F.mkdirSync(t,{recursive:!0}),jf(e,t)}function kf(e){let{outcome:t,filePath:n,sessionName:r,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=t.status===`passed`,c=new Set(t.artifactPaths);t.status===`failed`&&typeof t.error.logPath==`string`&&c.add(t.error.logPath);let l=P.join(o,`result.txt`),u=P.join(o,`failure.txt`),d=Af([...c],o,[l,u]),f=[`file: ${n}`,`session: ${r}`,`attempt: ${i}/${a}`,`status: ${s?`passed`:`failed`}`];t.status===`passed`?f.push(`replayed: ${t.replayed}`,`healed: ${t.healed}`):(f.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&f.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&f.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&f.push(`logPath: ${t.error.logPath}`),t.error.details?.reason===`timeout`&&f.push(`timeoutMode: cooperative`)),d.length>0&&f.push(`copiedArtifacts: ${d.map(e=>P.basename(e)).join(`, `)}`);let p=`${f.join(`
|
|
2
|
+
`)}\n`;F.writeFileSync(l,p),s||F.writeFileSync(u,p)}function Af(e,t,n){let r=[],i=new Set(n.map(e=>P.basename(e).toLowerCase()));for(let n of e){if(!Nf(n))continue;let e=P.basename(n);if(P.resolve(n)===P.resolve(t,e)&&!i.has(e.toLowerCase())){r.push(n);continue}let a=Mf(e,t,i),o=P.join(t,a);F.copyFileSync(n,o),r.push(o)}return r}function jf(e,t){let n=P.join(t,`replay.ad`);if(F.copyFileSync(e,n),P.extname(e).toLowerCase()===`.ad`)return;let r=P.join(t,P.basename(e));P.resolve(r)!==P.resolve(n)&&F.copyFileSync(e,r)}function Mf(e,t,n){let r=P.extname(e),i=r?e.slice(0,-r.length):e,a=e,o=2;for(;n.has(a.toLowerCase())||F.existsSync(P.join(t,a));)a=`${i}-${o++}${r}`;return a}function Nf(e){try{return F.statSync(e).isFile()}catch{return!1}}function Pf(t){let{platformFilter:n,discoverSources:r}=t,i=r(),a=[];for(let e of i){let{path:t,manifest:r}=e,i={kind:`run`,path:t,title:r.title,manifest:r};if(!n){a.push(i);continue}let o=r.device.platform;if(o.kind===`caller-bound`){a.push(i);continue}if(o.kind===`unspecified`){a.push({kind:`skip`,path:t,reason:`skipped-by-filter`,message:`missing platform metadata for --platform ${n}`});continue}Bf(n,o.value)&&a.push(i)}if(a.filter(e=>e.kind===`run`).length===0){let t=n?` for --platform ${n}`:``;throw new e(`INVALID_ARGS`,`No replay tests matched${t}.`)}return a}function Ff(e,t,n,r,i=0){let a=P.basename(n,P.extname(n)),o=Te(a.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`));return`${e}:test:${t}:${r+1}${o?`-${o}`:``}:attempt-${i+1}`}function If(e){let t=e?.trim()||`${process.pid}-${Date.now().toString(36)}`;return Te(t.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`))||`suite`}function Lf(e){let{requestId:t,suiteInvocationId:n,filePath:r,caseIndex:i,attemptIndex:a,shardIndex:o}=e;return[t??n,...o===void 0?[]:[`shard`,o+1],`test`,i+1,P.basename(r),`attempt`,a+1].join(`:`)}function Rf(e,t){return typeof e==`number`?e:t}function zf(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function Bf(e,t){return e===`apple`?S(t):t===e}function Vf(e){return{status:`failed`,error:e.error,artifactPaths:e.artifactPaths??[],warnings:e.warnings??[],infrastructure:e.infrastructure??!1,...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}const Hf=2e3;async function Uf(e){let{filePath:t,sessionName:r,requestId:i,parentRequestId:a,timeoutMs:o,platform:s,target:c,artifactsDir:l,shard:u,onStep:d,runReplay:f,cleanupSession:p,finalizeAttempt:m,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=g({attemptId:i,parentAttemptId:a}),v=new Set,y,b=!1,x,S=Date.now(),C=Xf({artifactsDir:l,artifactPaths:v,filePath:t,sessionName:r,requestId:i,timeoutMs:o,platform:s,target:c}),w=f({filePath:t,sessionName:r,platform:s,target:c,requestId:i,artifactsDir:l,artifactPaths:v,tracePath:C,appendTimingEvent:e=>Z(C,e),shard:u,onStep:d}).catch(e=>Vf({error:n(e)})).finally(()=>{_.release()});try{x=typeof o==`number`?await Promise.race([w,new Promise(e=>{y=setTimeout(()=>{b=!0,_.cancel(),e(Zf(o,[...v]))},o)})]):await w,Z(C,{type:`replay_test_attempt_stop`,ts:new Date().toISOString(),session:r,ok:x.status===`passed`,timedOut:b,durationMs:Date.now()-S,errorCode:x.status===`passed`?void 0:x.error.code})}finally{y&&clearTimeout(y),b&&(await Gf(w)||(x=Jf(x),h({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:r,requestId:i,graceMs:Hf}}),Kf({replayPromise:w,cleanupSession:p,sessionName:r,requestId:i,emitDiagnostic:h})));let e=await qf({finalizeAttempt:m,sessionName:r,artifactPaths:v,artifactsDir:l,tracePath:C,emitDiagnostic:h});x?.status===`passed`&&e&&(x=Yf(x,`Replay test finalization failed: ${e.error.message}`));let t=Date.now();try{Z(C,{type:`replay_test_cleanup_start`,ts:new Date().toISOString(),session:r}),await p(r),Z(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!0,durationMs:Date.now()-t})}catch(e){let i=n(e);Z(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-t,errorCode:i.code}),h({level:`warn`,phase:`test_cleanup_failed`,data:{session:r,error:i.message}}),x=Wf(x,i,v)}}return x??Vf({error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}})}function Wf(e,t,n){return e?.status===`failed`?{...e,infrastructure:!0}:Vf({error:t,artifactPaths:[...n],infrastructure:!0})}async function Gf(e){return await Promise.race([e.then(()=>!0),Jn(Hf).then(()=>!1)])}async function Kf(e){let{replayPromise:t,cleanupSession:r,sessionName:i,requestId:a,emitDiagnostic:o}=e;try{await t}finally{try{await r(i)}catch(e){o({level:`warn`,phase:`test_late_cleanup_failed`,data:{session:i,requestId:a,error:n(e).message}})}}}async function qf(e){let{finalizeAttempt:t,sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o,emitDiagnostic:s}=e;if(!t)return;let c=Date.now();Z(o,{type:`replay_test_finalize_start`,ts:new Date().toISOString(),session:r});try{let e=await t({sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o,appendTimingEvent:e=>Z(o,e)});return Z(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:e===void 0,durationMs:Date.now()-c,errorCode:e?.error.code}),e}catch(e){let t=n(e);return Z(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-c,errorCode:t.code}),s({level:`warn`,phase:`test_finalize_failed`,data:{session:r,error:t.message}}),Vf({error:t})}}function Jf(e){return!e||e.status===`passed`?e:{...e,infrastructure:!0,error:{...e.error,details:{...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0}}}}function Yf(e,t){return{...e,warnings:[...e.warnings,t]}}function Xf(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=P.join(t,`replay-timing.ndjson`);return F.mkdirSync(P.dirname(l),{recursive:!0}),F.writeFileSync(l,``),n.add(l),Z(l,{type:`replay_test_attempt_start`,ts:new Date().toISOString(),replayPath:r,session:i,requestId:a,timeoutMs:o,platform:s,target:c}),l}function Z(e,t){e&&F.appendFileSync(e,`${JSON.stringify(t)}\n`)}function Zf(e,t=[]){return Vf({artifactPaths:t,error:{code:`COMMAND_FAILED`,message:`TIMEOUT after ${e}ms`,hint:`Replay test timeouts are cooperative; the active command may take a short grace period to stop.`,details:{reason:`timeout`,timeoutMs:e,timeoutMode:`cooperative`,artifactPaths:t}}})}async function Qf(e){let t=$f(e),n=await ep(e,t);return{result:op(e,t,n),infrastructure:n.finalOutcome?.status===`failed`&&n.finalOutcome.infrastructure}}function $f(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:P.join(i,...a?[`shard-${a.shardIndex+1}`]:[],Df(t.path,n)),maxAttempts:r+1}}async function ep(e,t){np(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!e.isCanceled();r+=1){let i=await tp(e,t,r);if(rp(n,i),ip(e,i.outcome,r))break;ap(e,t,i)}return n}async function tp(e,t,n){let{entry:r,sessionName:i,suiteInvocationId:a,caseIndex:o,suiteIndex:s,suiteTotal:c,requestId:l,timeoutMs:u,shard:d}=e,f=n+1,p=Date.now(),m=Ff(i,a,r.path,o,n),h=P.join(t.testArtifactsDir,`attempt-${f}`);Of(r.path,h);let g=Lf({requestId:l,suiteInvocationId:a,filePath:r.path,caseIndex:o,attemptIndex:n,shardIndex:d?.shardIndex}),_={file:r.path,title:r.title,index:s,total:c,attempt:f,maxAttempts:t.maxAttempts,session:m,artifactsDir:t.testArtifactsDir,...Q(d)},v=await Uf({filePath:r.path,sessionName:m,requestId:g,parentRequestId:l,timeoutMs:u,platform:r.manifest.device.platform.kind===`declared`?r.manifest.device.platform.value:void 0,target:r.manifest.device.target,artifactsDir:h,shard:d,onStep:t=>{e.emitProgress({type:`replay-test`,..._,status:`progress`,stepIndex:t.index,stepTotal:t.total,...t.command===void 0?{}:{stepCommand:t.command},...t.value===void 0?{}:{stepValue:t.value}})},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt,emitDiagnostic:e.emitDiagnostic,bindAttemptCancellation:e.bindAttemptCancellation}),y=Date.now()-p;return kf({outcome:v,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{outcome:v,sessionName:m,attempt:f,durationMs:y}}function np(e,t){let{entry:n,sessionName:r,suiteInvocationId:i,caseIndex:a,suiteIndex:o,suiteTotal:s,shard:c}=e;e.emitProgress({type:`replay-test`,file:n.path,title:n.title,status:`start`,index:o,total:s,maxAttempts:t.maxAttempts,session:Ff(r,i,n.path,a),artifactsDir:t.testArtifactsDir,...Q(c)})}function rp(e,t){e.finalOutcome=t.outcome,e.finalSessionName=t.sessionName,e.attempts=t.attempt,e.finalAttemptDurationMs=t.durationMs,t.outcome.status!==`passed`&&e.attemptFailures.push({attempt:t.attempt,message:t.outcome.error.message,durationMs:t.durationMs})}function ip(e,t,n){return t.status===`passed`||e.isCanceled()||t.infrastructure||n>=e.retries}function ap(e,t,n){n.outcome.status!==`passed`&&e.emitProgress({type:`replay-test`,file:e.entry.path,title:e.entry.title,status:`fail`,index:e.suiteIndex,total:e.suiteTotal,attempt:n.attempt,maxAttempts:t.maxAttempts,durationMs:n.durationMs,retrying:!0,message:n.outcome.error.message,hint:n.outcome.error.hint,session:n.sessionName,artifactsDir:t.testArtifactsDir,...Q(e.shard)})}function op(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalOutcome?.status===`passed`?sp(e,t,n,r):cp(e,t,n,r)}function sp(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome;if(c?.status!==`passed`)throw Error(`Expected passing replay test outcome.`);return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`pass`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,...Q(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`passed`,durationMs:r,finalAttemptDurationMs:n.finalAttemptDurationMs,attempts:n.attempts,artifactsDir:t.testArtifactsDir,replayed:c.replayed,healed:c.healed,...c.warnings.length>0?{warnings:[...c.warnings]}:{},...c.snapshotDiagnostics?{snapshotDiagnostics:c.snapshotDiagnostics}:{},...up(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function cp(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome,l=c?.status===`failed`?c.error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`};return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`fail`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,message:l.message,hint:l.hint,...Q(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`failed`,durationMs:r,attempts:n.attempts,artifactsDir:t.testArtifactsDir,error:l,...lp(c),...up(s)}}function lp(e){let t=e?.status===`failed`?e:void 0;return{...t&&t.warnings.length>0?{warnings:[...t.warnings]}:{},...t?.infrastructure?{infrastructure:!0}:{},...e?.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}function up(e){return Q(e)}function Q(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function dp(e,t,n,r){if(!e||t.length===0)return;let i=await r(e.count);return{mode:e.kind,shardCount:e.count,total:n+(e.kind===`all`?t.length*e.count:t.length),shards:i.map((n,r)=>({shardIndex:r,shardCount:e.count,device:n,entries:e.kind===`all`?t:t.filter((t,n)=>n%e.count===r)}))}}async function fp(e){let{request:t,runReplay:n,cleanupSession:i,finalizeAttempt:a,emitProgress:o,isCanceled:s,emitDiagnostic:c,bindAttemptCancellation:l,discoverSources:u,resolveShardTargets:d}=e,f=t.sessionName;if(t.inputs.length===0)return{status:`failed`,error:{code:`INVALID_ARGS`,message:`test requires at least one path or glob`}};try{let e=Date.now(),r=await pp(t,u,d);_p(r,o);let p=r.shardPlan?vp({entries:r.entries,total:r.total,emitProgress:o}):[];return r.shardPlan?p.push(...await yp({shards:r.shardPlan.shards,sessionName:f,suiteInvocationId:r.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:r.suiteArtifactsDir,suiteTotal:r.total,runReplay:n,cleanupSession:i,finalizeAttempt:a,emitProgress:o,isCanceled:s,emitDiagnostic:c,bindAttemptCancellation:l})):p.push(...await Cp({discoveryEntries:r.entries,sessionName:f,suiteInvocationId:r.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:r.suiteArtifactsDir,suiteTotal:r.total,runReplay:n,cleanupSession:i,finalizeAttempt:a,emitProgress:o,isCanceled:s,emitDiagnostic:c,bindAttemptCancellation:l})),{status:`completed`,data:Ep(r.total,p,Date.now()-e,r.suiteArtifactsDir)}}catch(e){let t=r(e);return{status:`failed`,error:{code:t.code,message:t.message}}}}async function pp(e,t,n){let r=mp(e,t),i=hp(r),a=r.length-i.length,o=If(e.requestId),s=await dp(e.shard?{kind:e.shard.mode,count:e.shard.count}:void 0,i,a,n);return{entries:r,runnable:i,shardPlan:s,suiteInvocationId:o,suiteArtifactsDir:gp(e,o),total:s?.total??r.length}}function mp(e,t){return Pf({platformFilter:e.platformFilter,discoverSources:t})}function hp(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function gp(e,t){return Ef({artifactsDir:typeof e.artifactsDir==`string`?e.artifactsDir:void 0,cwd:e.cwd,suiteInvocationId:t})}function _p(e,t){t({type:`replay-test-suite`,status:`start`,total:e.total,runnable:e.runnable.length,skipped:e.entries.length-e.runnable.length,artifactsDir:e.suiteArtifactsDir,shardMode:e.shardPlan?.mode,shardCount:e.shardPlan?.shardCount})}function vp(e){let{entries:t,total:n}=e,r=[];for(let[i,a]of t.entries())a.kind===`skip`&&(e.emitProgress({type:`replay-test`,file:a.path,status:`skip`,index:i+1,total:n,message:a.message}),r.push({file:a.path,status:`skipped`,durationMs:0,reason:a.reason,message:a.message}));return r}async function yp(e){return(await Promise.allSettled(e.shards.map(async t=>await xp({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[bp(r,e.sessionName,t.reason)]:[]})}function bp(e,t,r){let i=n(r);return{file:e.entries[0]?.entry.path??`shard-${e.shardIndex+1}`,session:Sp(t,e),status:`failed`,durationMs:0,attempts:1,error:{code:i.code,message:i.message,hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,details:i.details},shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}}async function xp(e){let{shard:t,sessionName:n}=e;return await wp({...e,entries:t.entries,sessionName:Sp(n,t),shard:t})}function Sp(e,t){return`${e}:shard-${t.shardIndex+1}`}async function Cp(e){let{discoveryEntries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h}=e,g=[],_=0;for(let[e,v]of t.entries()){if(p())break;if(v.kind===`skip`){f({type:`replay-test`,file:v.path,status:`skip`,index:e+1,total:c,message:v.message}),g.push({file:v.path,status:`skipped`,durationMs:0,reason:v.reason,message:v.message});continue}_+=1;let t=await Qf({entry:v,sessionName:n,suiteInvocationId:r,caseIndex:_-1,cwd:i,requestId:a,retries:zf(o.retries,v.manifest.attemptDefaults?.retries),timeoutMs:Rf(o.timeoutMs,v.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h});if(g.push(t.result),Tp(t,o,p))break}return g}async function wp(e){let{entries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=[];for(let[e,v]of t.entries()){if(m())break;let{entry:t,suiteIndex:y}=v,b=await Qf({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:zf(o.retries,t.manifest.attemptDefaults?.retries),timeoutMs:Rf(o.timeoutMs,t.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:y,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g});if(_.push(b.result),Tp(b,o,m))break}return _}function Tp(e,t,n){return n()||t.failFast===!0&&e.result.status===`failed`||e.infrastructure}function Ep(e,t,n,r){let i=t.filter(e=>e.status===`passed`).length,a=t.filter(e=>e.status===`failed`),o=a.length,s=t.filter(e=>e.status===`skipped`).length,c=i+o,l=v(t.map(e=>e.status===`skipped`?void 0:e.snapshotDiagnostics));return{total:e,executed:c,passed:i,failed:o,skipped:s,notRun:Math.max(0,e-c-s),durationMs:n,failures:a,tests:t,artifactsDir:r,...l?{snapshotDiagnostics:l}:{}}}function Dp(e,t){return()=>e.map(e=>Op(e,t))}function Op(e,t){let n=e.entry,r=q(e,n),i=et(n,t)===`maestro`,a=Re(r);return{path:n,manifest:{...i?{title:Ya(r,n).name}:{},device:{platform:a.platform?{kind:`declared`,value:a.platform}:i?{kind:`caller-bound`}:{kind:`unspecified`},...a.target===void 0?{}:{target:a.target}},...a.timeoutMs!==void 0||a.retries!==void 0?{attemptDefaults:{...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.retries===void 0?{}:{retries:a.retries}}}:{}}}}function kp(e){return async t=>(await Mp(e,t)).map(Ap)}function Ap(t){if(t.platform===`web`||!x(t))throw new e(`INVALID_ARGS`,`test sharding requires a mobile device; ${t.id} is ${t.platform}`);return{id:t.id,name:t.name,platform:t.platform,...t.target===void 0?{}:{target:t.target}}}function jp(e,t){if(!t)return e;let n={...e??{},device:void 0,udid:void 0,serial:void 0,platform:t.device.platform,target:t.device.target,shardAll:void 0,shardSplit:void 0,shardCount:t.shardCount,shardIndex:t.shardIndex};return t.device.platform===`android`?{...n,serial:t.device.id}:{...n,udid:t.device.id}}async function Mp(t,n){let r=Ip(t),i=Pp(await Tn(Np(t)),r,t);if(i.length<n)throw new e(`DEVICE_NOT_FOUND`,`test sharding requires ${Fp(n)}, but only ${i.length} matched`);return i.slice(0,n)}function Np(e){let t=Cn(e?.androidDeviceAllowlist);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:te({simulatorSetPath:wn(e?.iosSimulatorDeviceSet),platform:e?.platform,target:e?.target}),androidSerialAllowlist:t?Array.from(t).sort():void 0}}function Pp(e,t,n){return t.length>0?Lp(e,t,n):e.filter(e=>Rp(e,n)).sort(Vp)}function Fp(e){return`${e} device${e===1?``:`s`}`}function Ip(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function Lp(t,n,r){return n.map(n=>{let i=Bp(n),a=t.find(e=>zp(e,r)&&(e.id===n||Bp(e.name)===i));if(!a)throw new e(`DEVICE_NOT_FOUND`,`No shard device matched ${n}`);return a})}function Rp(e,t){return!zp(e,t)||!x(e)?!1:e.booted!==!1}function zp(e,t){return!(!ee(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function Bp(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}function Vp(e,t){return e.id.localeCompare(t.id)}function Hp(t){let n=Up(t?.shardAll,`--shard-all`),r=Up(t?.shardSplit,`--shard-split`);if(n!==void 0&&r!==void 0)throw new e(`INVALID_ARGS`,`--shard-all and --shard-split are mutually exclusive`);if(n!==void 0)return{mode:`all`,count:n};if(r!==void 0)return{mode:`split`,count:r}}function Up(t,n){if(t!==void 0){if(typeof t!=`number`||!Number.isInteger(t)||t<1)throw new e(`INVALID_ARGS`,`${n} requires a positive integer`);return t}}const Wp=new Set([`IOS_BOOT_TIMEOUT`,`IOS_RUNNER_CONNECT_TIMEOUT`,`IOS_RUNNER_OWNED_BY_OTHER_DAEMON`,`IOS_TOOL_MISSING`,`ANDROID_BOOT_TIMEOUT`,`ADB_TRANSPORT_UNAVAILABLE`,`CI_RESOURCE_STARVATION_SUSPECTED`]);function Gp(e){return Wp.has(e.toUpperCase())}const Kp=[`failed to start daemon`,`runner did not accept connection`,`xcodebuild exited early`,`device is offline`,`device offline`,`device unauthorized`];function qp(e){if(!(`ok`in e)&&e.status===`failed`&&e.infrastructure===!0)return!0;let t=Jp(e);return t?Yp(t.details)||Xp(t.code,t.message):!1}function Jp(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function Yp(e){if(e?.recovery===`runner_recycle_budget_exhausted`)return!0;let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`||_t(t)?!0:t?Gp(t):!1}function Xp(e,t){let n=`${e}\n${t}`.toLowerCase();return Kp.some(e=>n.includes(e))}function Zp(e){if(!e.ok)return{status:`failed`,error:e.error,artifactPaths:em(e.error.details?.artifactPaths),warnings:pt(e.error.details),infrastructure:qp(e),...tm(e.error.details?.snapshotDiagnostics)};let t=e.data;return{status:`passed`,replayed:typeof t?.replayed==`number`?t.replayed:0,healed:typeof t?.healed==`number`?t.healed:0,warnings:pt(t),artifactPaths:em(t?.artifactPaths),...tm(t?.snapshotDiagnostics)}}function Qp(e){if(!e||e.ok)return;let t=Zp(e);return t.status===`failed`?t:void 0}function $p(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function em(e){return[...new Set($p(e))]}function tm(e){let t=_(e);return t?{snapshotDiagnostics:t}:{}}const nm=1e3,rm=3e3;function im(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await am(e)}}async function am(e){let{req:t,sessionName:n,sessionStore:r,artifactsDir:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0)return;let o=r.get();if(!o||o.screenRecording)return;let s=St(o.device.platform),c=i?P.join(i,`recording${s}`):xt(o.device.platform);sm(a,{type:`video_recording_start`,session:n,videoPath:c}),O({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:c}}),e.video.throwIfCanceled();let l=await e.video.record(cm({req:t,sessionName:n,phase:`start`,outputPath:c}));if(!l.ok)return sm(a,{type:`video_recording_start_failed`,session:n,videoPath:c,errorCode:l.error.code}),l;let u=Date.now();return await bt(nm),sm(a,{type:`video_preroll_done`,session:n,durationMs:Date.now()-u,requestedDurationMs:nm}),O({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-u,data:{session:n,requestedDurationMs:nm}}),l}async function om(e){let{req:t,sessionName:n,sessionStore:r,artifactPaths:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0||!r.get()?.screenRecording)return;sm(a,{type:`video_tail_start`,session:n,requestedDurationMs:rm});let o=Date.now();await bt(rm);let s=Date.now(),c=await e.video.record(cm({req:t,sessionName:n,phase:`stop`}));return Rc(c).forEach(e=>i.add(e)),sm(a,{type:`video_recording_stop`,session:n,ok:c.ok,durationMs:Date.now()-s,tailDurationMs:s-o,errorCode:c.ok?void 0:c.error.code}),O({phase:`replay_test_video_recording_stop`,durationMs:Date.now()-s,data:{session:n,ok:c.ok,tailDurationMs:s-o}}),c}function sm(e,t){e({...t,ts:new Date().toISOString()})}function cm(e){let t={token:e.req.token,meta:e.req.meta};return e.phase===`start`?{request:t,sessionName:e.sessionName,phase:`start`,outputPath:e.outputPath}:{request:t,sessionName:e.sessionName,phase:`stop`}}const lm=[{keys:[`replayKeepSession`],requested:e=>e.replayKeepSession===!0,message:`test does not support --keep-session; suite attempts own their cleanup. Run one native .ad script directly with replay --keep-session.`},{keys:[`replayFrom`,`replayPlanDigest`],requested:e=>e.replayFrom!==void 0||e.replayPlanDigest!==void 0,message:`test does not support --from/--plan-digest; resume is replay-only. Run the failing script directly with replay --from.`},{keys:[`saveScript`,`force`],requested:e=>!!e.saveScript||e.force===!0,message:`test does not support --save-script/--force; the agent-supervised repair loop is replay-only. Repair the failing script directly with replay --save-script.`}],um=({attemptId:e,parentAttemptId:t})=>{Zt(e);let n=dm(e,t);return{cancel:()=>qt(e),release:()=>{n(),Xt(e)}}};function dm(e,t){if(!t||t===e)return()=>{};let n=j(t);if(!n)return()=>{};let r=()=>{qt(e)};return n.aborted?(r(),()=>{}):(n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r)})}function fm(e){let{platform:t,target:n,artifactsDir:r,shard:i,sourceBundle:a}=e,o=pm(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0&&a===void 0?o:jp({...o??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r},...a===void 0?{}:{replayScriptSource:a}},i)}function pm(e){if(!e||e.recordVideo!==!0&&e.replayScriptSources===void 0)return e;let t={...e};return delete t.recordVideo,delete t.replayScriptSources,Object.keys(t).length>0?t:void 0}async function mm(e){let{request:t,session:{name:n,logPath:i},createSession:a,invoke:o,cleanupSession:s,video:c}=e;if(t.flags?.recordVideo===!0&&c===void 0)return u(`COMMAND_FAILED`,`Screen-recording runtime is not configured for replay video capture`);let l=t.flags??{};for(let e of lm)if(e.requested(l))return u(`INVALID_ARGS`,e.message);let d,f;try{d=_m(t,n),f=gm(t)}catch(e){let t=r(e);return u(t.code,t.message)}let p=new Map(f.map(e=>[e.entry,e])),m=await fp({request:d,emitProgress:Qt,isCanceled:()=>Yt(t.meta?.requestId),emitDiagnostic:O,bindAttemptCancellation:um,runReplay:async({filePath:n,sessionName:r,platform:s,target:l,requestId:u,artifactsDir:d,artifactPaths:f,tracePath:m,appendTimingEvent:h,shard:g,onStep:_})=>{let v=e=>(f&&Rc(e).forEach(e=>f.add(e)),e),y=fm({parentFlags:t.flags,platform:s,target:l,artifactsDir:d,shard:g,sourceBundle:p.get(n)}),b=a(r,i),x=c?{req:t,sessionName:r,sessionStore:b.store,artifactsDir:d,appendTimingEvent:h,video:c}:void 0,S=x?im(x):void 0;return Zp(await Sf({...vm(e,{request:{...t,command:`replay`,session:r,positionals:[n],flags:y,meta:{...t.meta??{},...u?{requestId:u}:{}}},openLifecycle:S}),session:b,tracePath:m,onStep:_,publicNetworkOnly:e.publicNetworkOnly,invoke:async e=>{let t=x?await am(x):void 0;return t&&!t.ok?t:v(await o(e))}}))},finalizeAttempt:async({sessionName:e,artifactPaths:n,artifactsDir:r,appendTimingEvent:o})=>{if(c)return Qp(await om({req:t,sessionName:e,sessionStore:a(e,i).store,artifactsDir:r,appendTimingEvent:o,artifactPaths:n,video:c}))},discoverSources:Dp(f,t.flags?.replayBackend),resolveShardTargets:kp(t.flags),cleanupSession:s});return m.status===`completed`?{ok:!0,data:hm(m.data,t)}:u(m.error.code,m.error.message)}function hm(e,t){let n=t.meta?.clientArtifactPaths?.artifactsDir,r=e.artifactsDir;if(!n||!r)return e;let i=P.join(n,P.basename(r)),a=e=>e===r||e.startsWith(r+P.sep)?i+e.slice(r.length):e,o={...e,artifactsDir:i,tests:e.tests.map(e=>`artifactsDir`in e&&e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e),failures:e.failures.map(e=>e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e)};return F.existsSync(r)?{...o,artifacts:[{field:`artifactsDir`,artifactType:`test-artifacts`,path:r,localPath:n,fileName:P.basename(r)}]}:o}function gm(t){let n=t.flags?.replayScriptSources;if(!n)throw new e(`INVALID_ARGS`,us);return n}function _m(e,t){let n=e.flags??{},r=e.meta?.cwd,i=bm(n.artifactsDir);return{inputs:e.positionals??[],sessionName:t,cwd:r,requestId:e.meta?.requestId,platformFilter:n.platform,artifactsDir:i===void 0?void 0:Ot(i,r),failFast:n.failFast===!0,retries:ym(n.retries),timeoutMs:ym(n.timeoutMs),shard:Hp(n)}}function vm(e,t){let{publicNetworkOnly:n,resolvedSessionScope:r,dispatch:i,dependencies:a}=e,o=i||t.openLifecycle?{...i,...t.openLifecycle?{openLifecycle:t.openLifecycle}:{}}:void 0;return{request:t.request,...n?{publicNetworkOnly:n}:{},...r?{resolvedSessionScope:r}:{},...o?{dispatch:o}:{},dependencies:a}}function ym(e){return typeof e==`number`?e:void 0}function bm(e){return typeof e==`string`?e:void 0}function xm(t){let n=t.flags??{};if(n.waitMs===void 0)return;let[r]=Ae(`waitMs`);if(!r)throw new e(`INTERNAL_ERROR`,`The waitMs option has no flag declaration whose bounds the daemon can enforce.`);return p(n,`waitMs`,{min:r.min,max:r.max})}function Sm(e){let t=e.internal?.openDeviceWait?.waitedMs;return t===void 0?{}:{waitedMs:t}}function Cm(e){return{...Sm(e),offersDeviceWait:e.command===`open`&&typeof e.flags?.waitMs!=`number`}}function wm(e){let{req:t,budgetMs:n,sessionName:r,sessionStore:i,deviceId:a}=e;if(t.command===`open`&&n!==void 0&&!(a===void 0||i.get(r)))return Em({req:t,sessionName:r,sessionStore:i,deviceId:a,budgetMs:n})}function Tm(e,t,n){let r=e.findByDevice(t);if(!(!r||r.address===n))return r}function Em(e){let{req:t,sessionName:n,sessionStore:r,deviceId:i,budgetMs:a}=e,o=Dt.fromTimeoutMs(a),s=()=>Tm(r,i,n),c=async()=>{for(;;){let e=s();if(!e||o.isExpired())return;Qt({type:`command`,status:`progress`,message:`Waiting for ${e.session.device.name}: held by session "${e.address}" (${Math.round(o.elapsedMs())}ms of the ${Math.round(a)}ms wait budget used)`}),await bt(Math.min(250,o.remainingMs())),Jt(t.meta?.requestId)}};return{waitForDeviceOutsideLocks:c,runWhenDeviceIsUnheld:async e=>{let{acquireLocks:n,task:r}=e;for(;;){let e=await n(async()=>{if(s()){if(!o.isExpired())return{ran:!1};Dm(t,o.elapsedMs())}return{ran:!0,outcome:await r()}});if(e.ran)return e.outcome;await c()}}}}function Dm(e,t){if(t<=0)return;let n=e.internal??={};n.openDeviceWait={waitedMs:t}}const Om={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},$=new Map;async function km(e){let t=await I.mkdtemp(P.join(Kn.tmpdir(),`agent-device-materialized-`));try{let n=await Pm(e.installablePath,P.join(t,`installable`)),r=e.archivePath?await Pm(e.archivePath,P.join(t,`archive`)):void 0,i=Wn.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{Mm(i)},a);return $.set(i,{rootPath:t,installablePath:n,archivePath:r,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:i,installablePath:n,...r?{archivePath:r}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await I.rm(t,{recursive:!0,force:!0}),e}}async function Am(e,t){await Nm(e,tn($,e,t,Om))}async function jm(e){let t=Array.from($.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await Nm(e,t)}))}async function Mm(e){let t=$.get(e);if(t)try{await Nm(e,t)}catch{}}async function Nm(e,t){clearTimeout(t.timer),$.delete(e),await I.rm(t.rootPath,{recursive:!0,force:!0})}async function Pm(e,t){let n=await I.stat(e);await I.mkdir(t,{recursive:!0});let r=P.join(t,P.basename(e));return n.isDirectory()?(await I.cp(e,r,{recursive:!0}),r):(await I.copyFile(e,r),r)}function Fm(e){return e.device.platform===`web`}function Im(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function Lm(e){let{session:t,sessionName:n,sessionStore:r}=e;t.appLog&&await hn({session:t,sessionName:n,sessionStore:r,resourcePath:pn.resolvePath(r.resolveSessionDir(n))})}async function Rm(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.perfCapture&&await mn({...e,session:t,intent:`disposal`})}async function zm(e,t){await t.stopSnapshotHelper(e.device)}async function Bm(e){let{session:t,sessionName:n,sessionStore:r,platformCleanup:i}=e;await i.closeManagedBrowser({device:t.device,sessionName:n,stateDir:r.resolveDaemonStateDir(),openSessionNames:()=>Im(r)})}async function Vm(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function Hm(t){if(t.failures.length===0)return;let n=t.failures.map(({step:e})=>e),r=t.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return O({level:`error`,phase:t.phase,data:{session:t.sessionName,failedSteps:n,errors:r}}),new e(`COMMAND_FAILED`,`Session cleanup left ${t.failures.length} resource(s) unreleased: ${r.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:t.sessionName,failedSteps:n,hint:`Some session resources failed to release; inspect the session log for per-resource diagnostics. The session was still deleted, so retrying is safe.`})}async function Um(t){let{session:n,sessionName:r,sessionStore:i}=t;if(!t.platformCleanup)throw new e(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let a=t.platformCleanup,o=[{step:`recording`,run:()=>Wm({session:n,sessionName:r,sessionStore:i})},...t.appLog===`run`?[{step:`app_log`,run:()=>Lm({session:n,sessionName:r,sessionStore:i})}]:[],{step:`audio_probe`,run:()=>Gm({session:n,sessionName:r,sessionStore:i})},{step:`perf_capture`,run:()=>Rm({session:n,sessionName:r,sessionStore:i})},{step:`platform_snapshot_helper`,run:()=>zm(n,a)},{step:`web_browser`,run:()=>Bm({session:n,sessionName:r,sessionStore:i,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>jm(r)});let s=Hm({sessionName:r,phase:`session_teardown_cleanup_failed`,failures:await Vm(o)});if(s)throw s}async function Wm(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.screenRecording&&await Hn({intent:`disposal`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}async function Gm(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.audioProbe&&await fn({intent:`disposal`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}function Km(e){return w(e)&&e.kind===`simulator`}function qm(e){return e.platform===`android`&&e.kind===`emulator`}const Jm=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function Ym(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Xm(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function Zm(e){return nn(Xm(e))}function Qm(t,n){if(t!==void 0){if(typeof t!=`string`)throw new e(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return k(t)}}function $m(t){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(t)}. Use an integer between 1 and 65535.`);return t}}function eh(t){if(t!==void 0){if(typeof t!=`number`)throw new e(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return $m(t)}}function th(t,n,r){if(t===void 0)return r;if(!s(t))throw new e(`INVALID_ARGS`,`Invalid open runtime platform: ${String(t)}. Use "ios", "android", or "harmonyos".`);if(r&&t!==r)throw new e(`INVALID_ARGS`,`open runtime targets ${t}, but session "${n}" is bound to ${r}.`);return t}function nh(e){if(s(e))return e}function rh(e,t){return{platform:t,metroHost:k(e?.metroHost),metroPort:$m(e?.metroPort),bundleUrl:k(e?.bundleUrl),launchUrl:k(e?.launchUrl)}}function ih(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function ah(e){if(qm(e))return`10.0.2.2`;if(Km(e))return`127.0.0.1`}function oh(e,t){if(!e||k(e.metroHost)||k(e.bundleUrl)||e.metroPort===void 0)return e;let n=ah(t);return n?{...e,metroHost:n}:e}function sh(t){let{runtime:n,sessionName:r,platform:i}=t;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new e(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!Jm.includes(e));if(o)throw new e(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Jm.join(`, `)}.`);return{platform:th(a.platform,r,i),metroHost:Qm(a.metroHost,`metroHost`),metroPort:eh(a.metroPort),bundleUrl:Qm(a.bundleUrl,`bundleUrl`),launchUrl:Qm(a.launchUrl,`launchUrl`)}}function ch(e,t,n){if(n){if(Ym(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function lh(t,n,r,i){let a=t.getRuntimeHints(n);if(!a)return;let o=r?T(r):void 0,s=nh(o)??i;if(a.platform&&r&&!s)throw new e(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new e(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function uh(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?nh(T(i)):e.platform,o=n.getRuntimeHints(r),s=sh({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=lh(n,r,i,a);return{runtime:i?oh(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&Ym(s)>0?s:void 0;return{runtime:i?oh(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function dh(e){return uh(e).runtime}function fh(e){try{return{ok:!0,data:uh(e)}}catch(e){let t=r(e);return u(t.code,t.message,t.details)}}async function ph(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!mh(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:Xm(t)})}function mh(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Zm(e.previousRuntime)&&!Zm(e.runtime)}function hh(e){let{device:t,owner:n,stateDir:r,intent:i}=e,a=i.kind===`exact-owner`&&de(i.owner,n)?le(i.fence):null;if(!a)return{status:`binding-invalid`};let o=an(gn(t)),s=ln(on(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!_h(c.stateDir,r)||!de(cn(c),n)?{status:`conflict`,conflict:s}:c.allocator.identityIncarnationId===a.identityIncarnationId?{status:`covered`}:{status:`incarnation-stale`,heldIncarnationId:c.allocator.identityIncarnationId}}function gh(e){let t=an(gn(e));return rn(on(t))}function _h(e,t){return P.resolve(e)===P.resolve(t)}function vh(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=T(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=S(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${Et(i)}`,`${a} ${Et(e.id)}`,...n===`release`||sn(t.classification)?[`--stale`]:[]].join(` `)}function yh(t,n){if(n.classification===`allocator-held`)return xh(t,n);let r=n.claim,i=vh(t,n,un(n.classification)?`release`:`status`),a=T(r?{platform:r.device.family,appleOs:r.device.appleOs}:t);return new e(`DEVICE_IN_USE`,r?`${a} device ${t.id} is owned by session "${r.session}" in workspace "${r.workspace}".`:`${t.name} has an ownership claim that could not be verified.`,{reason:Oh(n.classification),classification:n.classification,deviceKey:n.deviceKey,...r?{owner:{session:r.session,workspace:r.workspace,stateDir:r.stateDir}}:{},recovery:{command:i},hint:un(n.classification)?`The recorded owner can no longer release this device; settle its resources and release the claim with: ${i}`:`Inspect the owner with: ${i}`,retriable:!1})}function bh(e,t){return Dh(yh(e,t))}function xh(t,n){let r=n.allocatorClaim,i=T({platform:r.device.family,appleOs:r.device.appleOs}),a=vh(t,n);return new e(`DEVICE_IN_USE`,`${i} device ${t.id} is held by managed-device allocator "${r.allocator.instanceId}" for installation "${r.stateDir}".`,{reason:`DEVICE_CLAIM_ALLOCATOR_HELD`,classification:n.classification,deviceKey:n.deviceKey,owner:{kind:`allocator`,stateDir:r.stateDir,allocator:r.allocator},recovery:{command:a},hint:`This device belongs to a managed pool and is released only after its allocator proves the identity removed; inspect with: ${a}`,retriable:!1})}function Sh(t,n){return new e(`COMMAND_FAILED`,`${T(t)} device ${t.id} is a managed identity with no allocator-held execution claim for this installation.`,{reason:`allocator-claim-missing`,owner:ye(n),deviceKey:an(gn(t)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function Ch(t,n,r){return new e(`COMMAND_FAILED`,`${T(t)} device ${t.id} is held for identity incarnation "${r}", which is not the incarnation this binding fences.`,{reason:`allocator-claim-incarnation-stale`,owner:ye(n),deviceKey:an(gn(t)),heldIncarnationId:r,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function wh(t,n){return new e(`COMMAND_FAILED`,`A managed local owner executes only under an exact-owner binding that carries a managed binding fence.`,{reason:`runtime-contract-invalid`,owner:ye(n),deviceKey:an(gn(t)),retriable:!1})}function Th(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:wh(e,t)};case`missing`:return{admitted:!1,error:Sh(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:Ch(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:yh(e,n.conflict)}}}function Eh(e,t,n){let r=Th(e,t,n);return r.admitted?void 0:Dh(r.error)}function Dh(e){let{hint:t,retriable:n,...r}=e.details??{};return u(e.code,e.message,r,{hint:t,retriable:n})}function Oh(e){switch(e){case`live`:return`DEVICE_CLAIM_LIVE_OWNER`;case`owner-process-dead`:case`owner-daemon-superseded`:return`DEVICE_CLAIM_RECOVERY_PENDING`;case`owner-process-reused`:case`owner-state-dir-gone`:case`unknown`:case`inconsistent`:case`allocator-inconsistent`:return`DEVICE_CLAIM_OWNER_UNCERTAIN`}}function kh(e){switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{cr as $,km as A,Vs as B,Rm as C,Im as D,Fm as E,Sf as F,xr as G,Ya as H,Nl as I,vr as J,_r as K,Al as L,Cm as M,xm as N,Am as O,mm as P,ur as Q,jl as R,Lm as S,Um as T,wr as U,q as V,Cr as W,dr as X,yr as Y,lr as Z,nh as _,yh as a,Wm as b,rh as c,ph as d,pr as et,ih as f,mh as g,ch as h,Th as i,Qn as it,wm as j,jm as k,Ym as l,Xm as m,Eh as n,nr as nt,gh as o,dh as p,gr as q,bh as r,tr as rt,hh as s,kh as t,fr as tt,Zm as u,fh as v,zm as w,Hm as x,Gm as y,kl as z};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { A as
|
|
1
|
+
import { k as Rect } from "./sdk-contracts.js";
|
|
2
|
+
import { A as MultiTouchGesturePlan, M as PointerTrajectorySample, N as SinglePointerGesturePlan, j as PointerTrajectory } from "./sdk-selectors.js";
|
|
3
3
|
import { Readable, Stream, Writable } from "node:stream";
|
|
4
4
|
//#region packages/platform-android/src/helper-artifacts.d.ts
|
|
5
5
|
type AndroidImeHelperManifest = {
|
|
@@ -114,8 +114,8 @@ type AndroidAdbProcess = {
|
|
|
114
114
|
* Runs device-scoped adb arguments after the device serial has already been selected.
|
|
115
115
|
* Implementations must be safe to call concurrently for one request.
|
|
116
116
|
*/
|
|
117
|
-
type AndroidAdbExecutor = (args: string[], options?: AndroidAdbExecutorOptions) => Promise<AndroidAdbExecutorResult>;
|
|
118
|
-
type AndroidAdbSpawner = (args: string[], options?: AndroidAdbSpawnOptions) => AndroidAdbProcess;
|
|
117
|
+
type AndroidAdbExecutor = (args: readonly string[], options?: AndroidAdbExecutorOptions) => Promise<AndroidAdbExecutorResult>;
|
|
118
|
+
type AndroidAdbSpawner = (args: readonly string[], options?: AndroidAdbSpawnOptions) => AndroidAdbProcess;
|
|
119
119
|
type AndroidPortReverseEndpoint = `tcp:${number}` | `localabstract:${string}`;
|
|
120
120
|
type AndroidPortReverseMapping = {
|
|
121
121
|
local: AndroidPortReverseEndpoint;
|
|
@@ -211,4 +211,4 @@ declare function dismissAndroidKeyboardWithAdb(adb: AndroidAdbExecutor): Promise
|
|
|
211
211
|
declare function readAndroidClipboardWithAdb(adb: AndroidAdbExecutor): Promise<string>;
|
|
212
212
|
declare function writeAndroidClipboardWithAdb(adb: AndroidAdbExecutor, text: string): Promise<void>;
|
|
213
213
|
//#endregion
|
|
214
|
-
export { readAndroidClipboardWithAdb as a, AndroidAdbExecutor as c,
|
|
214
|
+
export { readAndroidClipboardWithAdb as a, AndroidAdbExecutor as c, AndroidAdbProvider as d, AndroidPortReverseEndpoint as f, getAndroidKeyboardStatusWithAdb as i, AndroidAdbExecutorOptions as l, AndroidKeyboardState as n, writeAndroidClipboardWithAdb as o, AndroidPortReverseProvider as p, dismissAndroidKeyboardWithAdb as r, AndroidInputOwner as s, AndroidKeyboardDismissResult as t, AndroidAdbExecutorResult as u };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime.js";import{
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{D as t,F as n}from"./sdk-contracts.js";import{AsyncLocalStorage as r}from"node:async_hooks";var i=e({listDeviceInventory:()=>l,listLocalDeviceInventory:()=>d,readDeviceInventory:()=>u,readInstalledAppProbe:()=>c,shouldPropagateDeviceInventoryProbeError:()=>m,withDeviceInventoryContext:()=>s});const a=`device_inventory_context_unavailable`,o=new r;async function s(e,t){return await o.run(e,t)}function c(){return o.getStore()?.findInstalledApp}async function l(e){return await f(`providerFirst`,e)}async function u(e){let t=p(),n=await t.providerFirst.discoverWithSource(e,t.requestScope);return{devices:n.devices.map(e=>({...e})),source:n.source}}async function d(e){return await f(`localOnly`,e)}async function f(e,t){let n=p();return(await n[e].discover(t,n.requestScope)).map(e=>({...e}))}function p(){let e=o.getStore();if(!e)throw new t(`COMMAND_FAILED`,`Device inventory gateway is unavailable outside request execution`,{reason:a});return e}function m(e){return n(e)||e instanceof t&&e.code===`COMMAND_FAILED`&&e.details?.reason===a?!0:e instanceof Error&&e.name===`AbortError`}export{m as a,u as i,l as n,s as o,d as r,i as t};
|