agent-device 0.21.0 → 0.21.2
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.0.apk → agent-device-android-ime-helper-0.21.2.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.2.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.0.manifest.json → agent-device-android-ime-helper-0.21.2.manifest.json} +4 -4
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.0.manifest.json → agent-device-android-snapshot-helper-0.21.2.manifest.json} +6 -6
- package/apple/snapshot-bridge/README.md +58 -1
- package/apple/snapshot-bridge/SnapshotBridge.m +6 -0
- package/apple/snapshot-bridge/SnapshotBridgeCapture.h +25 -0
- package/apple/snapshot-bridge/SnapshotBridgeCapture.m +138 -0
- package/apple/snapshot-bridge/SnapshotBridgeRuntime.h +1 -0
- package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +32 -3
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +12 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +20 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerScrollViewportPolicy.swift +413 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSelectorMatchPolicy.swift +15 -15
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +72 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTapPointPolicy.swift +63 -14
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +668 -82
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +48 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift +39 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +1078 -211
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +290 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +1 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +10 -10
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +250 -74
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +101 -42
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +13 -13
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +55 -43
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +71 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +144 -7
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +13 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +216 -17
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +206 -22
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +289 -42
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotBackendCapabilities.swift +92 -22
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +617 -122
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTiming.swift +79 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +71 -71
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +92 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +67 -67
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +4 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +17 -17
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +30 -30
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +31 -31
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputCandidatePolicy.swift +28 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +101 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +19 -19
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +55 -17
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +26 -5
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +126 -75
- package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +8 -12
- package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +9 -9
- package/dist/src/absence-observation-errors.js +1 -0
- package/dist/src/adapter.js +1 -1
- package/dist/src/adb-executor.js +1 -1
- package/dist/src/adb-failure.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.d.ts +1 -1
- package/dist/src/ai-sdk.js +1 -1
- package/dist/src/alert-runtime.js +1 -1
- package/dist/src/android-input-ownership.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-contract.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 +3 -3
- package/dist/src/app-lifecycle2.js +1 -1
- package/dist/src/app-log-files.js +1 -1
- package/dist/src/app-log-runtime2.js +3 -3
- package/dist/src/app-resolution.js +1 -1
- package/dist/src/apple-runner-platform.js +1 -0
- 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/browser-launch.js +1 -0
- package/dist/src/capture.js +1 -1
- package/dist/src/catalog.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +30 -26
- package/dist/src/cli.js +4 -4
- package/dist/src/click-button.js +1 -1
- package/dist/src/client-metro-companion.js +1 -1
- package/dist/src/client-metro.js +1 -1
- package/dist/src/client-types.d.ts +28 -13
- package/dist/src/code-signature-cache.js +1 -1
- package/dist/src/code-signature.js +1 -1
- package/dist/src/command-metadata.js +1 -1
- package/dist/src/command-schema.js +3 -3
- package/dist/src/command-tools.js +2 -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 +3 -3
- 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-process.js +1 -1
- package/dist/src/daemon-shutdown-report.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 -0
- package/dist/src/device-claim-inspection.js +1 -1
- package/dist/src/device-claim-rule.js +1 -1
- package/dist/src/device-input-state.d.ts +1 -1
- 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/device2.js +1 -1
- package/dist/src/diagnostics.js +1 -1
- package/dist/src/dispatch-resolve.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 -0
- 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 +1 -2
- package/dist/src/generic-settle.js +1 -1
- package/dist/src/gesture-plan.js +1 -1
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/harmonyos.js +1 -1
- package/dist/src/hdc.js +1 -1
- package/dist/src/helper.js +2 -2
- package/dist/src/human-control-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 +2 -2
- 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.js +5 -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 +3 -0
- 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 +2 -2
- package/dist/src/inventory2.js +1 -1
- package/dist/src/inventory3.js +1 -1
- package/dist/src/inventory5.js +1 -1
- package/dist/src/ios-snapshot-acquisition.js +1 -1
- package/dist/src/ios-snapshot-planning.js +1 -1
- package/dist/src/ios-snapshot-runtime.js +1 -1
- package/dist/src/ios-system-surface.js +1 -0
- package/dist/src/lease-scope.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun-runtime-dependencies.js +1 -1
- package/dist/src/limrun.d.ts +1 -1
- 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/managed-device-scope.js +1 -1
- package/dist/src/mechanics.js +16 -16
- package/dist/src/mobile-snapshot-semantics.js +1 -1
- package/dist/src/mp4-atoms.js +1 -0
- package/dist/src/multitouch-support.js +1 -1
- package/dist/src/observation.js +1 -1
- package/dist/src/open-target-resolution.js +1 -0
- package/dist/src/owner-identity.js +3 -3
- package/dist/src/parameterized-recorded-fill.js +1 -1
- package/dist/src/perf-facade.js +2 -2
- package/dist/src/perf-process-identity.js +1 -0
- 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-app-log-process.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 +2 -2
- 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-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-finalizer-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 -0
- package/dist/src/png-worker-contract.js +1 -1
- package/dist/src/png.js +1 -0
- package/dist/src/prepare-kind.js +1 -1
- package/dist/src/process.js +1 -1
- package/dist/src/provider-device-runtime.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 -0
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/rect-center.js +1 -1
- package/dist/src/register-builtins.js +1 -1
- package/dist/src/registry.js +36 -36
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/replay-divergence.js +1 -1
- package/dist/src/replay.js +2 -2
- package/dist/src/reporting.js +9 -8
- package/dist/src/request-admission.js +1 -1
- package/dist/src/request-cancel.js +1 -1
- package/dist/src/request-cancellation.js +1 -1
- package/dist/src/request-runtime-binding.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-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 -0
- package/dist/src/runtime2.js +4 -4
- package/dist/src/runtime3.js +1 -1
- package/dist/src/runtime4.js +5 -4
- 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-live-handle.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/screenshot-density.js +1 -1
- package/dist/src/screenshot-runtime.js +1 -1
- package/dist/src/screenshot.js +1 -1
- package/dist/src/screenshot3.js +3 -3
- 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 +69 -26
- 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.d.ts +1 -1
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +80 -16
- 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 +3 -3
- package/dist/src/session-allocation.js +1 -1
- package/dist/src/session-observation.js +1 -0
- 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/session-target-evidence.js +1 -1
- package/dist/src/session2.js +5 -5
- package/dist/src/settings.js +1 -1
- package/dist/src/simulator-boot.js +3 -0
- package/dist/src/simulator.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/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/src7.js +2 -2
- package/dist/src/src8.js +2 -2
- package/dist/src/string-enum.js +1 -1
- package/dist/src/takeover.js +1 -1
- package/dist/src/telemetry.js +1 -1
- package/dist/src/tool-provider.js +2 -2
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tool-provider3.js +1 -1
- package/dist/src/toolchain-probe.js +1 -1
- package/dist/src/touch-reference-frame.js +1 -0
- 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/update-check.js +1 -1
- package/dist/src/vars.js +2 -0
- package/dist/src/verified-file.js +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/video.js +2 -2
- package/dist/src/viewport.js +1 -0
- package/dist/src/web.js +1 -1
- package/dist/src/web2.js +1 -1
- package/dist/src/webdriver-ios-snapshot.js +1 -1
- package/dist/src/webdriver-source.js +1 -1
- package/dist/src/window-state.js +1 -0
- package/package.json +4 -2
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.0.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.0.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.0.apk.sha256 +0 -1
- package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -93
- package/dist/src/platform-runtime-apple-resources.js +0 -1
- package/dist/src/runner-selector-query.js +0 -1
- package/dist/src/snapshot-quality-verdict.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as e,o as t,x as n,y 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{_ as o,c as s,l as c,m as l,o as u,v as d}from"./sdk-device.js";import{d as f,l as p,n as m,r as h}from"./lease-scope.js";import{Jt as g,Rr as _,Ut as ee,Yt as te,er as ne,jr as re,wr as ie,xr as ae}from"./sdk-batch.js";import{a as oe,n as se,r as ce}from"./script.js";import"./session-store.js";import{r as le}from"./format.js";import{r as v}from"./diagnostics.js";import"./diagnostics2.js";import{r as y}from"./command.js";import{a as ue,t as de}from"./config.js";import{n as b}from"./runtime-transport-hints.js";import{n as fe,t as pe,u as me}from"./provider-session-ownership.js";import{a as he,c as ge,d as x,f as S,g as _e,h as ve,i as ye,l as be,m as xe,n as C,o as Se,p as Ce,r as we,s as w,u as Te}from"./human-control-contract.js";import{r as Ee}from"./application-lifecycle-runtime.js";import{a as De,c as Oe,n as ke,o as Ae,r as je,s as T,t as Me}from"./device-claim-inspection.js";import{b as Ne,c as Pe,g as Fe,i as Ie,p as Le,x as E}from"./perf-runtime-plan.js";import{n as Re,r as ze,t as Be}from"./lease-context.js";import{h as Ve,l as He,u as Ue}from"./screenshot-runtime.js";import{t as We}from"./device-isolation.js";import{i as D}from"./request-runtime-binding.js";import{a as Ge,c as Ke,d as O,l as qe,n as Je,o as Ye,r as Xe,u as k}from"./src8.js";import{n as Ze,t as Qe}from"./compatibility-policy.js";import{a as $e}from"./screen-recording-resource-recovery.js";import A from"node:path";import"node:fs";import et,{createHash as tt}from"node:crypto";import nt from"node:os";import j from"node:fs/promises";function rt(e,t){if(t?.replayBackend&&t.replayBackend!==`maestro`)throw new r(`INVALID_ARGS`,`Unsupported replay backend "${t.replayBackend}".`);return{...se(e),metadata:ce(e)}}function it(e,t){return M(e,t)?t:`${e}:${t}`}function M(e,t){return t.startsWith(`${e}:`)}function at(e,t){return!e.partitioned||M(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{holdsByDevice=new Map;mutations=new ot;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=be(e),this.now=e.now??(()=>Date.now()),this.onLeaseExpired=e.onLeaseExpired,this.providerSessionOwnership=new pe({now:this.now,retentionMs:e.providerSessionRetentionMs})}allocateLease(e){let t=Ce(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=ge(t,n,this.now());return this.leases.set(i.leaseId,i),this.bindLease(i),{...i}}refreshExistingRunBinding(e,t){let n=S(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 Te(i);return w(i,e),this.refreshLease(i,t)}heartbeatLease(e){let t=_e(e.leaseId);this.cleanupExpiredLeases();let n=this.getActiveLease(t);Se(n,e),w(n,e);let r=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(n,r)}releaseLease(e){let t=this.getLease(e);return t?(this.leases.delete(t.leaseId),this.unbindLease(t),{released:!0,lease:t}):{released:!1}}getLease(e){let t=_e(e.leaseId);this.cleanupExpiredLeases();let n=this.leases.get(t);if(n)return Se(n,e),w(n,e),{...n}}assertLeaseAdmission(e){let t=xe(e);this.cleanupExpiredLeases(),w(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`?x(this.requireHumanControlLease(e.leaseId)):void 0;return[...this.holdsByDevice.entries()].filter(([e])=>t===void 0||t===e).flatMap(([,e])=>[...e.values()].map(({hold:e})=>C(e))).sort((e,t)=>e.id.localeCompare(t.id))}async putHumanControlHold(e,t,n,i){i?.throwIfAborted();let a=ye(t),o=he(n);this.cleanupExpiredLeases();let s=this.resolveHumanControlScope(e,o),c=x(s),l=this.findHumanControlHold(a);if(l&&(this.assertHoldAuthority(e,l),x(l.hold.scope)!==c))throw new r(`INVALID_ARGS`,`Release a hold before changing its device scope.`);let u=this.now(),d={...e.kind===`lease`?{ownerLeaseId:e.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(e,t,n,i){let a=this.holdsByDevice.get(e),{id:o}=t.hold;try{if(await this.mutations.wait(e,i),i?.throwIfAborted(),a.get(o)!==t)throw new r(`COMMAND_FAILED`,`Human-control hold changed before activation completed.`,{holdId:o});let s=this.now();return t.hold={...t.hold,state:`active`,updatedAt:s,...n===void 0?{}:{expiresAt:s+n}},this.refreshHeldLease(e,s),C(t.hold)}catch(n){throw a.get(o)===t&&this.deleteHumanControlHold(e,o),n}}removeHumanControlHold(e,t){let n=ye(t);this.cleanupExpiredLeases();let r=this.findHumanControlHold(n);if(!r)return;this.assertHoldAuthority(e,r);let i=x(r.hold.scope);return this.deleteHumanControlHold(i,n),C(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=x(e),n=t===void 0?void 0:this.holdsByDevice.get(t)?.values().next().value;if(n)throw we(n.hold)}async runDeviceMutation(e,t){if(!e)return await t();this.cleanupExpiredLeases();let n=this.getActiveLease(e.leaseId);this.assertHumanControlAdmission(n);let r=x(n);return r===void 0?await t():await this.mutations.run(r,t)}requireHumanControlLease(e){let t=this.getActiveLease(e);if(!t.deviceKey)throw new r(`UNSUPPORTED_OPERATION`,`Human control requires a device-scoped remote lease.`);return{...t,deviceKey:t.deviceKey}}resolveHumanControlScope(e,t){if(e.kind===`host`){if(!t.scope)throw new r(`INVALID_ARGS`,`Host human control requires a lease device scope.`);return t.scope}if(t.scope)throw new r(`INVALID_ARGS`,`Lease-owner human control uses the admitted lease device; do not supply scope.`);let n=this.requireHumanControlLease(e.leaseId);return{backend:n.backend,leaseProvider:n.leaseProvider,deviceKey:n.deviceKey}}assertHoldAuthority(e,t){if(e.kind===`host`)return;let n=this.requireHumanControlLease(e.leaseId);if(t.ownerLeaseId!==n.leaseId||x(n)!==x(t.hold.scope))throw new r(`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=x(e);return t!==void 0&&this.holdsByDevice.has(t)}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){let n=this.deviceBindings.get(e),r=n?this.leases.get(n):void 0;r&&this.refreshLease(r,r.expiresAt-r.heartbeatAt,Math.max(t,r.heartbeatAt))}consumeExpiredLeases(){this.expireHumanControlHolds();let e=this.now(),t=[];for(let n of this.leases.values()){if(n.expiresAt>e||this.hasHumanControl(n))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=ve(e);if(!t)return;let n=this.leases.get(t);if(!n||n.expiresAt>this.now()||this.hasHumanControl(n))return;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};return this.onLeaseExpired?.(r),r}cleanupExpiredLeases(){this.consumeExpiredLeases()}enforceCapacity(e){if(e!==`ios-simulator`||this.maxActiveSimulatorLeases<=0)return;let t=Array.from(this.leases.values()).filter(e=>e.backend===`ios-simulator`).length;if(!(t<this.maxActiveSimulatorLeases))throw new r(`DEVICE_IN_USE`,`No simulator lease capacity available`,{reason:`LEASE_CAPACITY_EXCEEDED`,activeLeases:t,maxActiveLeases:this.maxActiveSimulatorLeases,backend:e,hint:`Retry after releasing another simulator lease.`})}getActiveLease(e){let t=this.leases.get(e);if(t)return t;throw new r(`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(S(e),e.leaseId);let t=x(e);t&&this.deviceBindings.set(t,e.leaseId)}unbindLease(e,t=this.now()){this.runBindings.delete(S(e));let n=x(e);n&&this.deviceBindings.delete(n),this.providerSessionOwnership.markLeaseReleased(e,t)}assertDeviceAvailable(e){let t=x({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 Te(r)}};function ct(e){let t=ue(e.meta?.sessionIsolation??e.flags?.sessionIsolation),n=e.meta?.tenantId??e.flags?.tenant,i=de(n);if(n&&!i)throw new r(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(t!==`tenant`)return e;if(!i)throw new r(`INVALID_ARGS`,`session isolation mode tenant requires --tenant (or meta.tenantId).`);let a=e.session||`default`;return M(i,a)?{...e,meta:{...e.meta,tenantId:i,sessionIsolation:t}}:{...e,session:it(i,a),meta:{...e.meta,tenantId:i,sessionIsolation:t}}}function lt(e,t,n,i={}){if(Ue(e.command))return;let a=Re(e);ft(e,a);let o=n?.lease;if(n===void 0&&!a.leaseId&&ut(e,i.providerAppCatalog))return;if(e.command===`human_control`&&!o&&!a.leaseId)throw new r(`UNSUPPORTED_OPERATION`,`Takeover requires an active remote device lease. Local takeover is not supported.`);if(e.command!==`human_control`&&!o&&e.meta?.sessionIsolation!==`tenant`&&(!a.leaseId||!a.tenantId&&!a.runId))return;pt(a,o);let s=ze(e,n),c={...s,leaseTtlMs:s.leaseTtlMs??(h(s)?3e5:void 0)};t.assertLeaseAdmission(p(s));let l=t.heartbeatLease(p(c));return He(e)&&t.assertHumanControlAdmission(l),l}function ut(e,t){let n=Ve(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function dt(e){Ue(e.command)||ft(e,Re(e))}function ft(e,t){if(e.command!==`open`)return;let n=m(t);if(n.length!==0)throw new r(`INVALID_ARGS`,`Proxy open requires leaseId, tenantId, runId, clientId, and deviceKey lease metadata.`,{missing:n})}function pt(e,t){t&&(N(`leaseId`,e.leaseId,t.leaseId),N(`tenantId`,e.tenantId,t.tenantId),N(`runId`,e.runId,t.runId),N(`leaseProvider`,e.leaseProvider,t.leaseProvider),N(`clientId`,e.clientId,t.clientId),N(`deviceKey`,e.deviceKey,t.deviceKey))}function N(e,t,n){if(!(!t||!n||t===n))throw new r(`UNAUTHORIZED`,`Lease does not match session owner (${e})`,{reason:`LEASE_SESSION_MISMATCH`,field:e})}async function mt(e,t){if(!t.leaseProvider||!e)return!1;try{return await e(t),v({level:`info`,phase:`provider_lease_expired_released`,data:{leaseId:t.leaseId,provider:t.leaseProvider}}),!0}catch(e){return v({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 ht(e){dt(e)}async function gt(e){let t=e.sessionStore.get(e.sessionName),n=t?.lease;return!t||!n||!e.leaseRegistry.consumeExpiredLease(n.leaseId)?!1:(v({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=>{v({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 Ne(t.deviceClaim).catch(e=>{v({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 _t(e){let{sessionName:t,sessionStore:n,leaseRegistry:r}=e,i=n.get(t),a=lt(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 vt(e){return Be(e.req,e.req.internal?.admittedLease)??e.existingLease}async function yt(e){let t=e.session.lease;if(!t)return;let n=f({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=fe(i);r&&a&&e.leaseRegistry.recordProviderSession(r,a);let o=e.leaseRegistry.releaseLease(n);return v({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:o.released}}),i}const bt=[`platform`,`target`],xt=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function St(e){return u({deviceName:e?.device,udid:e?.udid,serial:e?.serial})}function Ct(e){return St(e)||Et(e,bt)}function wt(e){return Ct(e)||Et(e,xt)}function Tt(e){return typeof e==`string`&&e.trim().length>0}function Et(e,t){return e?t.some(t=>Tt(e[t])):!1}function Dt(e){return{appleSimulatorAppTarget:Ot(e)}}function Ot(e){return e&&!i(e)?e:void 0}function kt(e){return`${e.device.platform} device "${e.device.name.trim()}" (${e.device.id})`}function P(e,t){return e.session.screenRecording?jt(e.address,t):Mt(e.address,t)}function At(e,t){return D(`DEVICE_IN_USE`,`Device is already in use by session "${e.address}".`,{session:e.address,deviceId:t.id,deviceName:t.name,hint:P(e,`device-in-use`)})}function jt(e,t){let n=y(e),r=`agent-device close --session ${n}`;return`Recording session "${e}" owns this device. Run ${`agent-device record stop --session ${n}`}; if the session still appears in agent-device session list, run ${r}. ${t===`selector-conflict`?`To keep using this device, rerun the command with --session ${n} and remove conflicting device selectors.`:`To keep using this device, reuse --session ${n} for commands that should attach to the recording session.`} Run agent-device session list to inspect active sessions.`}function Mt(e,t){let n=y(e),r=`agent-device close --session ${n}`;return t===`selector-conflict`?`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${n} and remove conflicting device selectors. To switch devices, first run ${r}, then open the desired device with a different --session name.`:`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${n}. To open a new session on this device, first run ${r}.`}function Nt(e,t){let{address:n,session:i}=e,a=Pt(i,t);if(a.length!==0)throw new r(`INVALID_ARGS`,`Session "${n}" is already bound to ${kt(i)}, but this request selected ${a.map(Ft).join(`, `)}.`,{session:n,conflicts:a.map(Ft),hint:P(e,`selector-conflict`)})}function Pt(e,t){if(!t)return[];let n=[],r=e.device,i=t.platform;if(i&&!o(r,i)&&n.push({key:`platform`,value:t.platform}),t.target&&t.target!==(r.target??`mobile`)&&n.push({key:`target`,value:t.target}),t.udid&&(!c(r)||t.udid!==r.id)&&n.push({key:`udid`,value:t.udid}),t.serial&&(!l(r.platform)||t.serial!==r.id)&&n.push({key:`serial`,value:t.serial}),t.device&&t.device.trim().toLowerCase()!==r.name.trim().toLowerCase()&&n.push({key:`device`,value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),i=r.simulatorSetPath?.trim();(!c(r)||r.kind!==`simulator`||e!==i)&&n.push({key:`iosSimulatorDeviceSet`,value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=We(t.androidDeviceAllowlist);(r.platform!==`android`||!e.has(r.id))&&n.push({key:`androidDeviceAllowlist`,value:t.androidDeviceAllowlist})}return n}function Ft(e){return`${It(e.key)}=${e.value}`}function It(e){switch(e){case`iosSimulatorDeviceSet`:return`--ios-simulator-device-set`;case`androidDeviceAllowlist`:return`--android-device-allowlist`;default:return`--${e}`}}function Lt(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(ne(t),`utf8`).digest(`hex`)}function Rt(e,t,n){return new qt(Bt(zt(t.resolve(e))),n).parse()}function zt(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Bt(e){let t=[],n=0;for(;n<e.length;){let i=e.slice(n),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){n+=a;continue}let o=Vt(i);if(!o)throw new r(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);t.push(o.value),n+=o.length}return t}function Vt(e){return Ht(e)??Ut(e)??Wt(e)??Gt(e)??Kt(e)}function Ht(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function Ut(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Wt(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Gt(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function Kt(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var qt=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let e=this.parseOr();if(this.peek())throw new r(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return e}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 e=this.peek();if(!e)throw new r(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(e.type===`boolean`)return this.index+=1,e.value;if(e.type===`paren`&&e.value===`(`){this.index+=1;let e=this.parseOr();if(!this.consumeParen(`)`))throw new r(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return e}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 r(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let e=this.peek();if(e?.type!==`operator`||e.value!==`==`&&e.value!==`!=`)throw new r(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,e}consumeStringLiteral(){let e=this.peek();if(e?.type!==`string`)throw new r(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,e.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 Jt(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Yt(e,t){return{...I(e,t),source:e.source}}function Xt(e,t,n){if(e===void 0)return;let i=n??Ge[t]??{},a=Ye(i),o;if(typeof e==`number`)o=e;else{let n=e.trim();if(n===``)throw new r(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);o=Number(n)}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 r(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);return o}function Zt(e,t,n,r){return Xt(e===void 0?t:n.resolve(String(e)),r)}function F(e){if(e?.aborted)throw n()}async function Qt(e,t){if(e.include.kind===`commands`)return{kind:`program`,source:e.source,config:{},commands:e.include.commands};if(!t.loadProgram)throw new r(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return F(t.signal),t.signal?await t.loadProgram(e.include.path,e.source.path,t.signal):await t.loadProgram(e.include.path,e.source.path)}function $t(e,t){if(e.include.kind===`file`)return A.resolve(t?A.dirname(t):process.cwd(),e.include.path)}function en(e){return e===void 0?void 0:A.resolve(e)}function tn(e,t){let n=$t(e,e.source.path);if(n&&t.has(n))throw new r(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${n}.`);return n}function nn(e,t,n,i){let a=e.include.kind===`file`?en(t.source.path):void 0,o=new Set([n,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new r(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function rn(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:Rt(e.true,t,n.platform)}function an(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function I(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>I(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,I(n,t)])):e}async function on(e,t){F(t.signal);let n=en(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 sn(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function sn(e,t,n,r,i){F(i.options.signal);let a=_n(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 ln(s,a,o,e.source.path??r,i));return n}finally{s()}}async function cn(e,t,n,r,i){let a=[];for(let o of e)a.push(...await ln(o,t,n,r,i));return a}async function ln(e,t,n,r,i){F(i.options.signal);let a=vn(e,r);switch(a.kind){case`runFlow`:{let e=dn(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await un(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[L(a,t,n,o)]}case`repeat`:return[L(a,t,n,await cn(a.commands,t,n,r,i))];case`retry`:return[L(a,t,n,await cn(a.commands,t,n,r,i))];default:return[hn(a,t,n)]}}async function un(e,t,n,r,i){let a=pn(e,i.context),o=tn(a,i.activeIncludePaths),s=await Qt(a,i.options);F(i.options.signal);let c=nn(a,s,o,i.activeIncludePaths),l=_n(t,e.env),u=i.context.enter(e.env);try{return await sn(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function dn(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:fn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function fn(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return mn(t.context.resolveDeferred(e))?`opaque`:Rt(e,t.context,t.options.platform)?void 0:`omit`}function pn(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function mn(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function hn(e,t,n){return O({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function L(e,t,n,r){return O({kind:`opaque`,command:gn(e),source:e.source,scopes:t,body:r,appId:n})}function gn(e){switch(e.kind){case`runFlow`:return O({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 O({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function _n(e,t){return t===void 0?e:[...e,t]}function vn(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function yn(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await on(e,t),a=bn(t.runtimeHints),o=O({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=Lt(o);return xn({...o,digest:s})}function bn(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 xn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))xn(t);return Object.freeze(e)}function Sn(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`)return{allowed:!1,reason:`step ${t+1} (runScript) 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 Cn(e,t={}){let n=Sn(e,t);if(!n.allowed)throw new r(`INVALID_ARGS`,n.reason);return n.startIndex}function wn(e,t){if(!Number.isInteger(t)||t<0||t>e.total)throw new r(`INVALID_ARGS`,`Maestro replay startIndex ${t} is out of range for a ${e.total}-step plan.`);return t}const Tn=`maestro-test-failure`;function R(e,t={}){return new r(`COMMAND_FAILED`,e,{...t,reason:Tn})}function En(e){return e instanceof r&&e.code===`COMMAND_FAILED`&&e.details?.reason===Tn}const Dn=new Set([``,`false`,`0`,`null`,`undefined`]);function On(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!Dn.has(e)}async function kn(e,t){F(t.options.signal);try{return await Vn(e,t.context,async()=>await An(e,t))}catch(t){throw V(t,e)}}async function An(e,t){if(e.kind===`command`)return await jn(e.command,e.appId,t);await In(e,t)}async function jn(e,t,n){let r=Yt(e,n.context);try{return await Pn(r,t,n)}catch(e){if(F(n.options.signal),Nn(r)&&En(e)){n.warnings.push(Mn(r,e)),n.skipped+=1;return}throw Hn(e,r)}}function Mn(e,t){let n=`${e.source.path?`${e.source.path}:`:``}line ${e.source.line}`,i=t instanceof r?t.message:String(t);return`Optional Maestro ${e.kind} skipped at ${n}: ${i}`}function Nn(e){return`optional`in e&&e.optional===!0}async function Pn(e,t,n){switch(e.kind){case`assertVisible`:await B({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await B({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!On(e.condition))throw R(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await B(Bn(e),Xt(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await Fn(e,t,n)}}async function Fn(e,t,n){let r=O({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 F(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 In(e,t){let n=Yt(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await Rn(n.when,t)){t.skipped+=1;return}t.executed+=1,await z(e.body,t);return;case`repeat`:{let r=Zt(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)F(t.options.signal),await z(e.body,t);return}case`retry`:{let r=Math.min(Zt(n.maxRetries,1,t.context,`retry.maxRetries`),Ze.control.retryMaxRetries);t.executed+=1,await Ln(e.body,r,t);return}}}async function z(e,t){for(let n of e)await kn(n,t)}async function Ln(e,t,n){let i;for(let r=0;r<=t;r+=1){F(n.options.signal);try{await z(e,n);return}catch(t){if(F(n.options.signal),!En(Wn(t)))throw t;i=V(t,e[0])}}throw i||new r(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function Rn(e,t){if(!rn(e,t.context,t.options))return!1;for(let n of an(e))if(F(t.options.signal),!(await zn(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function B(e,t,n){if(!(await zn(e,t,n)).matched)throw R(`Maestro ${e.kind} condition did not match.`)}async function zn(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 F(n.options.signal),n.context.recordObservation(i),i}function Bn(e){if(e.visible)return{kind:`visible`,selector:e.visible};if(e.notVisible)return{kind:`notVisible`,selector:e.notVisible};throw new r(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function Vn(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 V(e,t){if(Un(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Gn(e,t?.command),source:n,...t?{command:t.command}:{}}}function Hn(e,t){return{kind:`maestroPlanStepFailure`,error:Gn(e,t),source:t.source,command:t}}function Un(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Wn(e){return Un(e)?e.error:e}function Gn(e,t){if(!(e instanceof r)||!t||/\bline \d+\b/.test(e.message))return e;let n=t.source.path?`${t.source.path}:`:``;return new r(e.code,`${e.message} (${n}line ${t.source.line})`,e.details)}async function Kn(e,t,n={}){F(n.signal);let i=n.startIndex??0;if(!Number.isInteger(i)||i<0||i>e.total)throw new r(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${e.total}-step plan.`);let a={plan:e,port:t,options:n,context:Ke(n.defaults,n.env?{...n.env}:{}),timing:Qe,artifacts:new Set,warnings:[],executed:e.compatibility.staticallyExecutedControls,skipped:e.compatibility.staticallySkippedControls};for(let t=i;t<e.steps.length;t+=1)try{await qn(e.steps[t],t,a)}catch(e){throw Wn(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function qn(e,t,n){F(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};H(()=>n.options.observer?.commandStarted?.(s));try{let t=await kn(e,n);F(n.options.signal),H(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Jn(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=V(t,e);throw H(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Jn(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts]})),o}}function Jn(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 H(e){try{e?.()}catch{}}async function Yn(e,t,n={}){let r=Xn(e,n);return await Kn(e,t,{...n,startIndex:r})}function Xn(e,t){return t.from!==void 0||t.planDigest!==void 0?Cn(e,{from:t.from,planDigest:t.planDigest}):wn(e,t.startIndex??0)}function Zn(e){return Jt(e)?{command:e.kind,...e.kind===`runFlow`?W(e.label??e.includePath):{}}:{command:e.kind,...Qn(e)}}function Qn(e){return`label`in e&&e.label?W(e.label):$n(e)?W(or(e.target)):er(e)?tr(e):e.kind===`inputText`?W(`<text>`):nr(e)}function $n(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function er(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function tr(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return W(U(e.target));case`extendedWaitUntil`:return W(U(e.visible??e.notVisible));case`scrollUntilVisible`:return W(U(e.element))}}function nr(e){return rr(e)?ir(e):e.kind===`swipe`?ar(e):e.kind===`runFlow`?W(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?W(String(e.condition)):{}}function rr(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function ir(e){switch(e.kind){case`openLink`:return W(e.link);case`takeScreenshot`:return W(e.path);case`runScript`:return W(e.file);case`pressKey`:return W(e.key)}}function ar(e){return W(e.gesture.kind===`coordinates`?`${sr(e.gesture.start)} to ${sr(e.gesture.end)}`:e.gesture.direction)}function or(e){return e.space===`target`?U(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function U(e){return e?.id??e?.text}function sr(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function W(e){return e?{value:e}:{}}const cr=new Set(String.raw`^$\.*+?()[]{}|`);function lr(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function ur(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(cr.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!cr.has(i))return;t+=i,n+=1}return t}function dr(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(_(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=>ie(e,n)?e:null);return r?_(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function fr(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function pr(e,t){let n=[t.id===void 0?void 0:hr(e.identifier,t.id),t.text===void 0?void 0:gr(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 mr(e){return e.matches.filter(t=>dr(t,e.visibility,e.platform))}function hr(e,t){let n=e??``;return k(n)===k(t)||lr(n,t)}function gr(e,t){return[e.label,qe(e),e.identifier].filter(e=>!!e).some(e=>hr(e,t))}function _r(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 vr(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function yr(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=xr(a.rect,e.rect);n===void 0||!br(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 br(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 xr(e,t){if(!(!Sr(e)||!Sr(t)))return Math.fround(Math.hypot(G(e.x,e.width)-G(t.x,t.width),G(e.y,e.height)-G(t.y,t.height)))}function Sr(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function G(e,t){return e+Math.trunc(t/2)}function Cr(e,t={},n={}){let i=ae(e.nodes,t);t.onVisibilityContextCreated?.();let a=new WeakMap,o=new WeakSet,s=new WeakMap,c=new Map,l=t=>t.parentIndex===void 0?void 0:i.nodeByIndex.get(t.parentIndex)??e.nodes[t.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=(n,r)=>{let i=c.get(n);i||(i=new WeakMap,c.set(n,i));let a=i.get(r);if(a)return a;t.onPositionComputed?.(n,r);let o=yr(e.nodes,n,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 r(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),t.onSelectorComputed?.(i);try{let t=wr(e,i,l,u,m,p),r={matches:t,indexed:Or(t,i.index,n.orderUnindexed)};return a.set(i,r),r}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function wr(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=vr(m)?e.nodes.filter(e=>pr(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>Er(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=>Tr(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of Dr(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function Tr(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function Er(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Dr(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function Or(e,t,n){if(t===void 0)return n?n(e):[...e];let r=Ar(e)[jr(t)];return r?[r]:[]}function kr(e,t){return t===void 0?e[0]:Ar(e)[jr(t)]}function Ar(e){return[...e].sort((e,t)=>{let n=K(e.rect?.y),r=K(t.rect?.y);return n===r?K(e.rect?.x)-K(t.rect?.x):n-r})}function K(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function jr(e){let t=typeof e==`number`?e:Number(e.trim());if(!Number.isSafeInteger(t)||t<0)throw new r(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return t}const Mr={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Nr(e,t){let n=Mr[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 q(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Pr(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Pr(e){return e===!0?2:+(e===!1)}function Fr(e,t,n,r={}){let i=Nr(e,n),a=Lr(e,i,r),o=Ir(t,a),s=mr({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:Rr(s,t,n,a.visibility,i)}}function Ir(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Lr(e,t,n={}){return Cr(e,n,t?{orderUnindexed:e=>q(e,t)}:{})}function Rr(e,t,n,r,i){let a=n!==`ios`||!Hr(t)?e:e.filter(n=>{if(Gr(n))return!0;let i=e.filter(e=>e!==n&&Ur(n,e,t));return!i.some(e=>Gr(e)&&fr(n,e,r))&&!i.some(e=>fr(e,n,r))});return t.index===void 0&&i?q(a,i):a}function zr(e,t){let n=t===void 0?e.find(J):Br(e,t);return!n||!J(n)?null:{node:n,rect:n.rect}}function Br(e,t){return kr(e,t)}function Vr(e){return J(e)?e.rect:void 0}function J(e){return _(e.rect)}function Hr(e){return e.id!==void 0||e.text!==void 0}function Ur(e,t,n){if(n.id!==void 0&&Y(e.identifier)!==Y(t.identifier))return!1;if(n.text!==void 0){let n=Wr(e),r=new Set(Wr(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Wr(e){return[e.label,e.value,e.identifier].map(Y).filter(e=>e!==void 0)}function Y(e){if(e)return k(e)||void 0}function Gr(e){let t=re(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const Kr=Symbol(`maestroFlowProgram`),qr=Symbol(`maestroFailureCommand`),Jr=Symbol(`maestroFailurePlan`);function Yr(e,t){let n=Xe(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:$r(n),[Kr]:n}}async function Xr(e,t,n){let r;try{let i=Je(A.dirname(e.sourcePath),n.readSource),a=await yn(e[Kr],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=Cn(a,{from:n.from,planDigest:n.planDigest}),s=await Yn(a,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:i,signal:n.signal,startIndex:o,observer:Qr(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 Zr(e,t){let n=ti(e[qr]),r=e[Jr].platform;return!n||r!==`android`&&r!==`ios`?[]:Fr(t,n.selector,r).ranked.map(e=>({node:e,basis:ni(n.selector,e)}))}function Qr(e,t,n){return{commandStarted:e=>t?.actionStarted?.(X(e)),commandCompleted:e=>t?.actionCompleted?.({...X(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=Sn(e,{from:r.stepIndex,planDigest:e.digest}),a={...X(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,isControl:Jt(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},[qr]:r.command,[Jr]:e};n(a),t?.actionFailed?.(a)}}}function X(e){let t=Zn(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function $r(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(ei)}function ei(e){return!!(e?.trim()&&!e.includes(`$`)&&!i(e))}function ti(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 ni(e,t){return e.id!==void 0||e.text!==void 0&&pr({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}const ri=`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 ii(e,t){let n=e.files[t];if(n===void 0)throw new r(`INVALID_ARGS`,`replay script source is missing ${t}; it was not part of the script sources sent with this request.`,{path:t,entry:e.entry});return n}function ai(e){if(e.command!==`replay`||e.flags?.replayFrom!==void 0)return;let t=e.flags?.replayScriptSource;if(t)try{let n=t.entry,r=ii(t,n);if(le(n,e.flags?.replayBackend)===`maestro`){let t=Yr(r,n);return{flags:e.flags??{},options:oi(t.appTarget,e.flags?.platform)}}let i=rt(r,e.flags),a=si(i.actions);if(!a.appTarget)return;let o=ci(e.flags,i.actions),s=o.platform??i.metadata.platform;return{flags:s&&o.platform===void 0?{...o,platform:s}:o,options:s===`ios`?ui(a.appTarget):void 0}}catch{return}}function oi(e,t){return t===`ios`?ui(e)??{}:{}}function si(e){let t=oe(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return li(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function ci(e,t){let n=si(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function li(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!i(e))}function ui(e){let t=Ot(e);return t?{appleSimulatorAppTarget:t}:void 0}const di={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.`},Z=new Map;async function fi(e){let t=await j.mkdtemp(A.join(nt.tmpdir(),`agent-device-materialized-`));try{let n=await gi(e.installablePath,A.join(t,`installable`)),r=e.archivePath?await gi(e.archivePath,A.join(t,`archive`)):void 0,i=et.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{hi(i)},a);return Z.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 j.rm(t,{recursive:!0,force:!0}),e}}async function pi(e,t){await Q(e,me(Z,e,t,di))}async function mi(e){let t=Array.from(Z.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await Q(e,t)}))}async function hi(e){let t=Z.get(e);if(t)try{await Q(e,t)}catch{}}async function Q(e,t){clearTimeout(t.timer),Z.delete(e),await j.rm(t.rootPath,{recursive:!0,force:!0})}async function gi(e,t){let n=await j.stat(e);await j.mkdir(t,{recursive:!0});let r=A.join(t,A.basename(e));return n.isDirectory()?(await j.cp(e,r,{recursive:!0}),r):(await j.copyFile(e,r),r)}function _i(e){return e.device.platform===`web`}function vi(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function yi(e){let{session:t,sessionName:n,sessionStore:r}=e;t.appLog&&await Le({session:t,sessionName:n,sessionStore:r,resourcePath:Fe.resolvePath(r.resolveSessionDir(n))})}async function bi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.perfCapture&&await Ie({...e,session:t})}async function xi(e,t){await t.stopSnapshotHelper(e.device)}async function Si(e){let{session:t,sessionName:n,sessionStore:r,platformCleanup:i}=e;await i.closeManagedBrowser({device:t.device,sessionName:n,stateDir:r.resolveDaemonStateDir(),openSessionNames:()=>vi(r)})}async function Ci(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 wi(e){if(e.failures.length===0)return;let t=e.failures.map(({step:e})=>e),n=e.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return v({level:`error`,phase:e.phase,data:{session:e.sessionName,failedSteps:t,errors:n}}),new r(`COMMAND_FAILED`,`Session cleanup left ${e.failures.length} resource(s) unreleased: ${n.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:e.sessionName,failedSteps:t,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 Ti(e){let{session:t,sessionName:n,sessionStore:i}=e;if(!e.platformCleanup)throw new r(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let a=e.platformCleanup,o=[{step:`recording`,run:()=>Ei({session:t,sessionName:n,sessionStore:i})},...e.appLog===`run`?[{step:`app_log`,run:()=>yi({session:t,sessionName:n,sessionStore:i})}]:[],{step:`audio_probe`,run:()=>Di({session:t,sessionName:n,sessionStore:i})},{step:`perf_capture`,run:()=>bi({session:t,sessionName:n,sessionStore:i})},{step:`platform_snapshot_helper`,run:()=>xi(t,a)},{step:`web_browser`,run:()=>Si({session:t,sessionName:n,sessionStore:i,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>mi(n)});let s=wi({sessionName:n,phase:`session_teardown_cleanup_failed`,failures:await Ci(o)});if(s)throw s}async function Ei(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.screenRecording&&await $e({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}async function Di(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.audioProbe&&await Pe({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}function Oi(e){return c(e)&&e.kind===`simulator`}function ki(e){return e.platform===`android`&&e.kind===`emulator`}const Ai=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function ji(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function $(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 Mi(e){return Ee($(e))}function Ni(e,t){if(e!==void 0){if(typeof e!=`string`)throw new r(`INVALID_ARGS`,`Invalid open runtime ${t}: expected string.`);return b(e)}}function Pi(e){if(e!==void 0){if(!Number.isInteger(e)||e<1||e>65535)throw new r(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function Fi(e){if(e!==void 0){if(typeof e!=`number`)throw new r(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Pi(e)}}function Ii(e,n,i){if(e===void 0)return i;if(!t(e))throw new r(`INVALID_ARGS`,`Invalid open runtime platform: ${String(e)}. Use "ios", "android", or "harmonyos".`);if(i&&e!==i)throw new r(`INVALID_ARGS`,`open runtime targets ${e}, but session "${n}" is bound to ${i}.`);return e}function Li(e){if(t(e))return e}function Ri(e,t){return{platform:t,metroHost:b(e?.metroHost),metroPort:Pi(e?.metroPort),bundleUrl:b(e?.bundleUrl),launchUrl:b(e?.launchUrl)}}function zi(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 Bi(e){if(ki(e))return`10.0.2.2`;if(Oi(e))return`127.0.0.1`}function Vi(e,t){if(!e||b(e.metroHost)||b(e.bundleUrl)||e.metroPort===void 0)return e;let n=Bi(t);return n?{...e,metroHost:n}:e}function Hi(e){let{runtime:t,sessionName:n,platform:i}=e;if(t===void 0)return;if(!t||typeof t!=`object`||Array.isArray(t))throw new r(`INVALID_ARGS`,`open runtime must be an object.`);let a=t,o=Object.keys(a).find(e=>!Ai.includes(e));if(o)throw new r(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Ai.join(`, `)}.`);return{platform:Ii(a.platform,n,i),metroHost:Ni(a.metroHost,`metroHost`),metroPort:Fi(a.metroPort),bundleUrl:Ni(a.bundleUrl,`bundleUrl`),launchUrl:Ni(a.launchUrl,`launchUrl`)}}function Ui(e,t,n){if(n){if(ji(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Wi(e,t,n,i){let a=e.getRuntimeHints(t);if(!a)return;let o=n?d(n):void 0,s=Li(o)??i;if(a.platform&&n&&!s)throw new r(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${t}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new r(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Gi(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?Li(d(i)):e.platform,o=n.getRuntimeHints(r),s=Hi({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=Wi(n,r,i,a);return{runtime:i?Vi(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&ji(s)>0?s:void 0;return{runtime:i?Vi(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Ki(e){return Gi(e).runtime}function qi(t){try{return{ok:!0,data:Gi(t)}}catch(t){let n=e(t);return D(n.code,n.message,n.details)}}async function Ji(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!Yi(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:$(t)})}function Yi(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Mi(e.previousRuntime)&&!Mi(e.runtime)}function Xi(e){let{device:t,owner:n,stateDir:r,intent:i}=e,a=i.kind===`exact-owner`&&te(i.owner,n)?ee(i.fence):null;if(!a)return{status:`binding-invalid`};let o=T(E(t)),s=je(Oe(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!Qi(c.stateDir,r)||!te(Ae(c),n)?{status:`conflict`,conflict:s}:c.allocator.identityIncarnationId===a.identityIncarnationId?{status:`covered`}:{status:`incarnation-stale`,heldIncarnationId:c.allocator.identityIncarnationId}}function Zi(e){let t=T(E(e));return De(Oe(t))}function Qi(e,t){return A.resolve(e)===A.resolve(t)}const $i=new Set([`DEVICE_CLAIM_LIVE_OWNER`,`DEVICE_CLAIM_RECOVERY_PENDING`,`DEVICE_CLAIM_OWNER_UNCERTAIN`]);function ea(e){return $i.has(e)}function ta(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=d(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=s(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${y(i)}`,`${a} ${y(e.id)}`,...n===`release`||ke(t.classification)?[`--stale`]:[]].join(` `)}function na(e,t){if(t.classification===`allocator-held`)return ia(e,t);let n=t.claim,i=ta(e,t,Me(t.classification)?`release`:`status`),a=d(n?{platform:n.device.family,appleOs:n.device.appleOs}:e);return new r(`DEVICE_IN_USE`,n?`${a} device ${e.id} is owned by session "${n.session}" in workspace "${n.workspace}".`:`${e.name} has an ownership claim that could not be verified.`,{reason:da(t.classification),classification:t.classification,deviceKey:t.deviceKey,...n?{owner:{session:n.session,workspace:n.workspace,stateDir:n.stateDir}}:{},recovery:{command:i},hint:Me(t.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 ra(e,t){return ua(na(e,t))}function ia(e,t){let n=t.allocatorClaim,i=d({platform:n.device.family,appleOs:n.device.appleOs}),a=ta(e,t);return new r(`DEVICE_IN_USE`,`${i} device ${e.id} is held by managed-device allocator "${n.allocator.instanceId}" for installation "${n.stateDir}".`,{reason:`DEVICE_CLAIM_ALLOCATOR_HELD`,classification:t.classification,deviceKey:t.deviceKey,owner:{kind:`allocator`,stateDir:n.stateDir,allocator:n.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 aa(e,t){return new r(`COMMAND_FAILED`,`${d(e)} device ${e.id} is a managed identity with no allocator-held execution claim for this installation.`,{reason:`allocator-claim-missing`,owner:g(t),deviceKey:T(E(e)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function oa(e,t,n){return new r(`COMMAND_FAILED`,`${d(e)} device ${e.id} is held for identity incarnation "${n}", which is not the incarnation this binding fences.`,{reason:`allocator-claim-incarnation-stale`,owner:g(t),deviceKey:T(E(e)),heldIncarnationId:n,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function sa(e,t){return new r(`COMMAND_FAILED`,`A managed local owner executes only under an exact-owner binding that carries a managed binding fence.`,{reason:`runtime-contract-invalid`,owner:g(t),deviceKey:T(E(e)),retriable:!1})}function ca(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:sa(e,t)};case`missing`:return{admitted:!1,error:aa(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:oa(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:na(e,n.conflict)}}}function la(e,t,n){let r=ca(e,t,n);return r.admitted?void 0:ua(r.error)}function ua(e){let{hint:t,retriable:n,...r}=e.details??{};return D(e.code,e.message,r,{hint:t,retriable:n})}function da(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 fa(e){switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{ur as $,mi as A,Lr as B,yi as C,_i as D,Ti as E,ri as F,Br as G,Fr as H,ii as I,Nr as J,Vr as K,Zr as L,oi as M,ci as N,vi as O,ai as P,dr as Q,Xr as R,wi as S,xi as T,Rr as U,Ir as V,zr as W,_r as X,Cr as Y,mr as Z,Yi as _,yt as _t,na as a,At as at,Di as b,st as bt,Xi as c,Dt as ct,Mi as d,wt as dt,R as et,Ji as f,Tt as ft,Ui as g,mt as gt,$ as h,gt as ht,ca as i,Pt as it,fi as j,pi as k,Ri as l,Ct as lt,Ki as m,ht as mt,la as n,Nt as nt,ea as o,P as ot,zi as p,_t as pt,q,ra as r,Ft as rt,Zi as s,kt as st,fa as t,Xt as tt,ji as u,St as ut,Li as v,vt,bi as w,Ei as x,at as xt,qi as y,ct as yt,Yr as z};
|
|
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{_ as o,c as s,l as c,m as l,o as u,v as d}from"./sdk-device.js";import{d as f,l as p,n as m,r as h}from"./lease-scope.js";import{Mr as ee,Sr as te,Tr as ne,Wt as re,Xt as ie,Yt as g,tr as ae,zr as _}from"./sdk-batch.js";import{a as oe,n as se,r as ce}from"./script.js";import"./session-store.js";import{r as le}from"./format.js";import{r as v}from"./diagnostics.js";import"./diagnostics2.js";import{r as y}from"./command.js";import{a as ue,t as de}from"./config.js";import{n as b}from"./runtime-transport-hints.js";import{n as fe,t as pe,u as me}from"./provider-session-ownership.js";import{a as he,c as ge,d as x,f as _e,g as ve,h as ye,i as be,l as xe,m as Se,n as S,o as Ce,p as we,r as Te,s as C,u as Ee}from"./human-control-contract.js";import{i as w}from"./request-runtime-binding.js";import{r as De}from"./application-lifecycle-runtime.js";import{a as Oe,c as T,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 E}from"./perf-runtime-plan.js";import{n as ze,r as Be,t as Ve}from"./lease-context.js";import{h as He,l as Ue,u as We}from"./screenshot-runtime.js";import{t as Ge}from"./device-isolation.js";import{a as Ke,c as qe,d as D,l as Je,n as Ye,o as Xe,r as Ze,u as O}from"./src8.js";import{n as Qe,t as $e}from"./compatibility-policy.js";import{o as et}from"./screen-recording-resource-recovery.js";import k from"node:path";import"node:fs";import tt,{createHash as nt}from"node:crypto";import rt from"node:os";import A from"node:fs/promises";function it(t,n){if(n?.replayBackend&&n.replayBackend!==`maestro`)throw new e(`INVALID_ARGS`,`Unsupported replay backend "${n.replayBackend}".`);return{...se(t),metadata:ce(t)}}function at(e,t){return j(e,t)?t:`${e}:${t}`}function j(e,t){return t.startsWith(`${e}:`)}function ot(e,t){return!e.partitioned||j(e.tenant,t)}var st=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)}}},ct=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())}},lt=class{holdsByDevice=new Map;mutations=new st;inFlightWork=new ct;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=xe(e),this.now=e.now??(()=>Date.now()),this.onLeaseExpired=e.onLeaseExpired,this.providerSessionOwnership=new pe({now:this.now,retentionMs:e.providerSessionRetentionMs})}allocateLease(e){let t=we(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=ge(t,n,this.now());return this.leases.set(i.leaseId,i),this.bindLease(i),{...i}}refreshExistingRunBinding(e,t){let n=_e(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 Ee(i);return C(i,e),this.refreshLease(i,t)}heartbeatLease(e){let t=ve(e.leaseId);this.cleanupExpiredLeases();let n=this.getActiveLease(t);Ce(n,e),C(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=ve(e.leaseId);this.cleanupExpiredLeases();let n=this.leases.get(t);if(n)return Ce(n,e),C(n,e),{...n}}assertLeaseAdmission(e){let t=Se(e);this.cleanupExpiredLeases(),C(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`?x(this.requireHumanControlLease(e.leaseId)):void 0;return[...this.holdsByDevice.entries()].filter(([e])=>t===void 0||t===e).flatMap(([,e])=>[...e.values()].map(({hold:e})=>S(e))).sort((e,t)=>e.id.localeCompare(t.id))}async putHumanControlHold(t,n,r,i){i?.throwIfAborted();let a=be(n),o=he(r);this.cleanupExpiredLeases();let s=this.resolveHumanControlScope(t,o),c=x(s),l=this.findHumanControlHold(a);if(l&&(this.assertHoldAuthority(t,l),x(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),S(n.hold)}catch(e){throw a.get(o)===n&&this.deleteHumanControlHold(t,o),e}}removeHumanControlHold(e,t){let n=be(t);this.cleanupExpiredLeases();let r=this.findHumanControlHold(n);if(!r)return;this.assertHoldAuthority(e,r);let i=x(r.hold.scope);return this.deleteHumanControlHold(i,n),S(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=x(e),n=t===void 0?void 0:this.holdsByDevice.get(t)?.values().next().value;if(n)throw Te(n.hold)}async runDeviceMutation(e,t){if(!e)return await t();this.cleanupExpiredLeases();let n=this.getActiveLease(e.leaseId);this.assertHumanControlAdmission(n);let r=x(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||x(r)!==x(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=x(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=ye(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(_e(e),e.leaseId);let t=x(e);t&&this.deviceBindings.set(t,e.leaseId)}unbindLease(e,t=this.now()){this.runBindings.delete(_e(e));let n=x(e);n&&this.deviceBindings.delete(n),this.providerSessionOwnership.markLeaseReleased(e,t)}assertDeviceAvailable(e){let t=x({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 Ee(r)}};function ut(t){let n=ue(t.meta?.sessionIsolation??t.flags?.sessionIsolation),r=t.meta?.tenantId??t.flags?.tenant,i=de(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 j(i,a)?{...t,meta:{...t.meta,tenantId:i,sessionIsolation:n}}:{...t,session:at(i,a),meta:{...t.meta,tenantId:i,sessionIsolation:n}}}function dt(t,n,r,i={}){if(We(t.command))return;let a=ze(t);mt(t,a);let o=r?.lease;if(r===void 0&&!a.leaseId&&ft(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;ht(a,o);let s=Be(t,r),c={...s,leaseTtlMs:s.leaseTtlMs??(h(s)?3e5:void 0)};n.assertLeaseAdmission(p(s));let l=n.heartbeatLease(p(c));return Ue(t)&&n.assertHumanControlAdmission(l),l}function ft(e,t){let n=He(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function pt(e){We(e.command)||mt(e,ze(e))}function mt(t,n){if(t.command!==`open`)return;let r=m(n);if(r.length!==0)throw new e(`INVALID_ARGS`,`Proxy open requires leaseId, tenantId, runId, clientId, and deviceKey lease metadata.`,{missing:r})}function ht(e,t){t&&(M(`leaseId`,e.leaseId,t.leaseId),M(`tenantId`,e.tenantId,t.tenantId),M(`runId`,e.runId,t.runId),M(`leaseProvider`,e.leaseProvider,t.leaseProvider),M(`clientId`,e.clientId,t.clientId),M(`deviceKey`,e.deviceKey,t.deviceKey))}function M(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 gt(e,t){if(!t.leaseProvider||!e)return!1;try{return await e(t),v({level:`info`,phase:`provider_lease_expired_released`,data:{leaseId:t.leaseId,provider:t.leaseProvider}}),!0}catch(e){return v({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 _t(e){pt(e)}async function vt(e){let t=e.sessionStore.get(e.sessionName),n=t?.lease;return!t||!n||!e.leaseRegistry.consumeExpiredLease(n.leaseId)?!1:(v({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=>{v({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=>{v({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 yt(e){let{sessionName:t,sessionStore:n,leaseRegistry:r}=e,i=n.get(t),a=dt(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 bt(e){return Ve(e.req,e.req.internal?.admittedLease)??e.existingLease}async function xt(e){let t=e.session.lease;if(!t)return;let n=f({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=fe(i);r&&a&&e.leaseRegistry.recordProviderSession(r,a);let o=e.leaseRegistry.releaseLease(n);return v({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:o.released}}),i}const St=[`platform`,`target`],Ct=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function wt(e){return u({deviceName:e?.device,udid:e?.udid,serial:e?.serial})}function Tt(e){return wt(e)||Ot(e,St)}function Et(e){return Tt(e)||Ot(e,Ct)}function Dt(e){return typeof e==`string`&&e.trim().length>0}function Ot(e,t){return e?t.some(t=>Dt(e[t])):!1}function kt(e){return{appleSimulatorAppTarget:At(e)}}function At(e){return e&&!i(e)?e:void 0}function jt(e){return`${e.device.platform} device "${e.device.name.trim()}" (${e.device.id})`}function N(e,t){return e.session.screenRecording?Nt(e.address,t):Pt(e.address,t)}function Mt(e,t){return w(`DEVICE_IN_USE`,`Device is already in use by session "${e.address}".`,{session:e.address,deviceId:t.id,deviceName:t.name,hint:N(e,`device-in-use`)})}function Nt(e,t){let n=y(e),r=`agent-device close --session ${n}`;return`Recording session "${e}" owns this device. Run ${`agent-device record stop --session ${n}`}; if the session still appears in agent-device session list, run ${r}. ${t===`selector-conflict`?`To keep using this device, rerun the command with --session ${n} and remove conflicting device selectors.`:`To keep using this device, reuse --session ${n} for commands that should attach to the recording session.`} Run agent-device session list to inspect active sessions.`}function Pt(e,t){let n=y(e),r=`agent-device close --session ${n}`;return t===`selector-conflict`?`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${n} and remove conflicting device selectors. To switch devices, first run ${r}, then open the desired device with a different --session name.`:`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${n}. To open a new session on this device, first run ${r}.`}function Ft(t,n){let{address:r,session:i}=t,a=It(i,n);if(a.length!==0)throw new e(`INVALID_ARGS`,`Session "${r}" is already bound to ${jt(i)}, but this request selected ${a.map(P).join(`, `)}.`,{session:r,conflicts:a.map(P),hint:N(t,`selector-conflict`)})}function It(e,t){if(!t)return[];let n=[],r=e.device,i=t.platform;if(i&&!o(r,i)&&n.push({key:`platform`,value:t.platform}),t.target&&t.target!==(r.target??`mobile`)&&n.push({key:`target`,value:t.target}),t.udid&&(!c(r)||t.udid!==r.id)&&n.push({key:`udid`,value:t.udid}),t.serial&&(!l(r.platform)||t.serial!==r.id)&&n.push({key:`serial`,value:t.serial}),t.device&&t.device.trim().toLowerCase()!==r.name.trim().toLowerCase()&&n.push({key:`device`,value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),i=r.simulatorSetPath?.trim();(!c(r)||r.kind!==`simulator`||e!==i)&&n.push({key:`iosSimulatorDeviceSet`,value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=Ge(t.androidDeviceAllowlist);(r.platform!==`android`||!e.has(r.id))&&n.push({key:`androidDeviceAllowlist`,value:t.androidDeviceAllowlist})}return n}function P(e){return`${Lt(e.key)}=${e.value}`}function Lt(e){switch(e){case`iosSimulatorDeviceSet`:return`--ios-simulator-device-set`;case`androidDeviceAllowlist`:return`--android-device-allowlist`;default:return`--${e}`}}function Rt(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return nt(`sha256`).update(ae(t),`utf8`).digest(`hex`)}function zt(e,t,n){return new Jt(Vt(Bt(t.resolve(e))),n).parse()}function Bt(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Vt(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=Ht(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 Ht(e){return Ut(e)??Wt(e)??Gt(e)??Kt(e)??qt(e)}function Ut(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function Wt(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Gt(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Kt(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function qt(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var Jt=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 Yt(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Xt(e,t){return{...L(e,t),source:e.source}}function F(t,n,r){if(t===void 0)return;let i=r??Ke[n]??{},a=Xe(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 Zt(e,t,n,r){return F(e===void 0?t:n.resolve(String(e)),r)}function I(e){if(e?.aborted)throw t()}async function Qt(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 I(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 $t(e,t){if(e.include.kind===`file`)return k.resolve(t?k.dirname(t):process.cwd(),e.include.path)}function en(e){return e===void 0?void 0:k.resolve(e)}function tn(t,n){let r=$t(t,t.source.path);if(r&&n.has(r))throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function nn(t,n,r,i){let a=t.include.kind===`file`?en(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 rn(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:zt(e.true,t,n.platform)}function an(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function L(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>L(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,L(n,t)])):e}async function on(e,t){I(t.signal);let n=en(e.source.path),r={options:t,context:qe(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await sn(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function sn(e,t,n,r,i){I(i.options.signal);let a=_n(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 ln(s,a,o,e.source.path??r,i));return n}finally{s()}}async function cn(e,t,n,r,i){let a=[];for(let o of e)a.push(...await ln(o,t,n,r,i));return a}async function ln(e,t,n,r,i){I(i.options.signal);let a=vn(e,r);switch(a.kind){case`runFlow`:{let e=dn(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await un(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[R(a,t,n,o)]}case`repeat`:return[R(a,t,n,await cn(a.commands,t,n,r,i))];case`retry`:return[R(a,t,n,await cn(a.commands,t,n,r,i))];default:return[hn(a,t,n)]}}async function un(e,t,n,r,i){let a=pn(e,i.context),o=tn(a,i.activeIncludePaths),s=await Qt(a,i.options);I(i.options.signal);let c=nn(a,s,o,i.activeIncludePaths),l=_n(t,e.env),u=i.context.enter(e.env);try{return await sn(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function dn(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:fn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function fn(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return mn(t.context.resolveDeferred(e))?`opaque`:zt(e,t.context,t.options.platform)?void 0:`omit`}function pn(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function mn(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function hn(e,t,n){return D({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function R(e,t,n,r){return D({kind:`opaque`,command:gn(e),source:e.source,scopes:t,body:r,appId:n})}function gn(e){switch(e.kind){case`runFlow`:return D({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 D({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function _n(e,t){return t===void 0?e:[...e,t]}function vn(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function yn(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await on(e,t),a=bn(t.runtimeHints),o=D({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=Rt(o);return xn({...o,digest:s})}function bn(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 xn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))xn(t);return Object.freeze(e)}function Sn(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 Cn(t,n={}){let r=Sn(t,n);if(!r.allowed)throw new e(`INVALID_ARGS`,r.reason);return r.startIndex}function wn(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 Tn=`maestro-test-failure`;function z(t,n={}){return new e(`COMMAND_FAILED`,t,{...n,reason:Tn})}function En(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&t.details?.reason===Tn}const Dn=new Set([``,`false`,`0`,`null`,`undefined`]);function On(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!Dn.has(e)}async function kn(e,t){I(t.options.signal);try{return await Hn(e,t.context,async()=>await An(e,t))}catch(t){throw H(t,e)}}async function An(e,t){if(e.kind===`command`)return await jn(e.command,e.appId,t);await Ln(e,t)}async function jn(e,t,n){if(e.kind===`evalScript`)return await Pn(e,n);let r=Xt(e,n.context);try{return await Fn(r,t,n)}catch(e){if(I(n.options.signal),Nn(r)&&En(e)){n.warnings.push(Mn(r,e)),n.skipped+=1;return}throw Un(e,r)}}function Mn(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 Nn(e){return`optional`in e&&e.optional===!0}async function Pn(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 Fn(e,t,n){switch(e.kind){case`assertVisible`:await V({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await V({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!On(e.condition))throw z(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await V(Vn(e),F(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await In(e,t,n)}}async function In(e,t,n){let r=D({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 I(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 Ln(e,t){let n=Xt(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await zn(n.when,t)){t.skipped+=1;return}t.executed+=1,await B(e.body,t);return;case`repeat`:{let r=Zt(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)I(t.options.signal),await B(e.body,t);return}case`retry`:{let r=Math.min(Zt(n.maxRetries,1,t.context,`retry.maxRetries`),Qe.control.retryMaxRetries);t.executed+=1,await Rn(e.body,r,t);return}}}async function B(e,t){for(let n of e)await kn(n,t)}async function Rn(t,n,r){let i;for(let e=0;e<=n;e+=1){I(r.options.signal);try{await B(t,r);return}catch(e){if(I(r.options.signal),!En(Gn(e)))throw e;i=H(e,t[0])}}throw i||new e(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function zn(e,t){if(!rn(e,t.context,t.options))return!1;for(let n of an(e))if(I(t.options.signal),!(await Bn(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function V(e,t,n){if(!(await Bn(e,t,n)).matched)throw z(`Maestro ${e.kind} condition did not match.`)}async function Bn(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 I(n.options.signal),n.context.recordObservation(i),i}function Vn(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 Hn(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 H(e,t){if(Wn(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Kn(e,t?.command),source:n,...t?{command:t.command}:{}}}function Un(e,t){return{kind:`maestroPlanStepFailure`,error:Kn(e,t),source:t.source,command:t}}function Wn(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Gn(e){return Wn(e)?e.error:e}function Kn(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 qn(t,n,r={}){I(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:qe(r.defaults,r.env?{...r.env}:{}),timing:$e,artifacts:new Set,warnings:[],executed:t.compatibility.staticallyExecutedControls,skipped:t.compatibility.staticallySkippedControls};for(let e=i;e<t.steps.length;e+=1)try{await Jn(t.steps[e],e,a)}catch(e){throw Gn(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Jn(e,t,n){I(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};U(()=>n.options.observer?.commandStarted?.(s));try{let t=await kn(e,n);I(n.options.signal),U(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Yn(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=H(t,e);throw U(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Yn(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts]})),o}}function Yn(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 U(e){try{e?.()}catch{}}async function Xn(e,t,n={}){let r=Zn(e,n);return await qn(e,t,{...n,startIndex:r})}function Zn(e,t){return t.from!==void 0||t.planDigest!==void 0?Cn(e,{from:t.from,planDigest:t.planDigest}):wn(e,t.startIndex??0)}function Qn(e){return Yt(e)?{command:e.kind,...e.kind===`runFlow`?G(e.label??e.includePath):{}}:{command:e.kind,...$n(e)}}function $n(e){return`label`in e&&e.label?G(e.label):er(e)?G(sr(e.target)):tr(e)?nr(e):e.kind===`inputText`?G(`<text>`):rr(e)}function er(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function tr(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function nr(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return G(W(e.target));case`extendedWaitUntil`:return G(W(e.visible??e.notVisible));case`scrollUntilVisible`:return G(W(e.element))}}function rr(e){return ir(e)?ar(e):e.kind===`swipe`?or(e):e.kind===`runFlow`?G(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?G(String(e.condition)):{}}function ir(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function ar(e){switch(e.kind){case`openLink`:return G(e.link);case`takeScreenshot`:return G(e.path);case`runScript`:return G(e.file);case`pressKey`:return G(e.key)}}function or(e){return G(e.gesture.kind===`coordinates`?`${cr(e.gesture.start)} to ${cr(e.gesture.end)}`:e.gesture.direction)}function sr(e){return e.space===`target`?W(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function W(e){return e?.id??e?.text}function cr(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function G(e){return e?{value:e}:{}}const lr=new Set(String.raw`^$\.*+?()[]{}|`);function ur(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function dr(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(lr.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!lr.has(i))return;t+=i,n+=1}return t}function fr(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(_(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=>ne(e,n)?e:null);return r?_(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function pr(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function mr(e,t){let n=[t.id===void 0?void 0:gr(e.identifier,t.id),t.text===void 0?void 0:_r(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 hr(e){return e.matches.filter(t=>fr(t,e.visibility,e.platform))}function gr(e,t){let n=e??``;return O(n)===O(t)||ur(n,t)}function _r(e,t){return[e.label,Je(e),e.identifier].filter(e=>!!e).some(e=>gr(e,t))}function vr(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 yr(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function br(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=Sr(a.rect,e.rect);n===void 0||!xr(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 xr(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 Sr(e,t){if(!(!Cr(e)||!Cr(t)))return Math.fround(Math.hypot(K(e.x,e.width)-K(t.x,t.width),K(e.y,e.height)-K(t.y,t.height)))}function Cr(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function K(e,t){return e+Math.trunc(t/2)}function wr(t,n={},r={}){let i=te(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=br(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=Tr(t,i,l,u,m,p),n={matches:e,indexed:kr(e,i.index,r.orderUnindexed)};return a.set(i,n),n}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function Tr(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=yr(m)?e.nodes.filter(e=>mr(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>Dr(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=>Er(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of Or(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function Er(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function Dr(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Or(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function kr(e,t,n){if(t===void 0)return n?n(e):[...e];let r=jr(e)[Mr(t)];return r?[r]:[]}function Ar(e,t){return t===void 0?e[0]:jr(e)[Mr(t)]}function jr(e){return[...e].sort((e,t)=>{let n=q(e.rect?.y),r=q(t.rect?.y);return n===r?q(e.rect?.x)-q(t.rect?.x):n-r})}function q(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function Mr(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 Nr={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Pr(e,t){let n=Nr[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 J(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Fr(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Fr(e){return e===!0?2:+(e===!1)}function Ir(e,t,n,r={}){let i=Pr(e,n),a=Rr(e,i,r),o=Lr(t,a),s=hr({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:zr(s,t,n,a.visibility,i)}}function Lr(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Rr(e,t,n={}){return wr(e,n,t?{orderUnindexed:e=>J(e,t)}:{})}function zr(e,t,n,r,i){let a=n!==`ios`||!Ur(t)?e:e.filter(n=>{if(Kr(n))return!0;let i=e.filter(e=>e!==n&&Wr(n,e,t));return!i.some(e=>Kr(e)&&pr(n,e,r))&&!i.some(e=>pr(e,n,r))});return t.index===void 0&&i?J(a,i):a}function Br(e,t){let n=t===void 0?e.find(Y):Vr(e,t);return!n||!Y(n)?null:{node:n,rect:n.rect}}function Vr(e,t){return Ar(e,t)}function Hr(e){return Y(e)?e.rect:void 0}function Y(e){return _(e.rect)}function Ur(e){return e.id!==void 0||e.text!==void 0}function Wr(e,t,n){if(n.id!==void 0&&X(e.identifier)!==X(t.identifier))return!1;if(n.text!==void 0){let n=Gr(e),r=new Set(Gr(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Gr(e){return[e.label,e.value,e.identifier].map(X).filter(e=>e!==void 0)}function X(e){if(e)return O(e)||void 0}function Kr(e){let t=ee(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const qr=Symbol(`maestroFlowProgram`),Jr=Symbol(`maestroFailureCommand`),Yr=Symbol(`maestroFailurePlan`);function Xr(e,t){let n=Ze(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:ei(n),[qr]:n}}async function Zr(e,t,n){let r;try{let i=Ye(k.dirname(e.sourcePath),n.readSource),a=await yn(e[qr],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=Cn(a,{from:n.from,planDigest:n.planDigest}),s=await Xn(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:$r(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 Qr(e,t){let n=ni(e[Jr]),r=e[Yr].platform;return!n||r!==`android`&&r!==`ios`?[]:Ir(t,n.selector,r).ranked.map(e=>({node:e,basis:ri(n.selector,e)}))}function $r(e,t,n){return{commandStarted:e=>t?.actionStarted?.(Z(e)),commandCompleted:e=>t?.actionCompleted?.({...Z(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=Sn(e,{from:r.stepIndex,planDigest:e.digest}),a={...Z(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,isControl:Yt(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},[Jr]:r.command,[Yr]:e};n(a),t?.actionFailed?.(a)}}}function Z(e){let t=Qn(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function ei(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(ti)}function ti(e){return!!(e?.trim()&&!e.includes(`$`)&&!i(e))}function ni(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 ri(e,t){return e.id!==void 0||e.text!==void 0&&mr({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}const ii=`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 ai(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 oi(e){if(e.command!==`replay`||e.flags?.replayFrom!==void 0)return;let t=e.flags?.replayScriptSource;if(t)try{let n=t.entry,r=ai(t,n);if(le(n,e.flags?.replayBackend)===`maestro`){let t=Xr(r,n);return{flags:e.flags??{},options:si(t.appTarget,e.flags?.platform)}}let i=it(r,e.flags),a=ci(i.actions);if(!a.appTarget)return;let o=li(e.flags,i.actions),s=o.platform??i.metadata.platform;return{flags:s&&o.platform===void 0?{...o,platform:s}:o,options:s===`ios`?di(a.appTarget):void 0}}catch{return}}function si(e,t){return t===`ios`?di(e)??{}:{}}function ci(e){let t=oe(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return ui(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function li(e,t){let n=ci(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function ui(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!i(e))}function di(e){let t=At(e);return t?{appleSimulatorAppTarget:t}:void 0}const fi={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.`},Q=new Map;async function pi(e){let t=await A.mkdtemp(k.join(rt.tmpdir(),`agent-device-materialized-`));try{let n=await _i(e.installablePath,k.join(t,`installable`)),r=e.archivePath?await _i(e.archivePath,k.join(t,`archive`)):void 0,i=tt.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{gi(i)},a);return Q.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 A.rm(t,{recursive:!0,force:!0}),e}}async function mi(e,t){await $(e,me(Q,e,t,fi))}async function hi(e){let t=Array.from(Q.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await $(e,t)}))}async function gi(e){let t=Q.get(e);if(t)try{await $(e,t)}catch{}}async function $(e,t){clearTimeout(t.timer),Q.delete(e),await A.rm(t.rootPath,{recursive:!0,force:!0})}async function _i(e,t){let n=await A.stat(e);await A.mkdir(t,{recursive:!0});let r=k.join(t,k.basename(e));return n.isDirectory()?(await A.cp(e,r,{recursive:!0}),r):(await A.copyFile(e,r),r)}function vi(e){return e.device.platform===`web`}function yi(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function bi(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 xi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.perfCapture&&await Le({...e,session:t})}async function Si(e,t){await t.stopSnapshotHelper(e.device)}async function Ci(e){let{session:t,sessionName:n,sessionStore:r,platformCleanup:i}=e;await i.closeManagedBrowser({device:t.device,sessionName:n,stateDir:r.resolveDaemonStateDir(),openSessionNames:()=>yi(r)})}async function wi(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 Ti(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 v({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 Ei(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:()=>Di({session:n,sessionName:r,sessionStore:i})},...t.appLog===`run`?[{step:`app_log`,run:()=>bi({session:n,sessionName:r,sessionStore:i})}]:[],{step:`audio_probe`,run:()=>Oi({session:n,sessionName:r,sessionStore:i})},{step:`perf_capture`,run:()=>xi({session:n,sessionName:r,sessionStore:i})},{step:`platform_snapshot_helper`,run:()=>Si(n,a)},{step:`web_browser`,run:()=>Ci({session:n,sessionName:r,sessionStore:i,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>hi(r)});let s=Ti({sessionName:r,phase:`session_teardown_cleanup_failed`,failures:await wi(o)});if(s)throw s}async function Di(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.screenRecording&&await et({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}async function Oi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.audioProbe&&await Fe({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}function ki(e){return c(e)&&e.kind===`simulator`}function Ai(e){return e.platform===`android`&&e.kind===`emulator`}const ji=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function Mi(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Ni(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 Pi(e){return De(Ni(e))}function Fi(t,n){if(t!==void 0){if(typeof t!=`string`)throw new e(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return b(t)}}function Ii(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 Li(t){if(t!==void 0){if(typeof t!=`number`)throw new e(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Ii(t)}}function Ri(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 zi(e){if(n(e))return e}function Bi(e,t){return{platform:t,metroHost:b(e?.metroHost),metroPort:Ii(e?.metroPort),bundleUrl:b(e?.bundleUrl),launchUrl:b(e?.launchUrl)}}function Vi(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 Hi(e){if(Ai(e))return`10.0.2.2`;if(ki(e))return`127.0.0.1`}function Ui(e,t){if(!e||b(e.metroHost)||b(e.bundleUrl)||e.metroPort===void 0)return e;let n=Hi(t);return n?{...e,metroHost:n}:e}function Wi(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=>!ji.includes(e));if(o)throw new e(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${ji.join(`, `)}.`);return{platform:Ri(a.platform,r,i),metroHost:Fi(a.metroHost,`metroHost`),metroPort:Li(a.metroPort),bundleUrl:Fi(a.bundleUrl,`bundleUrl`),launchUrl:Fi(a.launchUrl,`launchUrl`)}}function Gi(e,t,n){if(n){if(Mi(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Ki(t,n,r,i){let a=t.getRuntimeHints(n);if(!a)return;let o=r?d(r):void 0,s=zi(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 qi(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?zi(d(i)):e.platform,o=n.getRuntimeHints(r),s=Wi({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=Ki(n,r,i,a);return{runtime:i?Ui(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&Mi(s)>0?s:void 0;return{runtime:i?Ui(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Ji(e){return qi(e).runtime}function Yi(e){try{return{ok:!0,data:qi(e)}}catch(e){let t=r(e);return w(t.code,t.message,t.details)}}async function Xi(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!Zi(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:Ni(t)})}function Zi(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Pi(e.previousRuntime)&&!Pi(e.runtime)}function Qi(e){let{device:t,owner:n,stateDir:r,intent:i}=e,a=i.kind===`exact-owner`&&ie(i.owner,n)?re(i.fence):null;if(!a)return{status:`binding-invalid`};let o=T(E(t)),s=Me(ke(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!ea(c.stateDir,r)||!ie(je(c),n)?{status:`conflict`,conflict:s}:c.allocator.identityIncarnationId===a.identityIncarnationId?{status:`covered`}:{status:`incarnation-stale`,heldIncarnationId:c.allocator.identityIncarnationId}}function $i(e){let t=T(E(e));return Oe(ke(t))}function ea(e,t){return k.resolve(e)===k.resolve(t)}const ta=new Set([`DEVICE_CLAIM_LIVE_OWNER`,`DEVICE_CLAIM_RECOVERY_PENDING`,`DEVICE_CLAIM_OWNER_UNCERTAIN`]);function na(e){return ta.has(e)}function ra(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=d(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=s(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${y(i)}`,`${a} ${y(e.id)}`,...n===`release`||Ae(t.classification)?[`--stale`]:[]].join(` `)}function ia(t,n){if(n.classification===`allocator-held`)return oa(t,n);let r=n.claim,i=ra(t,n,Ne(n.classification)?`release`:`status`),a=d(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:pa(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 aa(e,t){return fa(ia(e,t))}function oa(t,n){let r=n.allocatorClaim,i=d({platform:r.device.family,appleOs:r.device.appleOs}),a=ra(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 sa(t,n){return new e(`COMMAND_FAILED`,`${d(t)} device ${t.id} is a managed identity with no allocator-held execution claim for this installation.`,{reason:`allocator-claim-missing`,owner:g(n),deviceKey:T(E(t)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function ca(t,n,r){return new e(`COMMAND_FAILED`,`${d(t)} device ${t.id} is held for identity incarnation "${r}", which is not the incarnation this binding fences.`,{reason:`allocator-claim-incarnation-stale`,owner:g(n),deviceKey:T(E(t)),heldIncarnationId:r,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function la(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:g(n),deviceKey:T(E(t)),retriable:!1})}function ua(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:la(e,t)};case`missing`:return{admitted:!1,error:sa(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:ca(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:ia(e,n.conflict)}}}function da(e,t,n){let r=ua(e,t,n);return r.admitted?void 0:fa(r.error)}function fa(e){let{hint:t,retriable:n,...r}=e.details??{};return w(e.code,e.message,r,{hint:t,retriable:n})}function pa(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 ma(e){switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{dr as $,hi as A,Rr as B,bi as C,vi as D,Ei as E,ii as F,Vr as G,Ir as H,ai as I,Pr as J,Hr as K,Qr as L,si as M,li as N,yi as O,oi as P,fr as Q,Zr as R,Ti as S,Si as T,zr as U,Lr as V,Br as W,vr as X,wr as Y,hr as Z,Zi as _,xt as _t,ia as a,Mt as at,Oi as b,lt as bt,Qi as c,kt as ct,Pi as d,Et as dt,z as et,Xi as f,Dt as ft,Gi as g,gt,Ni as h,vt as ht,ua as i,It as it,pi as j,mi as k,Bi as l,Tt as lt,Ji as m,_t as mt,da as n,Ft as nt,na as o,N as ot,Vi as p,yt as pt,J as q,aa as r,P as rt,$i as s,jt as st,ma as t,F as tt,Mi as u,wt as ut,zi as v,bt as vt,xi as w,Di as x,ot as xt,Yi as y,ut as yt,Xr as z};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { O as Rect } from "./sdk-contracts.js";
|
|
2
2
|
import { D as PointerTrajectorySample, E as PointerTrajectory, O as SinglePointerGesturePlan, T as MultiTouchGesturePlan } from "./sdk-selectors.js";
|
|
3
3
|
import { Readable, Stream, Writable } from "node:stream";
|
|
4
4
|
//#region packages/platform-android/src/helper-artifacts.d.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime.js";import{
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{A as t,C 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 n(`COMMAND_FAILED`,`Device inventory gateway is unavailable outside request execution`,{reason:a});return e}function m(e){return t(e)||e instanceof n&&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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";const t=[`portrait`,`portrait-upside-down`,`landscape-left`,`landscape-right`],n={portrait:0,"landscape-left":1,"portrait-upside-down":2,"landscape-right":3};function r(e){return n[e]*90}function i(e){return n[e]%2==0?`PORTRAIT`:`LANDSCAPE`}function a(t){if(t===void 0)throw new e(`INVALID_ARGS`,`orientation requires an orientation argument. Use portrait|portrait-upside-down|landscape-left|landscape-right.`);switch(t?.trim().toLowerCase()){case`portrait`:return`portrait`;case`portrait-upside-down`:case`upside-down`:return`portrait-upside-down`;case`landscape-left`:case`left`:return`landscape-left`;case`landscape-right`:case`right`:return`landscape-right`;default:throw new e(`INVALID_ARGS`,`Invalid rotation: ${t}. Use portrait|portrait-upside-down|landscape-left|landscape-right.`)}}export{a,r as i,n,i as r,t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime.js";import{
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{C as t}from"./sdk-contracts.js";import{g as n,l as r,m as i,o as a,x as o}from"./sdk-device.js";var s=e({markSelectionBootOccurred:()=>u,resolveExistingSessionDeviceSelection:()=>l,resolveInventoryDeviceSelection:()=>c});async function c(e){let{devices:t,selector:r,source:i}=e,s=a(r);if(i===`provider`&&!s)return p(t,r);if(i===`local`&&!s){let n=await m(t,r,e.appleSimulatorAppTarget);if(n)return n}let c=t.filter(e=>n(e,r,{includeExplicitSelectors:s}));try{return d(await o([...t],r),c,{explicitSelector:s,source:i})}catch(e){throw h(e,c)}}function l(e){return{device:e,reason:`existing-session`,source:`session`,candidateCount:1,bootOccurred:!1}}function u(e){if(!e||e.source!==`local`)return e;let{device:t}=e;return t.booted!==!0&&(t.kind===`simulator`||t.kind===`emulator`)?{...e,bootOccurred:!0}:e}function d(e,t,n){return{device:e,reason:n.explicitSelector?`explicit-selector`:n.source===`provider`?`single-provider-device`:f(e,t),source:n.source,candidateCount:t.length,bootOccurred:!1}}function f(e,t){return e.booted===!0&&t.filter(e=>e.booted===!0).length===1?`single-booted-local`:!e.booted&&t.length===1?`single-bootable-local`:`preferred-local`}async function p(e,r){let i=e.filter(e=>n(e,r)),a=i[0];if(a!==void 0&&i.length===1)return d(a,i,{explicitSelector:!1,source:`provider`});try{await o([...e],r)}catch(e){throw h(e,i)}throw new t(`AMBIGUOUS_MATCH`,`Multiple provider devices match this request.`,{...g(i),matches:i.length,hint:`Select the leased provider device explicitly with --device, --udid, or --serial.`,retrySelectors:_(i)})}async function m(e,i,a){let o=a?.trim();if(!o)return;let{readInstalledAppProbe:s}=await import(`./device-inventory-context.js`).then(e=>e.t),c=s();if(!c)return;let l=e.filter(e=>n(e,i)&&r(e)&&e.kind===`simulator`&&e.booted===!0);if(l.length<2)return;let u=(await Promise.all(l.map(async e=>await c(e,o)?e:void 0))).filter(e=>e!==void 0),d=u[0];if(d!==void 0&&u.length===1)return{device:d,reason:`single-app-installed-local`,source:`local`,candidateCount:1,bootOccurred:!1};throw u.length===0?new t(`APP_NOT_INSTALLED`,`No booted iOS simulator has ${o} installed`,{appTarget:o,...g(l),hint:`Install the app on a booted simulator, or pass --udid to select the intended device explicitly.`,retrySelectors:_(l)}):new t(`AMBIGUOUS_MATCH`,`Multiple booted iOS simulators have ${o} installed`,{appTarget:o,...g(u),hint:`Pass --udid to select the intended simulator explicitly.`,retrySelectors:_(u)})}function h(e,n){return!(e instanceof t)||e.code!==`AMBIGUOUS_MATCH`?e:new t(e.code,e.message,{...e.details??{},...g(n),retrySelectors:_(n)},e)}function g(e){return{devices:e.slice(0,10).map(e=>({id:e.id,name:e.name}))}}function _(e){return e.slice(0,10).flatMap(e=>[{flag:i(e.platform)?`--serial`:`--udid`,value:e.id},{flag:`--device`,value:e.name}])}export{u as n,l as r,s as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{r as t}from"./sdk-batch-runner.js";import{n}from"./app-inventory.js";import"./device.js";import{t as r}from"./request-cancellation.js";import{n as i,t as a}from"./ios-client.js";import{n as o,r as s}from"./snapshot.js";import c from"node:path";import l from"node:fs";import u from"node:os";import{setTimeout as d}from"node:timers/promises";function f(e){return e?.trim()||void 0}async function p(e,t){let n=await i({apiUrl:e.apiUrl,adbUrl:e.adbUrl,token:e.token,logLevel:`warn`}),r={platform:`android`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t},a={exec:async(e,t)=>await y(r,e,t),text:async e=>{await n.setText(e.target,e.text)}};return a.reverse=await t.android.createPortReverse(a.exec),Object.assign(r,{adbProvider:a})}function m(e){return e.dependencies.android.createInteractor(e.device,e.adbProvider)}async function h(e,t,n,i,a,o){a?.throwIfAborted();let s=f(i?.packageNameHint);i?.relaunch&&s&&await y(t,[`shell`,`am`,`force-stop`,s],{allowFailure:!0,signal:a});let c=await r(o,e.assets.getOrUpload({path:n,name:T(s,n)},{signal:a}),a);await r(o,t.client.sendAsset(c.signedDownloadUrl),a),a?.throwIfAborted();let l=s?await t.dependencies.android.inferAppName(s):void 0;return{...s?{packageName:s,launchTarget:s}:{},...l?{appName:l}:{}}}async function g(e,t){await e.adbProvider.reverse?.ensure({local:w(t.devicePort),remote:w(t.hostPort),ownerId:t.name})}async function _(e){await e.adbTunnelPromise?.catch(()=>{});let t=e.adbSerial;t&&(await v(e),await e.dependencies.host.runAdb([`disconnect`,t],{allowFailure:!0,timeoutMs:1e4}).catch(()=>{})),e.adbTunnel?.close(),e.adbTunnel=void 0,e.adbSerial=void 0,e.adbTunnelPromise=void 0}async function v(e){let t=e.adbProvider.reverse;if(!t?.list)return;let n=await t.list().catch(()=>[]),r=new Set,i=[];for(let e of n)e.ownerId?r.add(e.ownerId):i.push(e.local);await Promise.allSettled([...[...r].map(async e=>await t.removeAllOwned(e)),...i.map(async e=>await t.remove(e))])}async function y(e,t,n){let{adbArgs:r,result:i}=await b(e,t,n);return await x(r,i,n?.allowFailure,e.dependencies)}async function b(e,t,n){let r=[`-s`,await S(e),...t];return{adbArgs:r,result:await e.dependencies.host.runAdb(r,{allowFailure:n?.allowFailure,binaryStdout:n?.binaryStdout,stdin:n?.stdin,timeoutMs:n?.timeoutMs??3e4,signal:n?.signal})}}async function x(e,t,n,r){if(t.exitCode!==0&&n!==!0)throw await r.android.adbError(`Limrun Android ADB command failed`,t,{command:[`adb`,...e].join(` `)});return t}async function S(e){if(e.adbSerial)return e.adbSerial;let t=e.adbTunnelPromise??C(e);e.adbTunnelPromise=t;try{return await t}catch(n){throw e.adbTunnelPromise===t&&(e.adbTunnelPromise=void 0),n}}async function C(e){let t=await e.client.startAdbTunnel(),n=`${t.address.address}:${t.address.port}`;return e.adbTunnel=t,e.adbSerial=n,n}function w(t){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid Android tcp reverse port: ${t}`);return`tcp:${t}`}function T(e,t){let n=c.extname(t)||`.apk`;return`${e?.replaceAll(/[^a-zA-Z0-9_.-]+/g,`-`)||`android-app`}${n}`}async function E(e,t){let n=await a({apiUrl:e.apiUrl,token:e.token,logLevel:`warn`});return{platform:`ios`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t}}async function D(e,t,n,i,a,o){a?.throwIfAborted();let s=await j(n,t.dependencies);try{a?.throwIfAborted();let n=await r(o,e.assets.getOrUpload({path:s.uploadPath,name:s.assetName},{signal:a}),a),c=(await O(t,n.signedDownloadUrl,{md5:n.md5,relaunch:i?.relaunch,appIdentifierHint:i?.appIdentifierHint},a,o)).appId;return{...c?{bundleId:c,launchTarget:c}:{},...s.appName?{appName:s.appName}:{}}}finally{await s.cleanup()}}async function O(t,n,i,a,o){a?.throwIfAborted();let s=await r(o,t.client.listApps(),a).catch(e=>{if(a?.aborted)throw e}),c=f((await r(o,t.client.installApp(n,{md5:i?.md5,launchMode:i?.relaunch?`RelaunchIfRunning`:`ForegroundIfRunning`}),a)).bundleId),l=f(i?.appIdentifierHint),u=[];for(let e of N){e>0&&await d(e,void 0,{signal:a}),u=await r(o,t.client.listApps(),a);let n=P({resultBundleId:c,requestedBundleId:l,beforeInstallApps:s,afterInstallApps:u});if(n)return{appId:n}}throw new e(`COMMAND_FAILED`,`Limrun iOS app installation could not be verified.`,{resultBundleId:c,requestedBundleId:l,installedUserApps:u.filter(I).map(e=>e.bundleId).sort()})}function k(e){return new A(e)}var A=class{session;constructor(e){this.session=e}async open(e,n){if(n?.url){await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e)),await this.session.client.openUrl(n.url);return}if(t(e)){await this.session.client.openUrl(e);return}await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e))}async openDevice(){}async close(e){e&&await this.session.client.terminateApp(await this.session.dependencies.ios.resolveAppAlias(e)).catch(()=>{})}async tap(e,t){await this.session.client.tap(e,t)}async tapElementSelector(e){await this.session.client.tapElement(o(e))}async doubleTap(e,t){await this.tap(e,t),await this.tap(e,t)}async longPress(){throw R(`longpress`,`Limrun iOS direct sessions do not expose long press yet.`)}async focus(e,t){await this.tap(e,t)}async type(e,t){if(t&&t>0){for(let n of Array.from(e))await this.session.client.typeText(n),await d(t);return}await this.session.client.typeText(e)}async fill(e,t,n){await this.tap(e,t),await this.session.client.typeText(n)}async scroll(e,t){await this.session.client.scroll(e,t?.pixels??300)}async screenshot(e){let t=await this.session.client.screenshot();await s(e,t.base64)}async snapshot(){let{captureLimrunIosSnapshot:e}=await import(`./ios-snapshot-adapter.js`);return await e(this.session)}async back(){await this.session.client.pressKey(`escape`)}async home(){throw R(`home`,`Limrun iOS direct sessions do not expose home yet.`)}async setOrientation(e){if(e===`portrait-upside-down`)throw R(`orientation`,`Limrun iOS direct sessions support portrait and landscape orientation, not portrait upside-down.`);await this.session.client.setOrientation(e===`portrait`?`Portrait`:`Landscape`)}async performGesture(){throw R(`gesture`,`Limrun iOS direct sessions do not expose portable gesture execution yet.`)}async appSwitcher(){throw R(`app-switcher`,`Limrun iOS direct sessions do not expose app switcher yet.`)}async tvRemote(){throw R(`tv-remote`,`Limrun iOS direct sessions do not expose tv remote control.`)}async readAlert(){throw R(`alert`,L)}async awaitAlert(){throw R(`alert`,L)}async acceptAlert(){throw R(`alert`,L)}async dismissAlert(){throw R(`alert`,L)}async readClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard read yet.`)}async writeClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard write yet.`)}async setSetting(){throw R(`settings`,`Limrun iOS direct sessions do not expose settings changes yet.`)}};async function j(e,t){if(!(await l.promises.stat(e)).isDirectory())return{uploadPath:e,assetName:c.basename(e),appName:M(e),cleanup:async()=>{}};let n=await l.promises.mkdtemp(c.join(u.tmpdir(),`agent-device-limrun-ios-app-`)),r=c.join(n,`${c.basename(e)}.zip`);try{await t.host.archiveDirectory({sourceDirectory:c.dirname(e),entryName:c.basename(e),archivePath:r})}catch(e){throw await l.promises.rm(n,{recursive:!0,force:!0}),e}return{uploadPath:r,assetName:c.basename(r),appName:await t.ios.readBundleAppName(e)??M(e),cleanup:async()=>{await l.promises.rm(n,{recursive:!0,force:!0})}}}function M(e){return c.basename(e).replace(/\.(?:app|ipa|apk|aab|zip)$/i,``)||void 0}const N=[0,250];function P(e){let t=new Set(e.afterInstallApps.map(e=>e.bundleId));return(e.resultBundleId&&t.has(e.resultBundleId)?e.resultBundleId:void 0)??(e.requestedBundleId&&t.has(e.requestedBundleId)?e.requestedBundleId:void 0)??F(e.beforeInstallApps,e.afterInstallApps)}function F(e,t){if(!e)return;let n=new Set(e.map(e=>e.bundleId)),r=t.filter(e=>I(e)&&!n.has(e.bundleId));return r.length===1?r[0]?.bundleId:void 0}function I(e){return!e.bundleId.startsWith(`com.apple.`)&&!e.installType.toLowerCase().includes(`system`)}const L=`Limrun iOS direct sessions do not expose alert inspection yet.`;function R(t,n){throw new e(`UNSUPPORTED_OPERATION`,n,{command:t})}function z(e){return e.platform===`android`?B(e):V(e)}function B(e){let t=e.adbProvider.exec;return{platform:`android`,device:e.device,interactor:m(e),adb:e.adbProvider,listApps:async r=>await e.dependencies.android.listApps(t,n(r)),getForegroundApp:async n=>await e.dependencies.android.getForegroundApp(e.device,t,n),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},getKeyboardState:async()=>await e.dependencies.android.getKeyboardState(t),dismissKeyboard:async()=>await e.dependencies.android.dismissKeyboard(t),readLogs:async n=>await e.dependencies.android.readLogs(t,n),...H(e.client),installRemoteApp:async t=>{await e.client.sendAsset(t)}}}function V(e){return{platform:`ios`,device:e.device,interactor:k(e),viewport:{width:e.client.deviceInfo.screenWidth,height:e.client.deviceInfo.screenHeight},listApps:async t=>(await e.client.listApps()).filter(e=>n(t)===`all`||I(e)).map(e=>({id:e.bundleId,name:e.name,installType:e.installType})).sort((e,t)=>e.id.localeCompare(t.id)),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},readLogs:async(t,n)=>await e.client.appLogTail(t,n),...H(e.client),installRemoteApp:async(t,n)=>await O(e,t,n),runSimctl:t=>e.client.simctl(t)}}function H(e){return{startRecording:async t=>{await e.startRecording(t)},stopRecording:async({outPath:t})=>await e.stopRecording({localPath:t})}}export{_ as a,p as c,D as i,h as l,k as n,g as o,E as r,m as s,z as t};
|
package/dist/src/device2.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{v as t}from"./sdk-device.js";import{r as n}from"./command.js";import{i as r,n as i,t as a}from"./device-claim-inspection.js";import{t as o}from"./shared.js";const s=async({positionals:t,flags:n})=>{if(t.length!==1||t[0]!==`status`&&t[0]!==`release`)throw new e(`INVALID_ARGS`,`device accepts only: status, release`);if(t[0]===`release`)return await c(n);let s=r({platform:n.platform,device:n.device,udid:n.udid,serial:n.serial}),l=s.filter(e=>i(e.classification)),u=(n.stale?l:s.filter(e=>!i(e.classification))).map(m),d={claims:u,...n.stale?{}:{hiddenStaleClaims:l.length}};return await o(n,d,()=>g(u,{staleOnly:n.stale===!0,hiddenStaleClaims:l.length,staleCommand:x(n,`status`),releasableClaims:l.filter(e=>a(e.classification)).length,releaseCommand:x(n,`release`)})),!0};async function c(t){if(t.stale!==!0)throw new e(`INVALID_ARGS`,`device release only releases provably stale claims; pass --stale to confirm.`,{hint:`A live owner is released by closing its session from its own workspace, or by stopping its daemon: agent-device daemon stop --state-dir <owner state dir>.`});let{runStaleDeviceClaimRelease:n}=await import(`./device-release.js`),r=await n({platform:t.platform,device:t.device,udid:t.udid,serial:t.serial}),i={released:r.filter(e=>e.status===`released`).map(l),retained:r.filter(e=>e.status===`retained`).map(l),refused:r.filter(e=>e.status===`refused`).map(l),changed:r.filter(e=>e.status===`changed`).map(l)};return await o(t,i,()=>u(r)),!0}function l(e){let{device:t,...n}=e;return{...n,...t?{device:h(t)}:{}}}function u(e){return e.length===0?`No local device claims matched.`:e.map(d).join(`
|
|
2
2
|
`)}function d(e){let n=e.device?`${t({platform:e.device.family,appleOs:e.device.appleOs})} ${e.device.name}`:e.deviceKey??e.fileName,r=f(e);switch(e.status){case`released`:return`released ${n}${r}`;case`retained`:return`retained ${n}${r} — resources not settled (${e.reason}); the claim stays until they are.`;case`refused`:return`refused ${n}${r} — ${e.reason} (${e.classification}); ${p(e)}`;case`changed`:return`changed ${n} — the claim changed while releasing; re-run device status.`}}function f(e){return e.allocator?` allocator=${e.allocator.instanceId} incarnation=${e.allocator.identityIncarnationId}`:e.session?` session=${e.session} workspace=${e.workspace}`:``}function p(e){return e.classification===`allocator-held`?`held by its managed-device allocator; it is cleared only after the allocator proves the identity removed.`:e.classification===`live`||e.classification===`owner-state-dir-gone`?e.stateDir?`close the owning session from its workspace, or stop its daemon: agent-device daemon stop --state-dir ${n(e.stateDir)}`:`close the owning session from its workspace first.`:`only provably dead owners are released; nothing was changed.`}function m(e){let t=e.claim??e.allocatorClaim;return{...e.deviceKey?{deviceKey:e.deviceKey}:{},...t?{}:{fileName:e.fileName},classification:e.classification,...t?{device:h(t.device)}:{},...e.claim?{owner:{session:e.claim.session,workspace:e.claim.workspace,stateDir:e.claim.stateDir,pid:e.claim.ownerPid,startTime:e.claim.ownerStartTime}}:{},...e.allocatorClaim?{owner:{kind:`allocator`,stateDir:e.allocatorClaim.stateDir,allocator:e.allocatorClaim.allocator}}:{},...e.error?{error:e.error}:{}}}function h(e){let{family:n,...r}=e;return{...r,platform:t({platform:n,appleOs:e.appleOs})}}function g(e,t){let n=e.map(v);if(n.length===0){if(t.staleOnly)return`No stale local device claims found.`;if(t.hiddenStaleClaims===0)return`No local device claims found.`}return[...n.length===0?[`No live local device claims found.`]:n,..._(t)].join(`
|
|
3
3
|
`)}function _(e){if(e.staleOnly)return e.releasableClaims>0?[`Release provably dead owners with: ${e.releaseCommand}`]:[];if(e.hiddenStaleClaims===0)return[];let t=e.hiddenStaleClaims===1?`claim`:`claims`;return[`${e.hiddenStaleClaims} stale ${t} hidden; inspect with: ${e.staleCommand}`]}function v(e){return`${y(e)}: ${e.classification}${b(e.owner)}`}function y(e){let t=e.device;return t?`${t.platform??`unknown`} ${t.name??t.id??`claim`}`:String(e.deviceKey??e.fileName??`claim`)}function b(e){if(!e||typeof e!=`object`)return``;let t=e;return t.allocator?` allocator=${t.allocator.instanceId} incarnation=${t.allocator.identityIncarnationId} installation=${t.stateDir}`:` session=${t.session} workspace=${t.workspace}`}function x(e,t){let r=[e.platform?`--platform ${n(e.platform)}`:null,e.device?`--device ${n(e.device)}`:null,e.udid?`--udid ${n(e.udid)}`:null,e.serial?`--serial ${n(e.serial)}`:null].filter(e=>!!e);return[`agent-device device ${t}`,...r,`--stale`].join(` `)}export{s as deviceCommand};
|
package/dist/src/diagnostics.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{z as e}from"./sdk-contracts.js";import t from"node:path";import n from"node:fs";import r from"node:crypto";import{AsyncLocalStorage as i}from"node:async_hooks";import a from"node:os";const o=new i;function s(){return r.randomBytes(8).toString(`hex`)}function c(){return`${Date.now().toString(36)}-${r.randomBytes(4).toString(`hex`)}`}async function l(e,t){let n={...e,diagnosticId:c(),events:[],liveWrittenEventCount:0,phaseCounts:new Map,sensitiveValues:new Set,ensuredDirectories:new Set};return await o.run(n,t)}function u(e){let t=o.getStore();t&&Object.assign(t,e)}function d(){let e=o.getStore();if(!e)return{};let{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}=e;return{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}}function f(e){if(!e)return;let t=o.getStore();t&&(t.sensitiveValues.add(e),t.sortedSensitiveValues=void 0)}function p(e){let t=o.getStore();if(!t)return 0;let n=0;for(let r of e)n+=t.phaseCounts.get(r)??0;return n}function m(e){let t=o.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??`info`,phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?v(t,e.data):void 0};if(t.events.push(n),t.phaseCounts.set(e.phase,(t.phaseCounts.get(e.phase)??0)+1),!t.debug&&!t.traceLogPath)return;let r=`${JSON.stringify(n)}\n`;try{t.debug&&t.logPath&&(x(t,t.logPath,r),t.liveWrittenEventCount=t.events.length),t.traceLogPath&&x(t,t.traceLogPath,r),t.debug&&!t.logPath&&!t.traceLogPath&&process.stderr.write(`[agent-device][diag] ${r}`)}catch{}}async function h(e,t,n){let r=Date.now();try{let i=await t();return m({level:`info`,phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw m({level:`error`,phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function g(e={}){let r=o.getStore();if(!r||!e.force&&!r.debug&&!r.flushOnSuccess||r.events.length===0)return null;let i=_(r);try{if(r.logPath){let e=r.events.slice(r.liveWrittenEventCount);if(e.length>0){let t=e.map(e=>JSON.stringify(y(e,i)));x(r,r.logPath,`${t.join(`
|
|
2
2
|
`)}\n`)}let t=r.logRecord;return r.events=[],r.liveWrittenEventCount=0,{path:r.logPath,...t?{ref:t}:{}}}let e=b(r.session??`default`),o=new Date().toISOString().slice(0,10),s=t.join(a.homedir(),`.agent-device`,`logs`,e,o);n.mkdirSync(s,{recursive:!0});let c=new Date().toISOString().replaceAll(/[:.]/g,`-`),l=t.join(s,`${c}-${r.diagnosticId}.ndjson`),u=r.events.map(e=>JSON.stringify(y(e,i)));return n.writeFileSync(l,`${u.join(`
|
|
3
3
|
`)}\n`),r.events=[],{path:l}}catch{return null}}function _(e){return e.sortedSensitiveValues??=[...e.sensitiveValues].sort((e,t)=>t.length-e.length),e.sortedSensitiveValues}function v(t,n){return y(e(n),_(t))}function y(e,t){return typeof e==`string`?t.reduce((e,t)=>e.replaceAll(t,`[REDACTED]`),e):Array.isArray(e)?e.map(e=>y(e,t)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,y(n,t)]))}function b(e){return e.replaceAll(/[^a-zA-Z0-9._-]/g,`_`)}function x(e,r,i){let a=t.dirname(r);e.ensuredDirectories.has(a)||(n.mkdirSync(a,{recursive:!0}),e.ensuredDirectories.add(a)),n.appendFileSync(r,i,`utf8`)}export{d as a,h as c,g as i,l,s as n,f as o,m as r,u as s,p as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{b as t,c as n,o as r}from"./sdk-device.js";import{c as i}from"./diagnostics.js";import"./diagnostics2.js";import{n as a,r as o}from"./device-isolation.js";import{a as s,i as c,r as l}from"./device-inventory-context.js";import{AsyncLocalStorage as u}from"node:async_hooks";async function d(e){let{resolveInventoryDeviceSelection:t}=await import(`./device-selection-resolver.js`).then(e=>e.t);return await t(e)}const f=new u;function p(t,n){return!r(n)&&t instanceof e&&t.code===`DEVICE_NOT_FOUND`}function m(e,t){return!r(e)&&(!e.platform||e.platform===`apple`||e.platform===`ios`)&&e.target!==`desktop`&&(!t||t.kind===`device`)}async function h(e,t={}){return(await g(e,t)).device}async function g(e,t={}){let r={...y(e),androidAvdSelection:t.androidAvdSelection??`running-only`},{iosSimulatorSetPath:a,...o}=r,s=C(r,t),l={platform:r.platform,target:e.target,cacheHit:!1};return await i(`resolve_target_device`,async()=>{let e=x(s);if(e)return l.cacheHit=!0,e;let i=await c(r),u=[...i.devices];if(n(o.platform)&&i.source===`local`){let e=await _(u,o,{simulatorSetPath:a,appleSimulatorAppTarget:t.appleSimulatorAppTarget});return S(s,e)}return S(s,await d({devices:u,selector:o,source:i.source}))},l)}async function _(t,n,r){let i;try{i=await d({devices:t,selector:n,source:`local`,appleSimulatorAppTarget:r.appleSimulatorAppTarget})}catch(e){if(!p(e,n))throw e}let a=await v(n,r,i?.device);if(a)return a;if(i)return i;throw new e(`DEVICE_NOT_FOUND`,`No devices found`,{selector:n})}async function v(e,t,n){if(m(e,n))try{return await d({devices:await l({platform:e.platform??`ios`,target:e.target,iosSimulatorSetPath:t.simulatorSetPath,kind:`simulator`}),selector:e,source:`local`})}catch(e){if(s(e))throw e;return}}function y(n){let r=n.platform;if(n.target&&!r)throw new e(`INVALID_ARGS`,`Device target selector requires --platform. Use --platform ios|macos|android|vega|linux|apple with --target mobile|tv|desktop.`);let i=t({simulatorSetPath:o(n.iosSimulatorDeviceSet),platform:r,target:n.target}),s=a(n.androidDeviceAllowlist);return{platform:r,target:n.target,deviceName:n.device,udid:n.udid,serial:n.serial,leaseId:n.leaseId,leaseProvider:n.leaseProvider,deviceKey:n.deviceKey,clientId:n.clientId,iosSimulatorSetPath:i,androidSerialAllowlist:s?Array.from(s).sort():void 0}}async function b(e){return f.getStore()?await e():await f.run(new Map,e)}function x(e){let t=f.getStore()?.get(e);if(t)return{...t,device:{...t.device}}}function S(e,t){return f.getStore()?.set(e,{...t,device:{...t.device}}),t}function C(e,t){let{appleSimulatorAppTarget:n,...r}=t;return JSON.stringify({request:e,options:r})}export{b as i,h as n,g as r,y as t};
|
package/dist/src/doctor2.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{r as t,t as n}from"./toolchain-probe.js";import{t as r}from"./tool-provider3.js";async function i(e){let i=r();if(!await i.isAvailable())return{id:`toolchain`,status:`info`,summary:`Vega toolchain: Vega CLI not found.`,hint:`Install Vega Developer Tools or ensure ~/vega/bin/vega is executable.`,command:`vega --version`};let o=await i.version({allowFailure:!0,timeoutMs:n}),s=await a(e),l=t(o.stdout),u=s.devices.some(e=>e.platform===`vega`&&e.kind===`emulator`&&e.target===`tv`&&e.booted===!0);return{id:`toolchain`,status:o.exitCode===0?`pass`:`info`,summary:l?`Vega toolchain: ${l}; ${u?`VVD running`:`no running VVD`}.`:`Vega toolchain: CLI found but version check failed.`,hint:u?void 0:`Start the Vega Virtual Device and retry doctor.`,evidence:{vegaVersion:l??null,deviceList:c(s)}}}async function a(e){try{return{devices:await e.listLocalDeviceInventory({platform:`vega`,target:`tv`}),listedSerials:[]}}catch(t){if(e.shouldPropagateInventoryProbeError(t))throw t;return{devices:[],listedSerials:o(t)}}}function o(t){if(!(t instanceof e)||t.code!==`DEVICE_NOT_FOUND`)return[];let n=t.details?.listedSerials;return s(n)?n:[]}function s(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function c(e){return(e.devices.length>0?e.devices.map(e=>e.id):e.listedSerials).join(`, `)||null}export{i as vegaToolchainCheck};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as e,s as t}from"./sdk-device.js";import{Gt as n,
|
|
1
|
+
import{f as e,s as t}from"./sdk-device.js";import{Gt as n,Jt as r,Kt as i}from"./sdk-batch.js";const a=4096;function o(e){return c(e,{seen:new WeakSet,nodes:0},0)}function s(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,p(t)])))}function c(e,t,n){if(!d(e)||n>32||t.seen.has(e))return!1;t.seen.add(e),t.nodes+=1;let r=t.nodes<=a&&Object.values(e).every(e=>l(e,t,n+1));return t.seen.delete(e),r}function l(e,t,n){return f(e)?!0:n>32?!1:Array.isArray(e)?u(e,t,n):c(e,t,n)}function u(e,t,n){if(t.seen.has(e))return!1;t.seen.add(e),t.nodes+=1;let r=t.nodes<=a&&e.every(e=>l(e,t,n+1));return t.seen.delete(e),r}function d(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function f(e){return e===null?!0:typeof e==`number`?Number.isFinite(e):typeof e==`string`||typeof e==`boolean`}function p(e){return Array.isArray(e)?Object.freeze(e.map(p)):typeof e==`object`&&e?s(e):e}function m(e){if(!P(e))return _(`Durable resource envelope must be an object`);let t=e.envelopeVersion;if(!N(t))return _(`Durable resource envelopeVersion must be a non-negative integer`);if(t!==1)return{status:`unreattachable`,reason:`descriptor-version-unsupported`,message:`Unsupported durable resource envelope version: ${t}`,version:t};if(!M(e.resourceKind))return _(`Durable resource resourceKind must be a non-empty string`);if(!M(e.sessionId))return _(`Durable resource sessionId must be a non-empty string`);let n=y(e.device);if(!n)return _(`Durable resource device identity is invalid`);let r=v(e.owner);if(!r)return _(`Durable resource owner reference is invalid`);if(r.kind===`local-family`&&r.family!==n.family)return _(`Durable resource local owner does not match the device family`);let i=D(e.fence);if(!i)return _(`Durable resource ownership fence is invalid`);if(!k(e.lifecycle))return _(`Durable resource lifecycle state is invalid`);let a=O(e.descriptor);return a?e.metadata!==void 0&&!o(e.metadata)?_(`Durable resource metadata must be a JSON object`):{status:`decoded`,envelope:Object.freeze({envelopeVersion:1,resourceKind:e.resourceKind,sessionId:e.sessionId,device:n,owner:r,fence:i,lifecycle:e.lifecycle,descriptor:a,...e.metadata===void 0?{}:{metadata:s(e.metadata)}})}:_(`Durable resource descriptor is invalid`)}function h(e,t){return Object.freeze({version:e.version,body:s(e.encode(t))})}function g(e){let t=m({envelopeVersion:1,...e});if(t.status!==`decoded`)throw TypeError(t.message);return t.envelope}function _(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function v(t){return P(t)?t.kind===`local-family`&&e(t.family)?n(t.family):t.kind===`managed-local`&&M(t.instance)?i(t.instance):t.kind===`provider-runtime`&&M(t.provider)&&M(t.instance)?r(t.provider,t.instance):null:null}function y(e){if(!P(e))return null;let t=x(e.id),n=S(e.family),r=C(e.kind),i=w(e.target);return!t||!n||!r||i===null||!T(e,n,r)?null:b(e,t,n,r,i)}function b(e,t,n,r,i){return Object.freeze({id:t,family:n,...e.appleOs===void 0?{}:{appleOs:e.appleOs},kind:r,...i===void 0?{}:{target:i},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend}})}function x(e){return M(e)?e:null}function S(t){return e(t)?t:null}function C(e){return A(e)?e:null}function w(e){if(e!==void 0)return j(e)?e:null}function T(e,n,r){if(n===`apple`){if(!t(e.appleOs))return!1}else if(e.appleOs!==void 0||e.iosPhysicalDeviceBackend!==void 0)return!1;return E(e.iosPhysicalDeviceBackend,r)}function E(e,t){return e===void 0?!0:t===`device`?e===`coredevice`||e===`xctest`:!1}function D(e){return!P(e)||!M(e.token)||!N(e.generation)?null:Object.freeze({token:e.token,generation:e.generation})}function O(e){return!P(e)||!N(e.version)||!o(e.body)?null:Object.freeze({version:e.version,body:s(e.body)})}function k(e){return e===`open`||e===`completed`}function A(e){return e===`simulator`||e===`emulator`||e===`device`}function j(e){return e===`mobile`||e===`tv`||e===`desktop`}function M(e){return typeof e==`string`&&e.trim().length>0}function N(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F(e){return e.status===`cleaned`||e.status===`already-missing`}export{h as a,m as i,g as n,y as r,F as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{C as e,D as t}from"./sdk-contracts.js";const n=new Set([`__proto__`,`constructor`,`prototype`]);async function r(n,r){let o=a(r),c=i(n),{default:l}=await import(`node:vm`),u={...r,output:o};try{l.runInNewContext(c,u,{filename:`evalScript`,timeout:1e4})}catch(n){throw new e(`COMMAND_FAILED`,`Maestro evalScript failed: ${t(n)}`,void 0,n instanceof Error?n:void 0)}return s(u.output)}function i(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1):t}function a(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))!n.startsWith(`output.`)||n===`output`||o(t,n.slice(7),r);return t}function o(e,t,n){let r=t.split(`.`).filter(l);if(r.length===0)return;let i=e;for(let e of r.slice(0,-1)){let t=i[e];(typeof t!=`object`||!t)&&(i[e]=Object.create(null)),i=i[e]}i[r.at(-1)]=n}function s(e){let t={};return c(e,[],t,new Set),t}function c(e,t,n,r){if(e!==void 0){if(typeof e!=`object`||!e){n[`output${t.map(e=>`.${e}`).join(``)}`]=u(e);return}if(!r.has(e)){r.add(e);try{let i=Array.isArray(e)?[...e.keys(),`length`]:Object.keys(e).filter(l);for(let a of i){let i=String(a);c(Array.isArray(e)&&i===`length`?e.length:e[i],[...t,i],n,r)}}finally{r.delete(e)}}}}function l(e){return!n.has(e)}function u(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}export{r as evaluateMaestroEvalScript};
|
package/dist/src/error.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as e,F as t,M as n}from"./sdk-contracts.js";import{r}from"./replay-divergence.js";function i(i,o={}){let s=i instanceof e?n(i):i;if(process.stderr.write(`Error (${s.code}): ${s.message}\n`),s.cause){let e=s.cause.code?`${s.cause.code} `:``;process.stderr.write(`Cause: ${e}${s.cause.message}\n`)}s.hint&&process.stderr.write(`Hint: ${s.hint}\n`);let c=a(t(s.details));c.length>0&&process.stderr.write(`${c.join(`
|
|
2
2
|
`)}\n`),s.diagnosticId&&process.stderr.write(`Diagnostic ID: ${s.diagnosticId}\n`),s.logPath&&process.stderr.write(`Diagnostics Log: ${s.logPath}\n`),s.logPathUnavailable&&process.stderr.write(`Remote Diagnostics: unavailable (${s.logPathUnavailable})\n`);let l=r(s.details);l&&process.stderr.write(`${l}\n`),o.showDetails&&s.details&&process.stderr.write(`${JSON.stringify(s.details,null,2)}\n`)}function a(e){return e.flatMap(e=>{if(e.kind===`element-match`){let t=e.matches-e.candidates.length;return[`Candidates:`,...e.candidates.map(t=>` ${o(t,e.refsGeneration)}`),...t>0?[` +${t} more`]:[]]}return[`Devices:`,...e.devices.map(e=>` ${e.id} ${e.name}`)]})}function o(e,t){return t===void 0?e:e.replace(/^@(e\d+)(?=\s|$)/,`@$1~s${t}`)}export{i as printHumanError};
|
package/dist/src/exec.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as e,T as t}from"./sdk-contracts.js";import{o as n}from"./sdk-remote-config.js";import{a as r,r as i,s as a}from"./diagnostics.js";import o from"node:path";import{constants as s}from"node:fs";import{AsyncLocalStorage as c}from"node:async_hooks";import{access as l,stat as u}from"node:fs/promises";import{spawn as d,spawnSync as f}from"node:child_process";import{Readable as p}from"node:stream";import{pipeline as m}from"node:stream/promises";const h=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,g=[`.com`,`.exe`,`.bat`,`.cmd`],_=new c;async function v(e,t){return e?await _.run(e,t):await t()}async function y(e){return await _.run(void 0,e)}async function b(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}async function x(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}function S(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function C(e,t,n={}){let r=N(e),i=A();return new Promise((a,o)=>{let s=d(r,t,{cwd:n.cwd,env:n.env,stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});n.onSpawn?.(s);let c=``,l=n.binaryStdout?[]:void 0,u=``,f=!1,p=Z(n.timeoutMs),m=p?setTimeout(()=>{f=!0,$(s,n.detached)},p):null,h=Q(s,n);n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),ne(s,n.stdin).catch(i=>{h.didAbort||f||re(i)||(o(te(r,e,t,i)),$(s,n.detached))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);c+=t,n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);u+=t,n.onStderrChunk?.(t)}),s.on(`error`,n=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t),o(U(h,r,e,t,n))}),s.on(`close`,s=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t);let d=s??1;if(!h.didAbort&&f&&p){o(R(r,e,t,p,d,c,u));return}let g=W(h,r,e,t,d,n.allowFailure,c,u);if(g){o(g);return}a({stdout:c,stderr:u,exitCode:d,stdoutBuffer:l?Buffer.concat(l):void 0})})})}async function w(e){let t=K(e);if(!t)return!1;if(o.isAbsolute(t))return Y(t);let n=process.env.PATH;if(!n)return!1;let r=q();for(let e of n.split(o.delimiter)){let n=e.trim();if(n){for(let e of J(t,r))if(await Y(o.join(n,e)))return!0}}return!1}async function ee(t,n){let r=G(t,n,`executable`);if(r){if(!await Y(r))throw new e(`TOOL_MISSING`,`${n} points to a missing or non-executable file: ${r}`,{envName:n,path:r});return r}}async function T(t,n){let r=G(t,n,`file`);if(r){if(!await X(r))throw new e(`TOOL_MISSING`,`${n} points to a missing or non-file path: ${r}`,{envName:n,path:r});return r}}function E(t,n,r={}){let i=N(t),a=f(i,n,{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`],encoding:r.binaryStdout?void 0:`utf8`,input:r.stdin,timeout:Z(r.timeoutMs),windowsHide:!0,shell:!1,...r.maxBuffer===void 0?{}:{maxBuffer:r.maxBuffer}});if(a.error){let o=a.error.code;throw o===`ETIMEDOUT`?new e(`COMMAND_FAILED`,`${i} timed out after ${Z(r.timeoutMs)}ms`,{cmd:t,args:n,timeoutMs:Z(r.timeoutMs)},a.error):o===`ENOENT`?F(i,t,a.error):I(i,t,n,a.error)}let o=r.binaryStdout?Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(a.stdout??``):void 0,s=r.binaryStdout?``:typeof a.stdout==`string`?a.stdout:(a.stdout??``).toString(),c=typeof a.stderr==`string`?a.stderr:(a.stderr??``).toString(),l=a.status??1;if(l!==0&&!r.allowFailure)throw B(i,t,n,l,s,c);return{stdout:s,stderr:c,exitCode:l,stdoutBuffer:o}}function D(e,t,n={}){return O(e,t,n).pid}function O(e,t,n={}){let r=N(e),i=d(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??`ignore`,detached:!0,windowsHide:!0,shell:!1}),a=i.pid??0,o=new Promise(e=>{i.once(`error`,t=>{e({pid:a,error:t.message})}),i.once(`exit`,(t,n)=>{e({pid:a,...typeof t==`number`?{exitCode:t}:{},...n?{signal:n}:{}})})});return i.unref(),{pid:a,exited:o}}function k(e,t,n={}){let r=N(e),i=A(),a=d(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??[`ignore`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});i.emitBackgroundSpawn(e,t);let o=``,s=``,c=n.captureOutput??!0,l=Q(a,n);return c&&(a.stdout?.setEncoding(`utf8`),a.stderr?.setEncoding(`utf8`),a.stdout?.on(`data`,e=>{o+=e}),a.stderr?.on(`data`,e=>{s+=e})),{child:a,wait:new Promise((c,u)=>{a.on(`error`,n=>{l.dispose(),i.emitBackgroundCompletion(e,t,`error`),u(U(l,r,e,t,n))}),a.on(`close`,a=>{l.dispose(),i.emitBackgroundCompletion(e,t,`exit`);let d=a??1,f=W(l,r,e,t,d,n.allowFailure,o,s);if(f){u(f);return}c({stdout:o,stderr:s,exitCode:d})})})}}function A(){let e=r(),t=e.debug===!0,i=n(process.env.AGENT_DEVICE_EXEC_TRACE??``)===!0;if(!t&&!i)return j();i&&e.flushOnSuccess!==!0&&a({flushOnSuccess:!0});let o=Date.now(),s=!1;return{emitForegroundCompletion:(e,t)=>{s||(s=!0,M({cmd:e,args:t,startedAtMs:o}))},emitBackgroundSpawn:(e,t)=>{M({cmd:e,args:t,data:{event:`spawn`}})},emitBackgroundCompletion:(e,t,n)=>{s||(s=!0,M({cmd:e,args:t,startedAtMs:o,data:{event:n}}))}}}function j(){return{emitForegroundCompletion:()=>{},emitBackgroundSpawn:()=>{},emitBackgroundCompletion:()=>{}}}function M(e){let t=e.args.slice(0,6);i({level:`debug`,phase:`exec_command`,durationMs:e.startedAtMs===void 0?void 0:Math.max(0,Date.now()-e.startedAtMs),data:{command:e.cmd,argsPrefix:t,...e.args.length>t.length?{omittedArgCount:e.args.length-t.length}:{},...e.data??{}}})}function N(t){let n=K(t);if(!n)throw new e(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(t)}`,{cmd:t,hint:`Use a bare command name from PATH or an absolute executable path.`});return n}function P(e,t,n,r){return r.code===`ENOENT`?F(e,t,r):I(e,t,n,r)}function F(t,n,r){return new e(`TOOL_MISSING`,`${t} not found in PATH`,{cmd:n},r)}function I(t,n,r,i){return new e(`COMMAND_FAILED`,`Failed to run ${t}`,{cmd:n,args:r},i)}function te(t,n,r,i){return new e(`COMMAND_FAILED`,`Failed to write stdin for ${t}`,{cmd:n,args:r},i instanceof Error?i:void 0)}function L(e,n,r){return t({cmd:n,args:r,executable:e})}function R(t,n,r,i,a,o,s){return new e(`COMMAND_FAILED`,`${t} timed out after ${i}ms`,{cmd:n,args:r,stdout:o,stderr:s,exitCode:a,timeoutMs:i})}function z(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&typeof t.details?.timeoutMs==`number`}function B(t,n,r,i,a,o){return new e(`COMMAND_FAILED`,`${t} exited with code ${i}`,H({stdout:a,stderr:o,exitCode:i},{cmd:n,args:r}))}function V(t,n,r){if(t.exitCode===0)return t;throw new e(`COMMAND_FAILED`,n,H(t,typeof r==`function`?r(t):r))}function H(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t}}function U(e,t,n,r,i){return e.didAbort?L(t,n,r):P(t,n,r,i)}function W(e,t,n,r,i,a,o,s){return e.didAbort?L(t,n,r):i!==0&&!a?B(t,n,r,i,o,s):null}function G(t,n,r){let i=t?.trim();if(i){if(!o.isAbsolute(i)||i.includes(`\0`))throw new e(`INVALID_ARGS`,`${n} must be an absolute ${r} path, not ${JSON.stringify(t)}`,{envName:n,path:t});return i}}function K(e){let t=e.trim();return!t||t.includes(`\0`)?null:o.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:h.test(t)?t:null}function q(){if(process.platform!==`win32`)return[``];let e=process.env.PATHEXT;if(!e)return g;let t=e.split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:g}function J(e,t){if(process.platform!==`win32`)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}async function Y(e){try{return await X(e)?(await l(e,process.platform===`win32`?s.F_OK:s.X_OK),!0):!1}catch{return!1}}async function X(e){try{return(await u(e)).isFile()}catch{return!1}}function Z(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function Q(e,t){let n=!1,r=()=>{n=!0,$(e,t.detached)};return t.signal?.aborted?r():t.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{t.signal?.removeEventListener(`abort`,r)}}}function $(e,t){if(t&&e.pid&&process.platform!==`win32`)try{process.kill(-e.pid,`SIGKILL`);return}catch{}e.kill(`SIGKILL`)}async function ne(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await m(p.from([t]),e.stdin)}}function re(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}export{V as a,b as c,O as d,x as f,y as g,v as h,Y as i,k as l,w as m,H as n,ee as o,E as p,z as r,T as s,S as t,D as u};
|
package/dist/src/file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{O as t,t as n}from"./owner-identity.js";import{t as r}from"./timeouts.js";import i from"node:path";import a from"node:fs";async function o(t){let{lockDirPath:n,owner:o}=t,l=i.join(n,`owner.json`),d=Date.now()+(t.timeoutMs??3e4),f=t.pollMs??100,p=t.ownerGraceMs??5e3,m=t.description??`process lock`;for(a.mkdirSync(i.dirname(n),{recursive:!0});Date.now()<d;)try{a.mkdirSync(n),s(l,o);let e=!1;return async()=>{e||(e=!0,a.rmSync(n,{recursive:!0,force:!0}))}}catch(e){let t=e;if(t.code!==`EEXIST`)throw t;if(c(n,l,p))continue;await r(f)}throw new e(`COMMAND_FAILED`,`Timed out waiting for ${m}`,{lockDirPath:n,...u(n,l)})}function s(e,n){t({destination:e,contents:JSON.stringify(n)})}function c(e,t,n){let r=null;try{r=a.statSync(e)}catch{return!0}let i=l(t);return i?!d(i)&&(a.rmSync(e,{recursive:!0,force:!0}),!0):Date.now()-r.mtimeMs<n?!1:(a.rmSync(e,{recursive:!0,force:!0}),!0)}function l(e){try{return JSON.parse(a.readFileSync(e,`utf8`))}catch{return null}}function u(e,t){let r=Date.now(),i=l(t),o;try{o=Math.max(0,Math.round(r-a.statSync(e).mtimeMs))}catch{}return{...o===void 0?{}:{lockAgeMs:o},...i?{ownerPid:i.pid,ownerStartTime:i.startTime,ownerAgeMs:Math.max(0,Math.round(r-i.acquiredAtMs)),ownerLiveness:n({owner:i})}:{}}}function d(e){let t=n({owner:e});return t!==`owner-process-dead`&&t!==`owner-process-reused`}export{o as t};
|
package/dist/src/find.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{p as e}from"./sdk-contracts.js";import{An as t,Ft as n,Nn as r,On as i,ht as a,kn as o}from"./sdk-batch.js";import{c as s}from"./session-store.js";import{C as c,_ as l,g as u,h as d,p as f}from"./runtime.js";import{n as p,t as m}from"./success-text.js";import{f as h}from"./absence-observation-errors.js";import{a as g,i as _}from"./request-runtime-binding.js";import{C as v,E as y,S as b}from"./session-snapshot.js";import{p as x}from"./quality-warnings.js";import{t as S}from"./internal/daemon.js";import{t as C}from"./snapshot-runtime-binding.js";import{l as w,n as T,u as E}from"./selector-runtime.js";import{t as D}from"./type-text-runtime.js";function O(t,n){let r=n[0]?.rect;if(!r)return t;let i=t.filter(t=>{if(!t.rect)return!1;let n=e(t.rect);return n.x>=r.x&&n.x<=r.x+r.width&&n.y>=r.y&&n.y<=r.y+r.height}),a=i.length>0?i:t;return a.length<2?a:k(a,n,u(n))}function k(e,t,n){return e.map((e,r)=>({node:e,index:r,score:A(e,t,n)})).sort((e,t)=>t.score===e.score?M(e.node)-M(t.node)||e.index-t.index:t.score-e.score).map(e=>e.node)}function A(e,t,n){let r=n(e);if(r.reason===`covered`)return 0;let i=j(r,t[0]);return i>0?i:e.hittable&&e.rect&&!l(e,t[0])?3:+!!e.rect}function j(e,t){return e.node.rect?e.reason===`semantic-target`||e.reason===`same-rect-descendant`?4:e.reason===`hittable-ancestor`&&!l(e.node,t)?2:0:0}function M(e){return e.rect?e.rect.width*e.rect.height:1/0}function N(e,t,n){let r={matches:e.length,candidates:e.slice(0,5).map(e=>h(e,0,!1))};return _(`AMBIGUOUS_MATCH`,`find matched ${e.length} elements for ${t} "${n}". Use a more specific locator or selector.`,{locator:t,query:n,...r})}function P(e){if(e.ambiguity!==`reject-candidates`)throw Error(`find's resolution policy must reject candidates, got "${e.ambiguity}"`)}function F(e){let{nodes:t,locator:n,query:r,selectorExpression:i,flags:a,platform:s}=e,u=c.findAct,d=t.filter(e=>!l(e,t[0])),p=u.resolution,m;if(m=i?f(u,d,i,{platform:s}).list?.matchedNodes??[]:o(d,n,r,{requireRect:p.requireRect}).matches,m=O(m,t),m.length>1){P(p);let e=I(m,a);if(!e)return{ok:!1,response:N(m,n,r)};m=e}let h=m[0]??null;return h?{ok:!0,node:h}:{ok:!1,response:_(`COMMAND_FAILED`,`find did not match any element`)}}function I(e,t){return t?.findFirst?[e[0]]:t?.findLast?[e.at(-1)]:null}function L(e){let{device:t,session:n,req:r,logPath:i,locator:a,query:o,sessionStore:s,sessionName:c}=e,l=w({device:t,session:n,sessionStore:s,sessionName:c,req:r,logPath:i,capture:e.capture});return async()=>{let{snapshot:e}=await l.capture({flags:{...r.flags,snapshotInteractiveOnly:!0},recovery:{legacyIosSparse:{query:o,shouldScope:z(a)},sparseVerdictQueryScope:{query:o,shouldScope:z(a)}}});return{nodes:e.nodes,snapshotQuality:e.snapshotQuality,systemSurfaceOnly:e.systemSurfaceOnly,iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}}}function R(e){return _(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}function z(e){return e!==`role`}async function B(e){let{req:o,sessionName:s,logPath:l,sessionStore:u,invoke:f}=e,p=o.command;if(p!==`find`)return null;let m=o.positionals??[],h=i(m,o.flags);if(!h.ok)return _(h.code,h.message);let{locator:v,query:y,action:b,value:S}=h.parsed;if(o.flags?.record&&!t(b))return _(`INVALID_ARGS`,`find ${b} is a mutating action and is always recorded; --record only applies to a read-only find (exists, wait, list, get text, get attrs).`);let w=await T({req:o,sessionName:s,logPath:l,sessionStore:u,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(w)return w;let D=u.get(s);if(!D)return g();let O=D.device,k=await C({command:`find`,device:O,session:D,plan:n({hasActiveApp:D.appBundleId!==void 0,intent:a(b)}),inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(!k.ok)return k.response;let A=r(v,y),j=L({device:O,session:D,req:o,logPath:l,locator:v,query:y,sessionStore:u,sessionName:s,capture:k.capture}),M={req:o,sessionName:s,logPath:l,sessionStore:u,invoke:f,session:D,device:O,command:p,locator:v,query:y,publicFlags:X(o.flags),boundFocusPoint:k.focusPoint,boundTypeText:k.typeText},N=await j();if(x(N.snapshotQuality))return R(N.snapshotQuality);let{nodes:P}=N,I=F({nodes:P,locator:v,query:y,selectorExpression:A,flags:o.flags,platform:O.platform});if(!I.ok)return E(I.response,N);let z=I.node,B=await d(c.findAct,P,z),H=B.node,U=`@${H.ref}`,W={...o.flags??{},noRecord:!0},G=await V(M,{node:z,resolvedNode:H,ref:U,nodes:P,...N.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:N.iosSystemSurfaceBundleId}:{},actionFlags:W,...B.kind===`occluded`?{occludedNode:B.node}:{}},b,S);return G&&E(G,N)}async function V(e,t,n,r){let i={click:()=>U(e,t),fill:()=>W(e,t,r),focus:()=>G(e,t),type:()=>K(e,t,r)}[n];return i?await i():null}function H(e){return{ref:e.ref,node:e.resolvedNode,nodes:e.nodes,...e.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}:{}}}async function U(t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,locator:u,query:d,publicFlags:f}=t,h=await c({token:r.token,session:i,command:`click`,positionals:[n.ref],flags:n.actionFlags,internal:{findResolvedTarget:H(n)}});if(!h.ok)return h;let g=n.resolvedNode.rect?e(n.resolvedNode.rect):n.node.rect?e(n.node.rect):null,_={ref:n.ref,locator:u,query:d};g&&(_.x=g.x,_.y=g.y);let v=m(h.data)??`Tapped ${n.ref}${g?` (${g.x}, ${g.y})`:``}`;return Object.assign(_,p(v)),s(a,o,r,l,{ref:n.ref,action:`click`,locator:u,query:d},{flags:f}),{ok:!0,data:_}}async function W(e,t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,publicFlags:u}=e;if(n===void 0)return _(`INVALID_ARGS`,`find fill requires text (use "" to clear the field)`);let d=await c({token:r.token,session:i,command:`fill`,positionals:[t.ref,n],flags:t.actionFlags,internal:{findResolvedTarget:H(t)}});return d.ok&&s(a,o,r,l,{ref:t.ref,action:`fill`},{flags:u}),d}async function G(e,t){let n=await q(e,t);return n.ok&&Y(e,t,`focus`),n}async function K(e,t,n){let{req:r,logPath:i,session:a}=e;if(!n)return _(`INVALID_ARGS`,`find type requires text`);let o=await q(e,t);if(!o.ok)return o;y(a);let s=e.boundTypeText;if(!s)return _(`COMMAND_FAILED`,`find type was admitted without a text-entry operation`);let c=await D({operations:{typeText:s}},[n],v(i,r.flags,a.appBundleId,a.trace?.outPath));return Y(e,t,`type`),{ok:!0,data:c??{ref:t.ref}}}async function q(t,n){let{req:r,logPath:i,session:a}=t,o=J(n,`be focused`);if(o)return o;let s=n.resolvedNode.rect?e(n.resolvedNode.rect):null;if(!s)return _(`COMMAND_FAILED`,`matched element has no bounds`);y(a);let c=t.boundFocusPoint;return c?{ok:!0,data:await S({operations:{focusPoint:c}},s,v(i,r.flags,a.appBundleId,a.trace?.outPath))??{ref:n.ref}}:_(`COMMAND_FAILED`,`find focus was admitted without a focus operation`)}function J(e,t){let n=e.occludedNode;return n?_(`COMMAND_FAILED`,`Matched element ${e.ref} is covered by another visible element and cannot ${t} safely`,{ref:`@${n.ref}`,interactionBlocked:n.interactionBlocked,hint:`Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.`}):null}function Y(e,t,n){let{req:r,sessionStore:i,session:a,command:o,publicFlags:c}=e;s(i,a,r,o,{ref:t.ref,action:n},{flags:c})}function X(e){return{...b(e)??{}}}export{B as handleFindCommands};
|
package/dist/src/finders.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Mn as e}from"./sdk-batch.js";import{t}from"./sdk-finders.js";export{t as findBestMatchesByLocator,e as parseFindArgs};
|