agent-device 0.20.7 → 0.20.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.7.apk → agent-device-android-ime-helper-0.20.8.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.8.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.7.manifest.json → agent-device-android-ime-helper-0.20.8.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.7.apk → agent-device-android-snapshot-helper-0.20.8.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.8.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.7.manifest.json → agent-device-android-snapshot-helper-0.20.8.manifest.json} +6 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +5 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+RecordingTests.swift +4 -0
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/android.js +1 -1
- package/dist/src/app-lifecycle.js +7 -7
- package/dist/src/app-lifecycle2.js +1 -1
- package/dist/src/app-log-reconnect.js +1 -1
- package/dist/src/app-log-runtime.js +3 -3
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/apps.js +5 -5
- package/dist/src/auth-session.js +1 -1
- package/dist/src/boot-diagnostics.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +1 -1
- package/dist/src/cli.js +4 -4
- package/dist/src/client-metro.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/debug-symbols.js +3 -3
- package/dist/src/device-claim-inspection.js +1 -1
- package/dist/src/device-input-state.js +1 -1
- package/dist/src/device-ready.js +1 -0
- package/dist/src/dispatch.js +1 -0
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/generic-settle.js +1 -1
- package/dist/src/handler-utils.js +1 -0
- package/dist/src/harmonyos.js +1 -1
- package/dist/src/hdc.js +1 -0
- package/dist/src/helper.js +1 -1
- package/dist/src/host-process.js +3 -2
- package/dist/src/ime-lifecycle.js +5 -5
- package/dist/src/index.d.ts +21 -21
- package/dist/src/input-actions.js +4 -4
- package/dist/src/input-actions2.js +1 -1
- package/dist/src/install-artifact.js +1 -1
- package/dist/src/interaction-runtime.js +1 -1
- package/dist/src/interaction-snapshot.js +1 -1
- package/dist/src/interaction-touch-reference-frame.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interactor.js +1 -1
- package/dist/src/interactor2.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +7 -29
- package/dist/src/inventory2.js +1 -1
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun-runtime-dependencies.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/manifest.js +1 -1
- package/dist/src/notifications.js +1 -1
- package/dist/src/output-path.js +1 -0
- package/dist/src/owner-identity.js +1 -1
- package/dist/src/physical-device-control.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-network-web-transport.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +4 -4
- package/dist/src/platform-runtime-screen-recording-android-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-apple-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-apple-runner-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -0
- package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-apple-transport.js +1 -0
- package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-harmony-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-output-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-web-host.js +1 -0
- package/dist/src/platform-runtime-toolchain-host.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/prepare-kind.js +13 -13
- package/dist/src/provider-webdriver.js +1 -1
- package/dist/src/proxy.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -0
- package/dist/src/record-trace.js +1 -1
- package/dist/src/recording-telemetry.js +1 -0
- package/dist/src/registry.js +4 -4
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/replay.js +2 -2
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-lease.js +1 -1
- package/dist/src/runtime.js +3 -3
- package/dist/src/runtime2.js +3 -3
- package/dist/src/runtime3.js +3 -3
- package/dist/src/runtime4.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/screenshot-result.js +4 -4
- package/dist/src/sdk-android-adb.js +4 -4
- package/dist/src/sdk-batch-runner.js +2 -2
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +5 -1
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session-target-evidence.js +1 -1
- package/dist/src/session.js +10 -10
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-session.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src2.js +2 -2
- package/dist/src/src3.js +1 -1
- package/dist/src/text-surface.js +1 -1
- package/dist/src/tool-provider.js +3 -3
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tool-provider3.js +1 -1
- package/dist/src/update-check.js +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/video.js +23 -0
- package/dist/src/web.js +1 -1
- package/package.json +2 -4
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.7.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.7.apk.sha256 +0 -1
- package/dist/src/context.js +0 -1
- package/dist/src/provider.js +0 -1
- package/dist/src/runner-client.js +0 -1
- package/dist/src/runner-provider.js +0 -1
- package/skills/agent-device/SKILL.md +0 -20
- package/skills/dogfood/SKILL.md +0 -27
package/dist/src/prepare-kind.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{E as e,S as t,_ as n,d as r,f as i,g as a,p as o,u as s}from"./sdk-contracts.js";import{A as c,B as l,I as u,M as d,St as f,a as p,ct as m,d as h,j as g,o as _,r as ee,s as te,u as ne,x as re}from"./version.js";import{$t as ie,At as ae,Bn as oe,Cn as se,Ct as ce,Dn as v,Fn as le,J as ue,Mn as de,Mt as fe,On as pe,Ot as me,Pt as he,Q as ge,Rn as _e,St as ve,Tt as ye,ft as be,gn as xe,gt as Se,hn as Ce,ht as we,jn as y,jt as b,kn as Te,kt as Ee,mn as De,pn as Oe,pt as ke,q as Ae,rn as je,tn as Me,tr as x,vn as Ne,wn as Pe,y as Fe,zn as Ie}from"./sdk-batch-runner.js";import{p as Le}from"./sdk-device.js";import{a as Re,n as ze,r as Be,t as Ve}from"./text-surface.js";import"./device.js";import He from"node:path";import{styleText as Ue}from"node:util";import{createHash as We}from"node:crypto";const Ge=3e5,Ke=[`leaseId`,`tenantId`,`runId`,`clientId`,`deviceKey`];function qe(e){return x({tenantId:e.meta?.tenantId??S(e.flags,`tenant`),runId:e.meta?.runId??S(e.flags,`runId`),leaseId:e.meta?.leaseId??S(e.flags,`leaseId`),leaseTtlMs:e.meta?.leaseTtlMs,leaseBackend:e.meta?.leaseBackend,leaseProvider:e.meta?.leaseProvider??S(e.flags,`leaseProvider`)??S(e.flags,`provider`),deviceKey:e.meta?.deviceKey??S(e.flags,`deviceKey`),clientId:e.meta?.clientId??S(e.flags,`clientId`)})}function Je(e){return x({tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId,leaseTtlMs:e.leaseTtlMs??e.ttlMs,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider??e.provider,deviceKey:e.deviceKey,clientId:e.clientId})}function Ye(e){return x({tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId,leaseTtlMs:e.leaseTtlMs,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId})}function Xe(e){return x({tenant:e.tenantId,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId})}function Ze(e){return x({tenantId:e.tenantId??``,runId:e.runId??``,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId,ttlMs:e.leaseTtlMs})}function Qe(e){return it(e)}function $e(e){let{ttlMs:t,...n}=it(e);return n}function et(e,t,n){let r=x({...n.includeTokenParam?{token:n.token}:{},session:n.session,tenantId:e.tenantId,runId:e.runId,leaseProvider:e.leaseProvider,clientId:e.clientId,deviceKey:e.deviceKey});switch(t){case`lease_allocate`:return{...r,...x({ttlMs:e.leaseTtlMs,backend:e.leaseBackend})};case`lease_heartbeat`:return{...r,...x({leaseId:e.leaseId,ttlMs:e.leaseTtlMs})};case`lease_release`:return{...r,...x({leaseId:e.leaseId})}}}function tt(e){let t=x({leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId});return Object.keys(t).length>0?t:void 0}function nt(e){return e.leaseProvider===`proxy`}function rt(e){return nt(e)?Ke.filter(t=>!e[t]):[]}function it(e){return x({leaseId:e.leaseId??``,tenantId:e.tenantId,runId:e.runId,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId,ttlMs:e.leaseTtlMs})}function S(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function C(e){return e?{message:e}:{}}function w(e,t){return t?{...e,message:t}:e}function at(e){return typeof e?.message==`string`&&e.message.length>0?e.message:null}function ot(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function st(e,t,n){return{deviceId:t,deviceName:n,...Le(e)?{serial:t}:e===`ios`?{udid:t}:{}}}function ct(e,t={}){let n=t.includeSerial??!0,r=lt(e);return{platform:e.platform,target:e.target,device:e.name,id:e.id,...e.platform===`ios`?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},...n&&r?{serial:r}:{}}}function lt(e){return Le(e.platform)?e.identifiers.serial??e.id:void 0}function ut(e){return{name:e.name,...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...ct(e.device,{includeSerial:!1}),createdAt:e.createdAt}}function dt(e){return{platform:e.platform,...e.appleOs?{appleOs:e.appleOs}:{},id:e.id,name:e.name,kind:e.kind,target:e.target,...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function ft(e){return e.bundleId??e.package??e.app}function pt(e){return w({app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}},`Installed: ${ft(e)}`)}function mt(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function ht(e){return w({launchTarget:e.launchTarget,...e.appName?{appName:e.appName}:{},...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{package:e.packageName}:{},...e.installablePath?{installablePath:e.installablePath}:{},...e.archivePath?{archivePath:e.archivePath}:{},...e.materializationId?{materializationId:e.materializationId}:{},...e.materializationExpiresAt?{materializationExpiresAt:e.materializationExpiresAt}:{}},`Installed: ${mt(e)}`)}function gt(e){let t=e.appName??e.appBundleId??e.session;return w({session:e.session,...e.warnings?.length?{warnings:e.warnings}:{},...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...e.requestLogPath?{requestLogPath:e.requestLogPath}:{},...e.eventLogPath?{eventLogPath:e.eventLogPath}:{},...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?ct(e.device):{},...e.snapshot?{snapshot:e.snapshot}:{},...e.initialSnapshotError?{initialSnapshotError:e.initialSnapshotError}:{}},t?`Opened: ${t}`:`Opened`)}function _t(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...`provider`in e&&e.provider?{provider:e.provider}:{},...C(e.session?`Closed: ${e.session}`:`Closed`)}}function vt(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...f(yt(e)),...e.unchanged?{unchanged:e.unchanged}:{},...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{},...e.refsGeneration===void 0?{}:{refsGeneration:e.refsGeneration}}}function yt(e){return{...e,...e.snapshotQuality?{quality:e.snapshotQuality}:{}}}const bt=[`medium`,`high`],xt=`medium`;function St(e){return bt.includes(e)}function Ct(e){let t=typeof e==`number`?e:wt(e);return t!==void 0&&Number.isInteger(t)&&t>=5&&t<=10?t:void 0}function wt(e){return typeof e==`string`&&/^\d+$/.test(e)?Number(e):void 0}function Tt(e){if(St(e))return e;let t=Ct(e);if(t!==void 0)return t<=7?`medium`:`high`}const Et=[`app`,`device`,`system`];function Dt(e){return e===`device`||e===`system`}const Ot=Pt(`public`),kt=Pt(`internal`),At=Pt(`local-cli`),jt={help:`help`};function Mt(){return[...Object.values(Ot),...Object.values(At)].sort()}function Nt(e){return Object.values(jt).includes(e)||Object.values(kt).includes(e)?!0:Mt().includes(e)}function Pt(e){let t={};for(let[n,r]of Fe(e))t[n]=r;return t}const Ft=[`app`,`frontmost-app`,`desktop`,`menubar`],It=m(Ft,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid surface: ${e}. Use ${Ft.join(`|`)}.`});function Lt(e){return It.parse(e)}const Rt=`--launch-console is supported only for iOS simulator app launches`,zt=`--launch-console requires a direct app launch and cannot be used with URL opens`,Bt=[`path`,`start`,`stop`,`doctor`,`mark`,`clear`],Vt=[`metrics`,`frames`,`memory`,`cpu`,`trace`],Ht=[`sample`,`snapshot`,`start`,`stop`,`report`],Ut=[`profile`],Wt=[`xctrace`,`simpleperf`,`perfetto`,`android-hprof`,`memgraph`],Gt=[`android-hprof`,`memgraph`],Kt=m(Vt),qt=m(Ht),Jt=m(Ut),Yt=m(Wt),Xt=m(Gt),Zt=`perf area must be metrics, frames, memory, cpu, or trace`,Qt=`perf action must be sample, snapshot, start, stop, or report`,$t=`perf cpu requires profile`,en=`perf --kind must be xctrace, simpleperf, perfetto, android-hprof, or memgraph`,tn=`perf memory snapshot --kind must be android-hprof or memgraph`,nn=Kt.is,rn=qt.is,an=Jt.is,on=Yt.is,sn=Xt.is;function T(e){return e.width>0&&e.height>0}function cn(e,t){return!e||!t?!1:e.x>=t.x-2&&e.y>=t.y-2&&e.x+e.width<=t.x+t.width+2&&e.y+e.height<=t.y+t.height+2}function ln(e,t){if(!e||!t)return!0;let n=e.y+e.height/2,r=t.y+t.height/2;return Math.abs(n-r)<=Math.max(e.height,t.height,1)}function un(e){return typeof e.parentIndex!=`number`}function E(e){let t=(e.type??``).toLowerCase(),n=(e.identifier??``).trim().toLowerCase();return t.includes(`edittext`)||t.includes(`textfield`)||n===`composer`}function dn(e){let t=(e.type??``).toLowerCase();return t.includes(`scroll`)||t.includes(`list`)||t.includes(`recyclerview`)}function D(e){let t=h(e);if(!t||t!==e.identifier?.trim()||!fn(t))return t;let n=(e.type??``).toLowerCase();return n.includes(`view`)||n.includes(`layout`)||n.includes(`image`)||n.includes(`list`)||n.includes(`recyclerview`)||n.includes(`collection`)?``:t}function O(e){let t=e.trim().replace(/\s+/g,` `).toLowerCase();return!t||/^(true|false|\d+)$/.test(t)?null:t}function fn(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function pn(e,t,n){let r=e;for(;typeof r.parentIndex==`number`;){let e=t.get(r.parentIndex);if(!e)return null;if(n(e))return e;r=e}return null}function mn(e,t){let n=[],r=[t];for(;r.length>0;){let t=r.pop();for(let i of e)i.parentIndex===t&&(n.push(i),r.push(i.index))}return n}function k(e,t,n){let r=[t];for(;r.length>0;){let t=r.pop();if(!n.has(t)){n.add(t);for(let i of e)i.parentIndex!==t||n.has(i.index)||r.push(i.index)}}}const hn=[`button`,`switch`,`checkbox`,`radio`],gn=[`button`,`image`,`textview`,`view`];function _n(e,t,n){for(let r of e){if(t.has(r.index)||!bn(r))continue;let i=xn(mn(e,r.index),r,t);if(i.label){n.set(r.index,{...r,...n.get(r.index),label:i.label});for(let n of i.removableIndexes)k(e,n,t)}}}function vn(e,t,n){let r=new Map;for(let i of e){if(t.has(i.index)||!On(i))continue;let a=O(D(i));if(!a)continue;let o=r.get(a);if(o&&Tn(o,i,t)){let s=En(e,o,i,t,n);r.set(a,s);continue}r.set(a,i)}}function yn(e,t){for(let n of e){if(t.has(n.index)||!Cn(n))continue;let r=O(D(n));if(!r)continue;let i=mn(e,n.index).filter(e=>!t.has(e.index)&&wn(n,e,r));for(let n of i.filter(Sn))k(e,n.index,t);let a=i.filter(e=>!Sn(e)),o=new Set(a.map(e=>O(D(e))).filter(e=>!!e));if(!(a.length<2||o.size<2))for(let n of a)k(e,n.index,t)}}function bn(e){return e.hittable===!0&&!E(e)&&!!(e.rect&&T(e.rect))&&D(e).trim().length===0}function xn(e,t,n){let r=[],i=[],a=new Set;for(let o of e){if(n.has(o.index)||!Sn(o)||!cn(o.rect,t.rect))continue;let e=D(o).trim().replace(/\s+/g,` `),s=O(e);i.push(o.index),!(!e||!s||a.has(s))&&(a.add(s),r.push(e))}return{label:r.join(`, `),removableIndexes:i}}function Sn(e){if(e.hittable===!0||E(e))return!1;let t=(e.type??``).toLowerCase();return t.includes(`text`)||t.includes(`image`)||t.includes(`icon`)}function Cn(e){return e.hittable===!0&&!E(e)&&!!(e.rect&&T(e.rect))&&!!O(D(e))}function wn(e,t,n){if(!On(t)||!cn(t.rect,e.rect))return!1;let r=O(D(t));return!!(r&&n!==r&&n.includes(r))}function Tn(e,t,n){return!n.has(e.index)&&ln(e.rect,t.rect)&&(Nn(e,t)||Mn(e,t))}function En(e,t,n,r,i){let a=kn(t,n),o=a.index===t.index?n:t,s=(o.type??``).toLowerCase().includes(`image`)?`has image`:null,c=i.get(a.index)??a,l=i.get(o.index)?.presentationHints??o.presentationHints;return i.set(a.index,{...c,presentationHints:Dn(c.presentationHints,l,s)}),k(e,o.index,r),i.get(a.index)??a}function Dn(e,t,n){return[...new Set([...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...n?[n]:[]])]}function On(e){if(!e.rect||!T(e.rect)||un(e)||E(e))return!1;let t=(e.type??``).toLowerCase();return t===`text`||jn(t,gn)}function kn(e,t){let n=An(e);return An(t)>n?t:e}function An(e){let t=(e.type??``).toLowerCase(),n=0;return jn(t,hn)?n+=100:t.includes(`image`)?n+=30:t.includes(`textview`)||t===`text`?n+=20:t.includes(`view`)&&(n+=10),e.hittable===!0&&(n+=20),e.enabled!==!1&&(n+=5),n}function jn(e,t){return t.some(t=>e.includes(t))}function Mn(e,t){let n=e.parentIndex===t.index?t:t.parentIndex===e.index?e:null,r=n?.index===e.index?t:n?.index===t.index?e:null;return!n||!r?!1:kn(n,r).index===n.index}function Nn(e,t){return e.parentIndex===t.parentIndex?Math.abs(e.index-t.index)<=3:e.parentIndex===t.index||t.parentIndex===e.index?!1:Math.abs((e.depth??0)-(t.depth??0))<=1&&Math.abs(e.index-t.index)<=2}function Pn(e,t,n){if(n.raw||!Fn(e))return{nodes:t,filteredCount:0};let r=In(t);return{nodes:r,filteredCount:t.length-r.length}}function Fn(e){let t=e.androidSnapshot;return!t||typeof t!=`object`?!1:t.backend===`android-helper`}function In(e){if(e.length===0)return e;let t=new Set,n=new Map,r=new Map(e.map(e=>[e.index,e]));return Ln(e,t),Rn(e,r,t,n),_n(e,t,n),yn(e,t),vn(e,t,n),e.filter(e=>!t.has(e.index)).map(e=>n.get(e.index)??e)}function Ln(e,t){for(let n of e)!n.rect||T(n.rect)||un(n)||k(e,n.index,t)}function Rn(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||un(i))continue;let a=pn(i,t,dn);a&&Bn(r,a,zn(i,e)),k(e,i.index,n)}}function zn(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&T(t.rect)).map(e=>e.index);return n.length===0?null:e.index<Math.min(...n)?`above`:e.index>Math.max(...n)?`below`:null}function Bn(e,t,n){if(!n)return;let r=e.get(t.index)??t;e.set(t.index,{...r,hiddenContentAbove:r.hiddenContentAbove===!0||n===`above`?!0:void 0,hiddenContentBelow:r.hiddenContentBelow===!0||n===`below`?!0:void 0})}function Vn(e){return[...Hn(e),...Gn(e)]}function Hn(e){let t=Kn(e?.candidates);if(t.length===0)return[];let n=typeof e?.matches==`number`?e.matches:t.length,r=typeof e?.refsGeneration==`number`?e.refsGeneration:void 0,i=n-t.length;return[`Candidates:`,...t.map(e=>` ${Wn(e,r)}`),...i>0?[` +${i} more`]:[]]}function Un(e){return Kn(e?.candidates).flatMap(e=>{let t=/^@(e\d+)(?:~s\d+)?(?:\s|$)/.exec(e);return t?.[1]?[t[1]]:[]})}function Wn(e,t){return t===void 0?e:e.replace(/^@(e\d+)(?=\s|$)/,`@$1~s${t}`)}function Gn(e){let t=qn(e?.devices);return t.length===0?[]:[`Devices:`,...t.map(e=>` ${e.id} ${e.name}`)]}function Kn(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function qn(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`&&typeof e.name==`string`):[]}function Jn(e){let t=e.trim().replace(/\s+/g,` `).toLowerCase();return!t||Yn(t)?null:t}function Yn(e){return/\S+@\S+\.\S+/.test(e)}function Xn(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??``).toLowerCase(),r=Jn(h(n));if(!r)continue;let i=`${e}|${r}`,a=t.get(i)??[];a.push(n),t.set(i,a)}let n=0;for(let e of t.values())e.length<=1||!Zn(e)||(n+=e.length);return n>=8}function Zn(e){for(let t=0;t<e.length;t+=1)for(let n=t+1;n<e.length;n+=1)if(Qn(e[t]?.rect,e[n]?.rect))return!0;return!1}function Qn(e,t){if(!e||!t)return!0;let n=.5;return!(e.x+e.width<=t.x+n||t.x+t.width<=e.x+n||e.y+e.height<=t.y+n||t.y+t.height<=e.y+n)}const $n={digest:8*1024,default:24*1024,full:64*1024};function er(e){return e===`digest`||e===`full`?e:`default`}function tr(e,t=256){let n=Buffer.from(e,`utf8`);if(n.length<=t)return e;let r=`…<truncated>`,i=Buffer.byteLength(r,`utf8`),a=Math.max(0,t-i);for(;a>0&&(n[a]&192)==128;)--a;return`${n.subarray(0,a).toString(`utf8`)}${r}`}function A(t,n=256){return tr(e(t),n)}function nr(e,t){let n=e;for(let e of t)e.value&&(n=n.split(e.value).join(`<var:${e.name}>`));return n}function rr(e){return(t,n)=>A(nr(t,e),n)}function ir(e,t){return e.state!==`available`||e.refs.length<=t?e:{...e,refs:e.refs.slice(0,t),truncated:!0}}function ar(e,t){let n=er(t),r=n===`digest`?8:20,i=ir(e.screen,r),a=n===`digest`?[]:e.suggestions.slice(0,5);return{...e,screen:i,suggestions:a}}function or(e){return Buffer.byteLength(JSON.stringify(e),`utf8`)}function sr(e){let{divergence:t,level:n,writeOverflowArtifact:r}=e,i=er(n),a=$n[i],o=ar(t,n),s=or(o);if(s<=a)return o;let c=s-a,l=r(ar(t,`full`)),u=cr(o);return`artifactPath`in l?{...u,overflow:{omittedBytes:c,artifactPath:l.artifactPath}}:{...u,artifactUnavailable:!0}}function cr(e){return{version:e.version,kind:e.kind,step:{index:e.step.index,source:{path:A(e.step.source.path),line:e.step.source.line}},action:A(e.action),cause:{code:e.cause.code,message:A(e.cause.message),...e.cause.hint?{hint:A(e.cause.hint)}:{}},screen:{state:`unavailable`,reason:`omitted-for-size`,hint:`The screen digest and suggestions were omitted to stay within the response byte budget. See overflow.artifactPath (or retry at --level full) for the complete report.`},suggestions:[],suggestionCount:e.suggestionCount,resume:e.resume,repairHint:e.repairHint,...e.targetBinding?{targetBinding:e.targetBinding}:{}}}function lr(e){let t=e?.divergence;if(!t||typeof t!=`object`)return null;let n=t,r=[...xr(n.step),..._r(n.kind,n.targetBinding),...ur(n.repairHint,n.resume),...Sr(n.screen),...Er(n.suggestions,n.suggestionCount),...Or(n.overflow,n.artifactUnavailable)];return r.length>0?r.join(`
|
|
2
|
-
`):null}function
|
|
3
|
-
`)}\n`),i.diagnosticId&&process.stderr.write(`Diagnostic ID: ${i.diagnosticId}\n`),i.logPath&&process.stderr.write(`Diagnostics Log: ${i.logPath}\n`);let o=
|
|
4
|
-
`)}\n`:``,d=t.raw?null:
|
|
1
|
+
import{E as e,S as t,_ as n,d as r,f as i,g as a,p as o,u as s}from"./sdk-contracts.js";import{A as c,B as l,I as u,M as d,St as f,a as p,ct as m,d as h,j as g,o as _,r as ee,s as te,u as ne,x as re}from"./version.js";import{$t as ie,An as ae,At as oe,Bn as se,Ct as ce,In as le,Mn as v,Mt as ue,Nn as y,On as b,Ot as de,Pt as fe,Q as pe,St as me,Tn as he,Tt as ge,Vn as _e,Z as ve,_n as ye,en as be,gn as xe,hn as Se,ht as Ce,in as we,jt as x,kn as Te,kt as Ee,mn as De,nn as Oe,nr as S,nt as ke,wn as Ae,y as je,yn as Me,zn as Ne}from"./sdk-batch-runner.js";import{p as Pe}from"./sdk-device.js";import{a as Fe,n as Ie,r as Le,t as Re}from"./text-surface.js";import"./device.js";import ze from"node:path";import{styleText as Be}from"node:util";import{createHash as Ve}from"node:crypto";const He=3e5,Ue=[`leaseId`,`tenantId`,`runId`,`clientId`,`deviceKey`];function We(e){return S({tenantId:e.meta?.tenantId??C(e.flags,`tenant`),runId:e.meta?.runId??C(e.flags,`runId`),leaseId:e.meta?.leaseId??C(e.flags,`leaseId`),leaseTtlMs:e.meta?.leaseTtlMs,leaseBackend:e.meta?.leaseBackend,leaseProvider:e.meta?.leaseProvider??C(e.flags,`leaseProvider`)??C(e.flags,`provider`),deviceKey:e.meta?.deviceKey??C(e.flags,`deviceKey`),clientId:e.meta?.clientId??C(e.flags,`clientId`)})}function Ge(e){return S({tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId,leaseTtlMs:e.leaseTtlMs??e.ttlMs,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider??e.provider,deviceKey:e.deviceKey,clientId:e.clientId})}function Ke(e){return S({tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId,leaseTtlMs:e.leaseTtlMs,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId})}function qe(e){return S({tenant:e.tenantId,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId})}function Je(e){return S({tenantId:e.tenantId??``,runId:e.runId??``,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId,ttlMs:e.leaseTtlMs})}function Ye(e){return tt(e)}function Xe(e){let{ttlMs:t,...n}=tt(e);return n}function Ze(e,t,n){let r=S({...n.includeTokenParam?{token:n.token}:{},session:n.session,tenantId:e.tenantId,runId:e.runId,leaseProvider:e.leaseProvider,clientId:e.clientId,deviceKey:e.deviceKey});switch(t){case`lease_allocate`:return{...r,...S({ttlMs:e.leaseTtlMs,backend:e.leaseBackend})};case`lease_heartbeat`:return{...r,...S({leaseId:e.leaseId,ttlMs:e.leaseTtlMs})};case`lease_release`:return{...r,...S({leaseId:e.leaseId})}}}function Qe(e){let t=S({leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId});return Object.keys(t).length>0?t:void 0}function $e(e){return e.leaseProvider===`proxy`}function et(e){return $e(e)?Ue.filter(t=>!e[t]):[]}function tt(e){return S({leaseId:e.leaseId??``,tenantId:e.tenantId,runId:e.runId,leaseBackend:e.leaseBackend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey,clientId:e.clientId,ttlMs:e.leaseTtlMs})}function C(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function w(e){return e?{message:e}:{}}function T(e,t){return t?{...e,message:t}:e}function nt(e){return typeof e?.message==`string`&&e.message.length>0?e.message:null}function rt(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function it(e,t,n){return{deviceId:t,deviceName:n,...Pe(e)?{serial:t}:e===`ios`?{udid:t}:{}}}function at(e,t={}){let n=t.includeSerial??!0,r=ot(e);return{platform:e.platform,target:e.target,device:e.name,id:e.id,...e.platform===`ios`?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},...n&&r?{serial:r}:{}}}function ot(e){return Pe(e.platform)?e.identifiers.serial??e.id:void 0}function st(e){return{name:e.name,...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...at(e.device,{includeSerial:!1}),createdAt:e.createdAt}}function ct(e){return{platform:e.platform,...e.appleOs?{appleOs:e.appleOs}:{},id:e.id,name:e.name,kind:e.kind,target:e.target,...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function lt(e){return e.bundleId??e.package??e.app}function ut(e){return T({app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}},`Installed: ${lt(e)}`)}function dt(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function ft(e){return T({launchTarget:e.launchTarget,...e.appName?{appName:e.appName}:{},...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{package:e.packageName}:{},...e.installablePath?{installablePath:e.installablePath}:{},...e.archivePath?{archivePath:e.archivePath}:{},...e.materializationId?{materializationId:e.materializationId}:{},...e.materializationExpiresAt?{materializationExpiresAt:e.materializationExpiresAt}:{}},`Installed: ${dt(e)}`)}function pt(e){let t=e.appName??e.appBundleId??e.session;return T({session:e.session,...e.warnings?.length?{warnings:e.warnings}:{},...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...e.requestLogPath?{requestLogPath:e.requestLogPath}:{},...e.eventLogPath?{eventLogPath:e.eventLogPath}:{},...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?at(e.device):{},...e.snapshot?{snapshot:e.snapshot}:{},...e.initialSnapshotError?{initialSnapshotError:e.initialSnapshotError}:{}},t?`Opened: ${t}`:`Opened`)}function mt(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...`provider`in e&&e.provider?{provider:e.provider}:{},...w(e.session?`Closed: ${e.session}`:`Closed`)}}function ht(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...f(gt(e)),...e.unchanged?{unchanged:e.unchanged}:{},...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{},...e.refsGeneration===void 0?{}:{refsGeneration:e.refsGeneration}}}function gt(e){return{...e,...e.snapshotQuality?{quality:e.snapshotQuality}:{}}}const _t=[`medium`,`high`],vt=`medium`;function yt(e){return _t.includes(e)}function bt(e){let t=typeof e==`number`?e:xt(e);return t!==void 0&&Number.isInteger(t)&&t>=5&&t<=10?t:void 0}function xt(e){return typeof e==`string`&&/^\d+$/.test(e)?Number(e):void 0}function St(e){if(yt(e))return e;let t=bt(e);if(t!==void 0)return t<=7?`medium`:`high`}const Ct=[`app`,`device`,`system`];function wt(e){return e===`device`||e===`system`}const Tt=jt(`public`),Et=jt(`internal`),Dt=jt(`local-cli`),Ot={help:`help`};function kt(){return[...Object.values(Tt),...Object.values(Dt)].sort()}function At(e){return Object.values(Ot).includes(e)||Object.values(Et).includes(e)?!0:kt().includes(e)}function jt(e){let t={};for(let[n,r]of je(e))t[n]=r;return t}const Mt=[`app`,`frontmost-app`,`desktop`,`menubar`],Nt=m(Mt,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid surface: ${e}. Use ${Mt.join(`|`)}.`});function Pt(e){return Nt.parse(e)}const Ft=`--launch-console is supported only for iOS simulator app launches`,It=`--launch-console requires a direct app launch and cannot be used with URL opens`,Lt=[`path`,`start`,`stop`,`doctor`,`mark`,`clear`],Rt=[`metrics`,`frames`,`memory`,`cpu`,`trace`],zt=[`sample`,`snapshot`,`start`,`stop`,`report`],Bt=[`profile`],Vt=[`xctrace`,`simpleperf`,`perfetto`,`android-hprof`,`memgraph`],Ht=[`android-hprof`,`memgraph`],Ut=m(Rt),Wt=m(zt),Gt=m(Bt),Kt=m(Vt),qt=m(Ht),Jt=`perf area must be metrics, frames, memory, cpu, or trace`,Yt=`perf action must be sample, snapshot, start, stop, or report`,Xt=`perf cpu requires profile`,Zt=`perf --kind must be xctrace, simpleperf, perfetto, android-hprof, or memgraph`,Qt=`perf memory snapshot --kind must be android-hprof or memgraph`,$t=Ut.is,en=Wt.is,tn=Gt.is,nn=Kt.is,rn=qt.is;function E(e){return e.width>0&&e.height>0}function an(e,t){return!e||!t?!1:e.x>=t.x-2&&e.y>=t.y-2&&e.x+e.width<=t.x+t.width+2&&e.y+e.height<=t.y+t.height+2}function on(e,t){if(!e||!t)return!0;let n=e.y+e.height/2,r=t.y+t.height/2;return Math.abs(n-r)<=Math.max(e.height,t.height,1)}function sn(e){return typeof e.parentIndex!=`number`}function cn(e){let t=(e.type??``).toLowerCase(),n=(e.identifier??``).trim().toLowerCase();return t.includes(`edittext`)||t.includes(`textfield`)||n===`composer`}function ln(e){let t=(e.type??``).toLowerCase();return t.includes(`scroll`)||t.includes(`list`)||t.includes(`recyclerview`)}function D(e){let t=h(e);if(!t||t!==e.identifier?.trim()||!un(t))return t;let n=(e.type??``).toLowerCase();return n.includes(`view`)||n.includes(`layout`)||n.includes(`image`)||n.includes(`list`)||n.includes(`recyclerview`)||n.includes(`collection`)?``:t}function O(e){let t=e.trim().replace(/\s+/g,` `).toLowerCase();return!t||/^(true|false|\d+)$/.test(t)?null:t}function un(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function dn(e,t,n){let r=e;for(;typeof r.parentIndex==`number`;){let e=t.get(r.parentIndex);if(!e)return null;if(n(e))return e;r=e}return null}function fn(e,t){let n=[],r=[t];for(;r.length>0;){let t=r.pop();for(let i of e)i.parentIndex===t&&(n.push(i),r.push(i.index))}return n}function k(e,t,n){let r=[t];for(;r.length>0;){let t=r.pop();if(!n.has(t)){n.add(t);for(let i of e)i.parentIndex!==t||n.has(i.index)||r.push(i.index)}}}const pn=[`button`,`switch`,`checkbox`,`radio`],mn=[`button`,`image`,`textview`,`view`];function hn(e,t,n){for(let r of e){if(t.has(r.index)||!vn(r))continue;let i=yn(fn(e,r.index),r,t);if(i.label){n.set(r.index,{...r,...n.get(r.index),label:i.label});for(let n of i.removableIndexes)k(e,n,t)}}}function gn(e,t,n){let r=new Map;for(let i of e){if(t.has(i.index)||!En(i))continue;let a=O(D(i));if(!a)continue;let o=r.get(a);if(o&&Cn(o,i,t)){let s=wn(e,o,i,t,n);r.set(a,s);continue}r.set(a,i)}}function _n(e,t){for(let n of e){if(t.has(n.index)||!xn(n))continue;let r=O(D(n));if(!r)continue;let i=fn(e,n.index).filter(e=>!t.has(e.index)&&Sn(n,e,r));for(let n of i.filter(bn))k(e,n.index,t);let a=i.filter(e=>!bn(e)),o=new Set(a.map(e=>O(D(e))).filter(e=>!!e));if(!(a.length<2||o.size<2))for(let n of a)k(e,n.index,t)}}function vn(e){return e.hittable===!0&&!cn(e)&&!!(e.rect&&E(e.rect))&&D(e).trim().length===0}function yn(e,t,n){let r=[],i=[],a=new Set;for(let o of e){if(n.has(o.index)||!bn(o)||!an(o.rect,t.rect))continue;let e=D(o).trim().replace(/\s+/g,` `),s=O(e);i.push(o.index),!(!e||!s||a.has(s))&&(a.add(s),r.push(e))}return{label:r.join(`, `),removableIndexes:i}}function bn(e){if(e.hittable===!0||cn(e))return!1;let t=(e.type??``).toLowerCase();return t.includes(`text`)||t.includes(`image`)||t.includes(`icon`)}function xn(e){return e.hittable===!0&&!cn(e)&&!!(e.rect&&E(e.rect))&&!!O(D(e))}function Sn(e,t,n){if(!En(t)||!an(t.rect,e.rect))return!1;let r=O(D(t));return!!(r&&n!==r&&n.includes(r))}function Cn(e,t,n){return!n.has(e.index)&&on(e.rect,t.rect)&&(jn(e,t)||An(e,t))}function wn(e,t,n,r,i){let a=Dn(t,n),o=a.index===t.index?n:t,s=(o.type??``).toLowerCase().includes(`image`)?`has image`:null,c=i.get(a.index)??a,l=i.get(o.index)?.presentationHints??o.presentationHints;return i.set(a.index,{...c,presentationHints:Tn(c.presentationHints,l,s)}),k(e,o.index,r),i.get(a.index)??a}function Tn(e,t,n){return[...new Set([...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...n?[n]:[]])]}function En(e){if(!e.rect||!E(e.rect)||sn(e)||cn(e))return!1;let t=(e.type??``).toLowerCase();return t===`text`||kn(t,mn)}function Dn(e,t){let n=On(e);return On(t)>n?t:e}function On(e){let t=(e.type??``).toLowerCase(),n=0;return kn(t,pn)?n+=100:t.includes(`image`)?n+=30:t.includes(`textview`)||t===`text`?n+=20:t.includes(`view`)&&(n+=10),e.hittable===!0&&(n+=20),e.enabled!==!1&&(n+=5),n}function kn(e,t){return t.some(t=>e.includes(t))}function An(e,t){let n=e.parentIndex===t.index?t:t.parentIndex===e.index?e:null,r=n?.index===e.index?t:n?.index===t.index?e:null;return!n||!r?!1:Dn(n,r).index===n.index}function jn(e,t){return e.parentIndex===t.parentIndex?Math.abs(e.index-t.index)<=3:e.parentIndex===t.index||t.parentIndex===e.index?!1:Math.abs((e.depth??0)-(t.depth??0))<=1&&Math.abs(e.index-t.index)<=2}function Mn(e,t,n){if(n.raw||!Nn(e))return{nodes:t,filteredCount:0};let r=Pn(t);return{nodes:r,filteredCount:t.length-r.length}}function Nn(e){let t=e.androidSnapshot;return!t||typeof t!=`object`?!1:t.backend===`android-helper`}function Pn(e){if(e.length===0)return e;let t=new Set,n=new Map,r=new Map(e.map(e=>[e.index,e]));return Fn(e,t),In(e,r,t,n),hn(e,t,n),_n(e,t),gn(e,t,n),e.filter(e=>!t.has(e.index)).map(e=>n.get(e.index)??e)}function Fn(e,t){for(let n of e)!n.rect||E(n.rect)||sn(n)||k(e,n.index,t)}function In(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||sn(i))continue;let a=dn(i,t,ln);a&&Rn(r,a,Ln(i,e)),k(e,i.index,n)}}function Ln(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&E(t.rect)).map(e=>e.index);return n.length===0?null:e.index<Math.min(...n)?`above`:e.index>Math.max(...n)?`below`:null}function Rn(e,t,n){if(!n)return;let r=e.get(t.index)??t;e.set(t.index,{...r,hiddenContentAbove:r.hiddenContentAbove===!0||n===`above`?!0:void 0,hiddenContentBelow:r.hiddenContentBelow===!0||n===`below`?!0:void 0})}function zn(e){return[...Bn(e),...Un(e)]}function Bn(e){let t=Wn(e?.candidates);if(t.length===0)return[];let n=typeof e?.matches==`number`?e.matches:t.length,r=typeof e?.refsGeneration==`number`?e.refsGeneration:void 0,i=n-t.length;return[`Candidates:`,...t.map(e=>` ${Hn(e,r)}`),...i>0?[` +${i} more`]:[]]}function Vn(e){return Wn(e?.candidates).flatMap(e=>{let t=/^@(e\d+)(?:~s\d+)?(?:\s|$)/.exec(e);return t?.[1]?[t[1]]:[]})}function Hn(e,t){return t===void 0?e:e.replace(/^@(e\d+)(?=\s|$)/,`@$1~s${t}`)}function Un(e){let t=Gn(e?.devices);return t.length===0?[]:[`Devices:`,...t.map(e=>` ${e.id} ${e.name}`)]}function Wn(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Gn(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`&&typeof e.name==`string`):[]}function Kn(e){let t=e.trim().replace(/\s+/g,` `).toLowerCase();return!t||qn(t)?null:t}function qn(e){return/\S+@\S+\.\S+/.test(e)}function Jn(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??``).toLowerCase(),r=Kn(h(n));if(!r)continue;let i=`${e}|${r}`,a=t.get(i)??[];a.push(n),t.set(i,a)}let n=0;for(let e of t.values())e.length<=1||!Yn(e)||(n+=e.length);return n>=8}function Yn(e){for(let t=0;t<e.length;t+=1)for(let n=t+1;n<e.length;n+=1)if(Xn(e[t]?.rect,e[n]?.rect))return!0;return!1}function Xn(e,t){if(!e||!t)return!0;let n=.5;return!(e.x+e.width<=t.x+n||t.x+t.width<=e.x+n||e.y+e.height<=t.y+n||t.y+t.height<=e.y+n)}const Zn={digest:8*1024,default:24*1024,full:64*1024};function Qn(e){return e===`digest`||e===`full`?e:`default`}function $n(e,t=256){let n=Buffer.from(e,`utf8`);if(n.length<=t)return e;let r=`…<truncated>`,i=Buffer.byteLength(r,`utf8`),a=Math.max(0,t-i);for(;a>0&&(n[a]&192)==128;)--a;return`${n.subarray(0,a).toString(`utf8`)}${r}`}function A(t,n=256){return $n(e(t),n)}function er(e,t){let n=e;for(let e of t)e.value&&(n=n.split(e.value).join(`<var:${e.name}>`));return n}function tr(e){return(t,n)=>A(er(t,e),n)}function nr(e,t){return e.state!==`available`||e.refs.length<=t?e:{...e,refs:e.refs.slice(0,t),truncated:!0}}function rr(e,t){let n=Qn(t),r=n===`digest`?8:20,i=nr(e.screen,r),a=n===`digest`?[]:e.suggestions.slice(0,5);return{...e,screen:i,suggestions:a}}function ir(e){return Buffer.byteLength(JSON.stringify(e),`utf8`)}function ar(e){let{divergence:t,level:n,writeOverflowArtifact:r}=e,i=Qn(n),a=Zn[i],o=rr(t,n),s=ir(o);if(s<=a)return o;let c=s-a,l=r(rr(t,`full`)),u=or(o);return`artifactPath`in l?{...u,overflow:{omittedBytes:c,artifactPath:l.artifactPath}}:{...u,artifactUnavailable:!0}}function or(e){return{version:e.version,kind:e.kind,step:{index:e.step.index,source:{path:A(e.step.source.path),line:e.step.source.line}},action:A(e.action),cause:{code:e.cause.code,message:A(e.cause.message),...e.cause.hint?{hint:A(e.cause.hint)}:{}},screen:{state:`unavailable`,reason:`omitted-for-size`,hint:`The screen digest and suggestions were omitted to stay within the response byte budget. See overflow.artifactPath (or retry at --level full) for the complete report.`},suggestions:[],suggestionCount:e.suggestionCount,resume:e.resume,repairHint:e.repairHint,...e.targetBinding?{targetBinding:e.targetBinding}:{}}}function sr(e){let t=e?.divergence;if(!t||typeof t!=`object`)return null;let n=t,r=[...yr(n.step),...hr(n.kind,n.targetBinding),...cr(n.repairHint,n.resume),...br(n.screen),...wr(n.suggestions,n.suggestionCount),...Er(n.overflow,n.artifactUnavailable)];return r.length>0?r.join(`
|
|
2
|
+
`):null}function cr(e,t){if(typeof e!=`string`)return[];let n=dr(e,t);return[`Repair hint: ${e}${n?` — ${n}`:``}`]}function lr(e){let t=e;if(!t||typeof t.allowed!=`boolean`)return;if(!t.allowed)return{allowed:!1,reason:typeof t.reason==`string`?t.reason:void 0};let{from:n,planDigest:r,alternateFrom:i}=t;if(!(typeof n!=`number`||typeof r!=`string`||r.length===0))return{allowed:!0,from:n,planDigest:r,alternateFrom:typeof i==`number`?i:void 0}}function j(e,t){return`replay --from ${e} --plan-digest ${t}`}function ur(e){return e?.repairSessionHeld===!0}function dr(e,t){let n=fr(e,lr(t));if(n!==void 0)return ur(t)?`${n} Read-only inspection while armed (snapshot -i, get attrs, find, is) is excluded from the healed script by default — no --no-record needed. If the step you are repairing is itself a read, add --record to that command so it lands in the heal.`:n}function fr(e,t){switch(e){case`record-and-heal`:return t?.allowed?`press the correct control via a blessed @ref from screen.refs (recorded), then ${j(t.from,t.planDigest)}.`:`press the correct control via a blessed @ref from screen.refs (recorded). ${mr(t)}`;case`state-repair`:return t?.allowed?`fix app state with --no-record actions, then ${j(t.from,t.planDigest)} to re-run it.`:`fix app state with --no-record actions. ${mr(t)}`;case`caution`:return pr({lead:`something already matches the recorded selector; a blind re-press may repeat the mistake.`,guidance:t});case`manual`:return pr({lead:`no safe automated repair could be proven; inspect the screen and repair by hand.`,guidance:t});default:return}}function pr(e){let{lead:t,guidance:n}=e;if(!n?.allowed)return`${t} ${mr(n)}`;let r=`if you fixed app state with --no-record actions: ${j(n.from,n.planDigest)}`;return n.alternateFrom===void 0?`${t} ${r}.`:`${t} ${r}; ${`if you performed the step's intent as a recorded action: ${j(n.alternateFrom,n.planDigest)}`}.`}function mr(e){return e&&!e.allowed&&e.reason?`This step cannot currently be resumed automatically (${e.reason}) — run a fresh full replay instead.`:`This step cannot currently be resumed automatically — run a fresh full replay instead.`}function hr(e,t){if(typeof e!=`string`||e===`action-failure`)return[];let n=t;return n?[gr(e,n.matchCount),..._r(n.mismatches),...vr(n.candidates)]:[]}function gr(e,t){return`Target binding: ${e}${typeof t==`number`?` (matchCount ${t})`:``} — recorded target evidence did not verify.`}function _r(e){return!Array.isArray(e)||e.length===0?[]:[` mismatches: ${e.slice(0,5).join(`; `)}`]}function vr(e){return!Array.isArray(e)||e.length===0?[]:[` ${e.length} candidate(s) shared the recorded identity:`,...e.slice(0,5).map(e=>` ${Cr(e)}`)]}function yr(e){let t=e;if(typeof t?.index!=`number`)return[];let n=t.source,r=typeof n?.path==`string`&&typeof n.line==`number`?` (${n.path}:${n.line})`:``;return[`Divergence at step ${t.index}${r}`]}function br(e){let t=e;return t?.state===`available`&&Array.isArray(t.refs)?xr(t.refs,t.refsGeneration):t?.state===`unavailable`?[Sr(t)]:[]}function xr(e,t){let n=e.slice(0,8).map(Cr),r=e.length-n.length;return[`Screen: ${e.length} actionable ref(s) captured (refsGeneration ${t}).`,...n,...r>0?[` ... ${r} more`]:[]]}function Sr(e){let t=typeof e.hint==`string`&&e.hint.length>0?` ${e.hint}`:``;return`Screen: unavailable (${String(e.reason??`unknown`)}).${t}`}function Cr(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` @${String(t.ref)} [${String(t.role)}]${n}`}function wr(e,t){return Array.isArray(e)&&e.length>0?[`Suggestions:`,...e.slice(0,5).map(Tr)]:typeof t==`number`&&t>0?[`Suggestions: ${t} available (omitted at this response level; rerun with --json for the full report).`]:[]}function Tr(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` - [${String(t.basis)}]${n} ${String(t.selector)}`}function Er(e,t){return e&&typeof e==`object`?[`Full report written to ${String(e.artifactPath)}.`]:t===!0?[`Full report exceeded the response budget and the overflow artifact could not be written.`]:[]}const Dr={application:`application`,navigationbar:`navigation-bar`,tabbar:`tab-bar`,button:`button`,imagebutton:`button`,link:`link`,cell:`cell`,statictext:`text`,checkedtextview:`text`,textbox:`text-field`,textfield:`text-field`,edittext:`text-field`,textarea:`text-view`,switch:`switch`,slider:`slider`,image:`image`,imageview:`image`,webview:`webview`,framelayout:`group`,linearlayout:`group`,relativelayout:`group`,constraintlayout:`group`,viewgroup:`group`,view:`group`,listview:`list`,recyclerview:`list`,collectionview:`collection`,searchfield:`search`,heading:`heading`,activityindicator:`activity-indicator`,progressindicator:`progress-indicator`,segmentedcontrol:`segmented-control`,group:`group`,window:`window`,checkbox:`checkbox`,radio:`radio`,menuitem:`menu-item`,toolbar:`toolbar`,scrollarea:`scroll-area`,scrollview:`scroll-area`,nestedscrollview:`scroll-area`,table:`table`};function Or(e,t={}){let n=[],r=[];for(let i of e){let e=i.depth??0,a=i.label?.trim()||i.value?.trim()||i.identifier?.trim()||``,o=P(i.type??`Element`),s=i.inheritsLabel===!0||i.inheritsIdentifier===!0;if(o===`group`&&!a&&!s)continue;for(;n.length>0&&e<=n[n.length-1];)n.pop();let c=n.length;n.push(e),r.push({node:i,depth:c,type:o,text:M(i,c,!1,o,t)})}return r}function M(e,t,n,r,i={}){let a=r??P(e.type??`Element`),o=Ie(e,a),s=Fr(e,a,i,o),c=` `.repeat(t),l=e.ref?`@${e.ref}`:``,u=Ir(e,a,i,o);!s&&(e.inheritsLabel===!0||e.inheritsIdentifier===!0)&&u.push(`same label as parent`);let d=u.map(e=>` [${e}]`).join(``),f=s?` "${s}"`:``,p=kr(e);return n?`${c}${l} [${a}]${d}${p}`.trimEnd():`${c}${l} [${a}]${f}${d}${p}`.trimEnd()}function kr(e){let t=e.actions?.filter(e=>e.trim().length>0);return!t||t.length===0?``:` actions: [${t.map(e=>`"${zr(Ar(e))}"`).join(`, `)}]`}function Ar(e){return e.replace(/\s+/g,` `).replace(/[\u0000-\u001f\u007f-\u009f]/g,``).trim()}function N(e,t){let n=e.label?.trim();if(n&&Nr(t,n))return``;let r=e.value?.trim();if(Mr(t)){if(r)return r;if(n)return n}else if(n)return n;if(r)return r;let i=e.identifier?.trim();return!i||Pr(i)&&(t===`group`||t===`image`||t===`list`||t===`collection`)?``:i}function P(e){let t=e,n=e.replace(/XCUIElementType/gi,``).toLowerCase(),r=t.includes(`.`)&&(t.startsWith(`android.`)||t.startsWith(`androidx.`)||t.startsWith(`com.`));return n.includes(`.`)&&(n=n.replace(/^android\.widget\./,``).replace(/^android\.view\./,``).replace(/^android\.webkit\./,``).replace(/^androidx\./,``).replace(/^com\.google\.android\./,``).replace(/^com\.android\./,``),r&&n.includes(`.`)&&(n=n.slice(n.lastIndexOf(`.`)+1))),n===`textview`?r?`text`:`text-view`:jr(n)||n||`element`}function jr(e){return Object.prototype.hasOwnProperty.call(Dr,e)?Dr[e]:void 0}function Mr(e){return e===`text-field`||e===`text-view`||e===`search`}function Nr(e,t){return e!==`scroll-area`&&e!==`list`&&e!==`collection`&&e!==`table`?!1:ne(t)}function Pr(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function Fr(e,t,n,r){return!n.summarizeTextSurfaces||!r.shouldSummarize?N(e,t):Lr(e,t,r.text)||N(e,t)}function Ir(e,t,n,r){let i=[];return e.enabled===!1&&i.push(`disabled`),i.push(...e.presentationHints??[]),!n.summarizeTextSurfaces||(e.selected===!0&&i.push(`selected`),e.focused===!0&&i.push(`focused`),Mr(t)&&i.push(`editable`),Rr(e,t)&&i.push(`scrollable`),!r.shouldSummarize)?Br(i):(i.push(`preview:"${zr(Re(r.text))}"`),i.push(`truncated`),Br(i))}function Lr(e,t,n){let r=Fe(e.label);if(r&&r!==n)return r;let i=Fe(e.identifier);if(i&&!Pr(i)&&i!==n)return i;switch(t){case`text`:case`text-view`:return`Text view`;case`text-field`:return`Text field`;case`search`:return`Search field`;default:return``}}function Rr(e,t){if(t===`scroll-area`)return!0;let n=(e.type??``).toLowerCase(),r=`${e.role??``} ${e.subrole??``}`.toLowerCase();return n.includes(`scroll`)||r.includes(`scroll`)}function zr(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Br(e){return[...new Set(e)]}function Vr(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}function Hr(e,r={}){let i=e instanceof n?t(e):e;process.stderr.write(`Error (${i.code}): ${i.message}\n`),i.hint&&process.stderr.write(`Hint: ${i.hint}\n`);let a=zn(i.details);a.length>0&&process.stderr.write(`${a.join(`
|
|
3
|
+
`)}\n`),i.diagnosticId&&process.stderr.write(`Diagnostic ID: ${i.diagnosticId}\n`),i.logPath&&process.stderr.write(`Diagnostics Log: ${i.logPath}\n`);let o=sr(i.details);o&&process.stderr.write(`${o}\n`),r.showDetails&&i.details&&process.stderr.write(`${JSON.stringify(i.details,null,2)}\n`)}function Ur(e,t={}){let n=e.nodes,r=Array.isArray(n)?n:[],o=a(i(e.backend)?e.backend:void 0),s=Mn(e,r,t),c=qr(e),l=fi(e,r,t,s),u=l.length>0?`${l.join(`
|
|
4
|
+
`)}\n`:``,d=t.raw?null:Wr(e);if(d)return`${c}${u}${Gr(d)}\n`;let f=t.raw||!o?null:p(s.nodes),m=!!e.truncated,h=f?.nodes??r,g=t.raw||!o?null:$r(e,f,h.length,r.length,s.filteredCount),_=Jr(r.length,g,m);return r.length===0?`${c}${_}\n${u}`:t.raw?`${c}${_}\n${u}${Yr(r)}\n`:t.flatten?`${c}${_}\n${u}${Xr(h)}${Qr(f)}\n`:`${c}${_}\n${u}${Zr(h)}${Qr(f)}\n`}function Wr(e){let t=e.unchanged;if(!t||typeof t!=`object`)return null;let n=t;return typeof n.ageMs!=`number`||typeof n.nodeCount!=`number`?null:{ageMs:n.ageMs,nodeCount:n.nodeCount,interactiveOnly:n.interactiveOnly===!0?!0:void 0,scope:typeof n.scope==`string`?n.scope:void 0}}function Gr(e){let t=Kr(e.ageMs);return e.scope?[`Scoped snapshot unchanged for scope "${e.scope}" since previous read ${t} ago.`,`Previous refs in this scope remain valid. Use find/get/is for a targeted query, or --force-full to re-emit.`].join(`
|
|
5
5
|
`):e.interactiveOnly?[`Interactive snapshot unchanged since previous read ${t} ago.`,`${e.nodeCount} visible nodes are unchanged. Previous @e refs are still valid. Use find/get/is for a targeted query, or --force-full to re-emit.`].join(`
|
|
6
6
|
`):[`Snapshot unchanged since previous read ${t} ago.`,`Refs from the previous snapshot are still valid. Use --force-full to re-emit the tree, or use find/get/is for a targeted query.`].join(`
|
|
7
|
-
`)}function
|
|
8
|
-
`)}\n`:``}function
|
|
9
|
-
`)}function
|
|
10
|
-
`)}function
|
|
11
|
-
`)}function
|
|
12
|
-
`)}`:``}function
|
|
13
|
-
`)}\n`:``;if(t)return`${c}Baseline initialized (${a} lines).\n`;let l=
|
|
14
|
-
`)}\n`:``;return o?`${c}${u}${[`${
|
|
15
|
-
`)}\n`}function oi(e,t){if(e.match===!0)return[`${t?I(`✓`,`green`):`✓`} Screenshots match.`];let n=e.dimensionMismatch,r=t?I(`✗`,`red`):`✗`;if(n){let e=n.expected,t=n.actual;return[`${r} Screenshots have different dimensions: expected ${e?.width}x${e?.height}, got ${t?.width}x${t?.height}`]}let i=F(e.differentPixels),a=F(e.mismatchPercentage),o=`${a===0&&i>0?`<0.01`:String(a)}% pixels differ`;return[`${r} ${t?I(o,`red`):o}`]}function si(e,t,n){if(t)return[];let r=[];if(e.diffPath){let t=di(e.diffPath),i=n?I(`Diff image:`,`dim`):`Diff image:`,a=n?I(t,`green`):t;r.push(` ${i} ${a}`)}if(e.currentOverlayPath){let t=di(e.currentOverlayPath),i=n?I(`Current overlay:`,`dim`):`Current overlay:`,a=n?I(t,`green`):t,o=F(e.currentOverlayRefCount),s=o>0?` (${o} refs)`:``;r.push(` ${i} ${a}${s}`)}return r}function ci(e,t){let n=F(e.differentPixels),r=F(e.totalPixels);return[` ${t?I(String(n),`red`):String(n)} different / ${r} total pixels`]}function li(e,t){let n=Array.isArray(e.regions)?e.regions:[];if(n.length===0)return[];let r=[` ${mi(`Changed regions:`,t)}`];for(let e of n.slice(0,5))r.push(...ui(e));return r}function ui(e){let t=e.shareOfDiffPercentage===0&&e.differentPixels>0?`<0.01`:String(e.shareOfDiffPercentage),n=e.rect,r=[` ${e.index}. x=${n.x} y=${n.y} ${n.width}x${n.height}, ${t}% of diff`],i=e.currentOverlayMatches?.[0];if(i){let e=i.label?` "${i.label}"`:``;r.push(` overlaps @${i.ref}${e}, ${i.regionCoveragePercentage}% of region`)}return r}function di(e){let t=process.cwd(),n=He.relative(t,e);return n===``||!n.startsWith(`..`)&&!He.isAbsolute(n)?n===``?`.`:`.${He.sep}${n}`:e}function F(e){return typeof e==`number`&&Number.isFinite(e)?e:0}function fi(e,t){if(e.length===0)return e;let n=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>e.kind===`added`||e.kind===`removed`).map(e=>e.index);if(n.length===0)return e;let r=Array(e.length).fill(!1);for(let i of n){let n=Math.max(0,i-t),a=Math.min(e.length-1,i+t);for(let e=n;e<=a;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])}function pi(e=process.stdout){let t=process.env.FORCE_COLOR;return typeof t==`string`?t!==`0`:typeof process.env.NO_COLOR==`string`?!1:!!e.isTTY}function I(e,t,n){return Ue(t,e,n)}function mi(e,t){return t?I(e,`dim`):e}function hi(e,t,n,r={nodes:t,filteredCount:0}){let i=yi(e);if(gi(e)){let e=vi(t,n);e&&i.push(e)}!n.raw&&r.filteredCount>0&&i.push(`Collapsed ${r.filteredCount} Android helper node${r.filteredCount===1?``:`s`} from the agent-facing text snapshot; use --raw or --json for the full hierarchy.`);let a=r.filteredCount>0?r.nodes:t;return!n.raw&&Xn(a)&&i.push(`Warning: possible repeated nav subtree detected.`),i}function gi(e){return!e.snapshotQuality&&!_i(e)}function _i(e){let t=e.snapshotDiagnostics;if(!t||typeof t!=`object`)return!1;let n=t.stats;return!!(n&&typeof n==`object`&&n.platform===`web`)}function vi(e,t){if(t.scoped===!0||t.depthLimited===!0||e.length>3)return null;let n=e.length===1?`node`:`nodes`;return`Hint: sparse accessibility snapshot returned ${e.length} ${n}; snapshot state is invalid or unavailable for this screen. Use plain screenshot, not screenshot --overlay-refs, as visual truth. If screenshot shows the Home Screen or another app, run open for this app again first. Then navigate away with coordinates if needed and retry snapshot -i on the next screen.`}function yi(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.length>0):[]}function bi(e){let t=[],n=[],r=new Map(e.map(e=>[e.node.index,e.node])),i=e=>{for(;n.length>0&&(!e||xi(e,n[n.length-1],r));)t.push(...wi(n.pop(),`below`))};for(let r of e)i(r),t.push(r.text),t.push(...wi(r,`above`)),r.node.hiddenContentBelow&&n.push(r);return i(),t}function xi(e,t,n){return Si(e.node,t.node,n)?!1:e.depth<=t.depth}function Si(e,t,n){let r=e;for(;typeof r.parentIndex==`number`;){if(r.parentIndex===t.index)return!0;let e=n.get(r.parentIndex);if(!e)return!1;r=e}return!1}function Ci(e){return Ar(e,{summarizeTextSurfaces:!0}).flatMap(e=>[M(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...wi({...e,depth:0})])}function wi(e,t){let n=Ti(e.type);if(!n)return[];let r=[];if(e.node.hiddenContentAbove&&t!==`below`&&r.push(`[content above ${n} hidden]`),e.node.hiddenContentBelow&&t!==`above`&&r.push(`[content below ${n} hidden]`),r.length===0)return[];let i=` `.repeat(e.depth+1);return r.map(e=>`${i}${e}`)}function Ti(e){return e===`scroll-area`||e===`list`||e===`collection`||e===`table`?e:null}function Ei(e,t,n={}){let r=ji(e);if(r.length===0)return{canScroll:!1,emptySnapshot:!0};let i=te(r),a=Mi(r,i,t,n);return a?{canScroll:Pi(a,i.get(a.index),t),emptySnapshot:!1,scope:Fi(a,r)}:{canScroll:!1,emptySnapshot:!1}}async function Di(e){let{edge:t,target:n={},scope:r,captureNodes:i}=e;try{let e=Ei(await i(r),t,n);return r&&e.emptySnapshot?await Di({edge:t,target:n,captureNodes:i}):e}catch(e){throw Ai(t,r,e)}}async function Oi(e){let{edge:t,captureState:r,scroll:i}=e,a=await r();a.scope&&(a=await r(a.scope));let o=0,s;for(;a.canScroll;){if(o>=40)throw new n(`COMMAND_FAILED`,`scroll ${t} reached the safety limit before the snapshot showed the edge`,{hint:`The scoped scroll container still reports hidden content. Use a smaller manual scroll + snapshot loop to inspect the current state.`});s=await i(),o+=1,a=await r(a.scope)}return{passes:o,result:s}}function ki(e,t,n,r,i){return t&&n===0?`Already at ${t}; no hidden content ${t===`bottom`?`below`:`above`} detected`:t?`Scrolled to ${t} with ${n} ${e} passes`:i===void 0?r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`:`Scrolled ${e} by ${i}px`}function Ai(e,t,r){return t?new n(`COMMAND_FAILED`,`Failed to verify scroll ${e} state for scoped container`,{scope:t,hint:`scroll ${e} could not verify the scoped scroll container. Run snapshot -i for the current screen and retry with a visible scroll target.`},r):new n(`COMMAND_FAILED`,`Failed to verify scroll ${e} state`,{hint:`scroll ${e} needs a snapshot showing hidden content ${e===`bottom`?`below`:`above`} before it will move.`},r)}function ji(e){return e.map((e,t)=>({...e,ref:`ref`in e&&e.ref?e.ref:`e${t+1}`}))}function Mi(e,t,n,r){let i=new Map(e.map(e=>[e.index,e])),a=e.filter(e=>oe(e)&&Vi(e.rect));if(a.length===0)return null;let o=Ni(r.nodeIndex,i);if(o)return o;let s=r.point;if(s){let e=a.filter(e=>e.rect&&Bi(e.rect,s)).sort(Ri);if(e.length>0)return e.find(e=>Pi(e,t.get(e.index),n))??e[0]??null}let c=a.filter(e=>Pi(e,t.get(e.index),n)).sort(zi);return c.length>0?c[0]??null:a.filter(t=>se(t,e)).sort(zi)[0]??a.sort(zi)[0]??null}function Ni(e,t){if(e===void 0)return null;let n=t.get(e);for(;n;){if(oe(n)&&Vi(n.rect))return n;n=n.parentIndex===void 0?void 0:t.get(n.parentIndex)}return null}function Pi(e,t,n){return n===`bottom`?e.hiddenContentBelow===!0||t?.hiddenContentBelow===!0:e.hiddenContentAbove===!0||t?.hiddenContentAbove===!0}function Fi(e,t){return[e.identifier,e.label].filter(e=>typeof e==`string`).map(e=>e.trim()).find(n=>Li(n)&&Ii(n,e,t))}function Ii(e,t,n){let r=e.toLowerCase(),i=n.filter(e=>[e.identifier,e.label,e.value].some(e=>typeof e==`string`&&e.trim().toLowerCase().includes(r)));return i.length===1&&i[0]?.index===t.index}function Li(e){return e.length>0&&e.length<=80&&!/^(true|false)$/i.test(e)&&!/^\d+$/.test(e)&&!/^\d+%$/.test(e)}function Ri(e,t){return L(e.rect)-L(t.rect)}function zi(e,t){return L(t.rect)-L(e.rect)}function L(e){return e?e.width*e.height:0}function Bi(e,t){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}function Vi(e){return!!(e&&e.width>0&&e.height>0)}function Hi(e,t,r,i){if(!Number.isFinite(e)||!Number.isInteger(e)||e<r||e>i)throw new n(`INVALID_ARGS`,`${t} must be an integer between ${r} and ${i}`);return e}function R(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}function z(e){return e.clock?.now()??Date.now()}async function Ui(e,t){e.clock?await e.clock.sleep(t):await new Promise(e=>setTimeout(e,t))}function Wi(e,t){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,e=>n(t,e)]))}function B(e){return e&&typeof e==`object`?e:void 0}function Gi(e){let t=Buffer.alloc(16);for(let n of e)qi(t,Ki(n));return{digest:`ax1:${We(`sha256`).update(t).update(`\0`).update(String(e.length)).digest(`hex`).slice(0,16)}`,nodeCount:e.length}}function Ki(e){return We(`sha256`).update(e.type??``).update(`\0`).update(e.label??``).update(`\0`).update(e.identifier??``).digest().subarray(0,16)}function qi(e,t){for(let n=0;n<e.length;n+=1)e[n]=(e[n]??0)^(t[n]??0)}function V(e){let{digest:t,nodeCount:n}=Gi(e),r=e.reduce((e,t)=>t.hittable===!1?e:e+1,0),i=Ji(e);return{digest:t,nodeCount:n,interactiveNodeCount:r,...i?{foregroundApp:i}:{}}}function Ji(e){for(let t of e)if(t.bundleId)return t.bundleId;for(let t of e)if(t.appName)return t.appName}const Yi=[`x`,`y`,`width`,`height`];function H(e){let t=U(e);if(!t)return null;let n=s(t);return!Number.isFinite(n.x)||!Number.isFinite(n.y)?null:n}function U(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),i=Number(e.height);return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||r<0||i<0?null:{x:t,y:n,width:r,height:i}}function W(e,t){return!e||!t?!1:Yi.every(n=>Math.abs(e[n]-t[n])<=.5)}function Xi(e){return{x:Zi(e.x,e.width),y:Zi(e.y,e.height)}}function Zi(e,t){if(t<=1)return Math.floor(e);let n=Math.ceil(e),r=Math.floor(e+t-1);return Math.round(Math.min(r,Math.max(n,e+t/2)))}function Qi(e){let t=new Map;for(let n of e)t.set(n.index,n);return t}function $i(e,t,n){let r=[],i=new Set([e.index]),a=e;for(;r.length<n;){if(typeof a.parentIndex!=`number`)return{chain:r,broken:!1};let e=t.get(a.parentIndex);if(!e||i.has(e.index))return{chain:r,broken:!0};i.add(e.index);let n=b(e);r.push({role:n.role,...n.label===void 0?{}:{label:n.label}}),a=e}return{chain:r,broken:!1}}function ea(e,t,n,r){return e.filter(e=>{if(!ae(b(e),n))return!1;let i=$i(e,t,Math.max(r.length,1));return!i.broken&&Ee(i.chain,r)})}function ta(e,t){let n=t.toLowerCase();return e.find(e=>{let t=(e.label??``).toLowerCase(),r=(e.value??``).toLowerCase(),i=(e.identifier??``).toLowerCase();return t.includes(n)||r.includes(n)||i.includes(n)})??null}function G(e,t){let n=[e.label,e.value,e.identifier].map(e=>typeof e==`string`?e.trim():``).find(e=>e&&e.length>0);return n&&K(n)?n:na(e,t)??(n&&K(n)?n:void 0)}function K(e){let t=e.trim();return!(!t||/^(true|false)$/i.test(t)||/^\d+$/.test(t))}function na(e,t){if(!e.rect)return;let n=e.rect.y+e.rect.height/2,r=null;for(let e of t){if(!e.rect)continue;let t=[e.label,e.value,e.identifier].map(e=>typeof e==`string`?e.trim():``).find(e=>e&&e.length>0);if(!t||!K(t))continue;let i=e.rect.y+e.rect.height/2,a=Math.abs(i-n);(!r||a<r.distance)&&(r={label:t,distance:a})}return r?.label}function ra(e){let t=[],n=[];for(let r of e){let e=r.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let i=y(r.type??``),a=[r.label,r.value,r.identifier].map(e=>typeof e==`string`?e.trim():``).find(e=>e&&e.length>0),o=a?K(a):!1;if((i===`group`||i===`ioscontentgroup`)&&!o){t.push(e);continue}let s=Math.max(0,e-t.length);n.push({...r,depth:s})}return n}function ia(e,t){return t.hittable?t:aa(e,t,e=>e.hittable===!0)}function aa(e,t,n){return Ie(e,t,_e(e),e=>n(e)?e:null)}function oa(e){return Be(e)}const sa=[`tabbar`,`toolbar`,`navigationbar`,`bottomnavigation`,`bottomnavigationview`,`sheet`,`dialog`,`alert`,`popover`,`menu`],ca=[`tabbar`,`toolbar`,`navigationbar`],la=[`button`,`link`,`menuitem`,`tabitem`,`textfield`,`searchfield`,`edittext`,`checkbox`,`radio`,`switch`,`cell`];function ua(e,t={}){if(e.length<2)return e;let n=new Map(e.map(e=>[e.index,e])),r={nodes:e,byIndex:n,overlayPositions:e.flatMap((e,r)=>ga(e,n,t)?[r]:[]),coverCache:new Map},i=[];for(let[n,a]of e.entries())ha(a)&&da(r,n,a,t)&&i.push(n);if(i.length===0)return e;let a=[...e];for(let t of i){let n=e[t];a[t]={...n,hittable:!1,interactionBlocked:`covered`,presentationHints:Ea(n.presentationHints)}}return a}function q(e){return e.interactionBlocked!==void 0}function da(e,t,n,r){let i=e.coverCache.get(t);if(i!==void 0)return i;e.coverCache.set(t,null);let a=J(n.rect);if(!a)return fa(e,t,null);let o=s(a);for(let i of e.overlayPositions){if(i<=t)continue;let s=e.nodes[i];if(s&&pa(e,i,n,a,o,r))return fa(e,t,s)}return fa(e,t,null)}function fa(e,t,n){return e.coverCache.set(t,n),n}function pa(e,t,n,r,i,a){if(!e.nodes[t])return!1;let o=ma(e,t,n,r,a);return!!(o&&de(o,i.x,i.y))}function ma(e,t,n,r,i){let a=e.nodes[t];if(!a||!ga(a,e.byIndex,i)||wa(n,a,e.byIndex))return null;let o=J(a.rect);return!o||W(r,o)||da(e,t,a,i)?null:o}function ha(e){return J(e.rect)?e.hittable===!0||xa(e)?!0:!!(e.label?.trim()||e.value?.trim()||e.identifier?.trim()):!1}function ga(e,t,n){return!J(e.rect)||v(e)||_a(e,t)?!1:Sa(e,sa)||va(e,t,n)}function _a(e,t){if(!Sa(e,ca))return!1;let n=J(e.rect);if(!n)return!1;let r=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(v(r)){let e=J(r.rect);return!!(e&&W(n,e))}i.add(r.index),r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}return!1}function va(e,t,n){return n.isAdditionalOverlayNode?.(e)===!0?!ya(e,t,n):!1}function ya(e,t,n){let r=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(ba(r,n))return!0;i.add(r.index),r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}return!1}function ba(e,t){return t.isAdditionalOverlayNode?.(e)===!0&&J(e.rect)!==null&&!v(e)}function xa(e){return Sa(e,la)}function Sa(e,t){let n=Ca(e);return t.some(e=>n.includes(e))}function Ca(e){return[e.type,e.role,e.subrole].map(e=>y(e??``)).join(` `)}function wa(e,t,n){return Ta(e,t,n)||Ta(t,e,n)}function Ta(e,t,n){let r=typeof t.parentIndex==`number`?n.get(t.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(r.index===e.index)return!0;i.add(r.index),r=typeof r.parentIndex==`number`?n.get(r.parentIndex):void 0}return!1}function J(e){let t=U(e);return t&&t.width>0&&t.height>0?t:null}function Ea(e){return Array.from(new Set([...e??[],`covered`]))}const Da=[`button`,`link`,`menuitem`,`tabitem`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];function Oa(e,t){let n=t[0];if(!n||!ka(t,new Map(e.map(e=>[e.index,e]))))return{kind:`ambiguous`,candidates:t};let r=Y(e,n).node;for(let n of t.slice(1))if(Y(e,n).node.index!==r.index)return{kind:`ambiguous`,candidates:t};return{kind:`equivalent`,node:r}}function ka(e,t){for(let n=0;n<e.length;n+=1)for(let r=n+1;r<e.length;r+=1){let i=e[n],a=e[r];if(!Aa(i,a,t)&&!Aa(a,i,t))return!1}return!0}function Aa(e,t,n){let r=t,i=new Set;for(;r.parentIndex!==void 0&&!i.has(r.index);){if(i.add(r.index),r.parentIndex===e.index)return!0;let t=n.get(r.parentIndex);if(!t)return!1;r=t}return!1}function ja(e,t){return Y(e,t).node}function Y(e,t){if(q(t))return{node:t,reason:`covered`};let n=Ma(e,t);if(n?.rect&&H(n.rect))return{node:n,reason:`same-rect-descendant`};if(Na(t)&&t.rect&&H(t.rect))return{node:t,reason:`semantic-target`};let r=ia(e,t);return r?.rect&&!q(r)&&H(r.rect)?Fa(t,r,e)?{node:t,reason:`overly-broad-ancestor`}:{node:r,reason:`hittable-ancestor`}:{node:t,reason:`original`}}function Ma(e,t){let n=U(t.rect);if(!n)return null;let r=t,i=new Set;for(;!i.has(r.ref);){i.add(r.ref);let t=e.filter(e=>{if(e.parentIndex!==r.index||!e.hittable||q(e))return!1;let t=U(e.rect);return t?W(t,n):!1});if(t.length!==1)break;r=t[0]}return r===t?null:r}function Na(e){return[e.type,e.role,e.subrole].map(e=>y(e??``)).some(Pa)}function Pa(e){return e===`tab`||Da.some(t=>e.includes(t))}function Fa(e,t,n){let r=U(e.rect),i=U(t.rect);if(!r||!i)return!1;if(Ia(t)&&!W(r,i))return!0;let a=La(n,r);return!a||!Ra(i,a)?!1:!W(r,i)}function Ia(e){let t=y(e.type??``);return t.includes(`scrollview`)||t.includes(`scrollarea`)||t.includes(`listview`)||t.includes(`recyclerview`)||t.includes(`collectionview`)||t===`list`||t===`table`||t===`collection`}function La(e,t){let n=s(t),r=e.filter(v).map(e=>U(e.rect)).filter(e=>e!==null);if(r.length===0)return null;let i=r.filter(e=>de(e,n.x,n.y));return le(i.length>0?i:r)}function Ra(e,t){let n=ee(e,t),r=e.width*e.height,i=t.width*t.height;if(n<=0||r<=0||i<=0)return!1;let a=n/i,o=n/r;return a>=.9&&o>=.8}function za(e){return e.hittable===!0||Na(e)}function Ba(e,t){let n=ye(b(e),t);return n.id!==void 0||n.label!==void 0?!1:ce(e.value)===null}function Va(e,t,n){let r=new Set,i=e;for(;typeof i.parentIndex==`number`;){if(r.has(i.index))return!1;if(r.add(i.index),i.parentIndex===t.index)return!0;let e=n.get(i.parentIndex);if(!e)return!1;i=e}return!1}function Ha(e,t){let n=Qi(t);return t.filter(t=>t.index!==e.index&&Va(t,e,n)).sort((e,t)=>e.index-t.index)}function Ua(e,t){let n=H(e.rect);return!n||!t.rect?!1:de(t.rect,n.x,n.y)}function Wa(e,t){if(!Ba(e,t))return e;let n=Ha(e,t);if(n.some(za))return e;let r=n.find(e=>b(e).label!==void 0);return!r||!Ua(r,e)?e:r}const Ga=new Set([`healthy`,`recovered`,`sparse`]),Ka=new Set([`tree`,`queries`,`private-ax`]),qa=new Set([`ax-rejected`,`sparse-tree`,`budget`,`no-nodes`,`capture-failed`,`deferred`,`requested-backend`]);function Ja(e){if(!e||typeof e!=`object`)return;let t=e;if(!(typeof t.state!=`string`||!Ga.has(t.state))&&!(typeof t.backend!=`string`||!Ka.has(t.backend)))return{state:t.state,backend:t.backend,reason:typeof t.reason==`string`?t.reason:void 0,reasonCode:typeof t.reasonCode==`string`&&qa.has(t.reasonCode)?t.reasonCode:void 0,customActions:Ya(t.customActions),effectiveDepth:typeof t.effectiveDepth==`number`?t.effectiveDepth:void 0,collapsedLeafIndexes:Array.isArray(t.collapsedLeafIndexes)?t.collapsedLeafIndexes.filter(e=>typeof e==`number`):void 0}}function Ya(e){if(!e||typeof e!=`object`)return;let t=e;if(!(typeof t.read!=`number`||typeof t.candidates!=`number`))return{read:t.read,candidates:t.candidates,truncated:typeof t.truncated==`number`?t.truncated:0,blocked:t.blocked===!0}}function Xa(e){return e?.state===`sparse`}function Za(e,t){return[...eo(e),...Qa(e),...to(e),...no(e,t)]}function Qa(e){let t=e.customActions;if(!t)return[];let n=[];return t.blocked?n.push(`Custom actions were not read: an earlier accessibility read is still hung, so this capture skipped the read pass instead of queueing behind it. No element’s actions list is authoritative here. Reads resume once that call returns.`):t.read<t.candidates&&n.push(`Custom actions were read for ${t.read} of ${t.candidates} merged elements, on-screen ones first; the remaining ${t.candidates-t.read} were not read, so an absent actions list on those is not evidence that they have none. Scroll them into view and re-run to read them.`),t.truncated>0&&n.push(`${t.truncated} element(s) published more custom actions than are shown; those lists are clipped to the first 8 names, and long names are shortened.`),n}function $a(e){return`Detected an overly complex or slow accessibility tree. Fell back to the ${e} snapshot backend. It is OK to continue; use --json to inspect snapshotQuality.reason if you need recovery details.`}function eo(e){return e.state===`recovered`?e.reasonCode===`deferred`||e.reasonCode===`requested-backend`?[]:[$a(e.backend)]:e.state===`sparse`?[`No snapshot backend could read this screen`+(e.reason?` (${e.reason})`:``)+`. Its refs and selectors are invalid. Use screenshot as visual truth and coordinate taps; retry snapshot after navigating.`]:[]}function to(e){return e.effectiveDepth===void 0?[]:[`Some deeper accessibility nodes were omitted; this tree is capped at depth ${e.effectiveDepth}. Re-run with --depth ${e.effectiveDepth} --scope <container> only if you need deeper content.`]}function no(e,t){let n=[];for(let r of e.collapsedLeafIndexes??[]){let e=t.find(e=>e.index===r);if(!e)continue;let i=e.identifier?` (${e.identifier})`:``;n.push(`@${e.ref} [${e.type??`element`}]${i} merges many labels into a single accessibility element. The app likely marks a container as accessible, which hides every descendant from assistive tech and automation — the children cannot be addressed individually. Fix the app's accessibility (mark the rows, not the container); until then use screenshot as visual truth and coordinate taps.`)}return n}const ro=new Set([`empty-helper-output`,`system-window-only`,`content-poor-app-window`]);function io(e){if(!e||typeof e!=`object`)return!1;let t=e.details?.androidSnapshotHelperFailureReason;return typeof t==`string`&&ro.has(t)}function ao(e){return e===`text`||e===`label`||e===`any`}function oo(e,t,n,r){if(!(r||e===`web`))return ao(t)?n:void 0}function so(e){return new n(`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.`})}async function co(e,t){let r=t??`default`,i=await e.sessions.get(r);if(!i)throw new n(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let a=i.refFrameSnapshot??i.snapshot;if(!a)throw new n(`INVALID_ARGS`,`No snapshot in session. Run snapshot first.`);return{sessionName:r,session:i,snapshot:a}}async function lo(e,t,r={updateSession:!0}){let i=e.backend.captureSnapshot;if(!i)throw new n(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let a=t.session??`default`,o=await e.sessions.get(a),s=await i(R(e,t),{interactiveOnly:r.interactiveOnly??!1,depth:t.depth,scope:r.scope??t.scope,raw:t.raw,includeRects:r.includeRects,...r.includeHiddenContentHints===void 0?{}:{includeHiddenContentHints:r.includeHiddenContentHints}}),c=s.snapshot??{nodes:s.nodes??[],truncated:s.truncated,backend:s.backend,...s.quality?{snapshotQuality:s.quality}:{},createdAt:z(e)};return(t.signal??e.signal)?.throwIfAborted(),r.updateSession&&o&&!Xa(c.snapshotQuality)&&await e.sessions.set({...o,snapshot:c}),{sessionName:a,session:o,snapshot:c}}async function uo(e,t,n){if(e.backend.readText){let r=await e.backend.readText(R(e,{session:t.sessionName}),n);if(r.text.trim())return r.text}return Be(n)}function fo(e,t,i){let a=o(t);if(!a)throw new n(`INVALID_ARGS`,i.invalidRefMessage);let s=r(e,a)??(i.fallbackLabel.length>0?ta(e,i.fallbackLabel):null);if(!s)throw new n(`COMMAND_FAILED`,i.notFoundMessage);return{ref:a,node:s}}function po(e,t){if(Buffer.byteLength(e,`utf8`)<=t)return e;let n=Buffer.byteLength(`…`,`utf8`),r=Math.max(0,t-n),i=Buffer.from(e,`utf8`),a=Math.min(r,i.length);for(;a>0&&(i[a]&192)==128;)--a;return i.subarray(0,a).toString(`utf8`)+`…`}function mo(e,t,n={}){let r=U(t.rect),i=H(r??void 0);if(!r||!i)return{kind:`invalid`};let a=ho(e,t,r);if(a.length===0)return{kind:`resolved`,point:i,strategy:`center`};let o=(n.bounds??[]).reduce((e,t)=>e?_o(e,t):null,r),s=o?vo(r,o,i,a):null;return s?{kind:`resolved`,point:s,strategy:`parent-owned`}:{kind:`blocked`,competitorRefs:a.map(e=>e.ref)}}function ho(e,t,n){let r=new Map(e.map(e=>[e.index,e]));return e.filter(e=>e.index!==t.index).filter(e=>go(e,t,r)).filter(Na).flatMap(e=>{let t=U(e.rect);if(!t||W(t,n))return[];let r=_o(t,n);return r&&r.width>0&&r.height>0?[{ref:e.ref,index:e.index,rect:r}]:[]}).sort((e,t)=>e.index-t.index)}function go(e,t,n){let r=new Set,i=e;for(;typeof i.parentIndex==`number`&&!r.has(i.index);){if(r.add(i.index),i.parentIndex===t.index)return!0;let e=n.get(i.parentIndex);if(!e)return!1;i=e}return!1}function _o(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width),a=Math.min(e.y+e.height,t.y+t.height);return i<=n||a<=r?null:{x:n,y:r,width:i-n,height:a-r}}function vo(e,t,n,r){let i=wo(e),a=So(t.x,t.width,n.x,r.flatMap(({rect:e})=>[e.x,e.x+e.width]),i),o=So(t.y,t.height,n.y,r.flatMap(({rect:e})=>[e.y,e.y+e.height]),i);return a.flatMap(a=>o.flatMap(o=>{let s={x:Math.round(a),y:Math.round(o)};if(!yo(t,s))return[];let c=bo(s,e,n,r,i);return c?[c]:[]})).sort(xo)[0]?.point??null}function yo(e,t){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}function bo(e,t,n,r,i){let a=Co(e,t,r);return a.parentEdge<i||a.competitor<12?null:{point:e,distanceSquared:(e.x-n.x)**2+(e.y-n.y)**2,clearance:Math.min(a.parentEdge,a.competitor)}}function xo(e,t){return e.distanceSquared-t.distanceSquared||t.clearance-e.clearance||e.point.y-t.point.y||e.point.x-t.point.x}function So(e,t,n,r,i){let a=e+i,o=e+t-i;if(a>o)return[];let s=[...new Set([e,e+t,...r])].sort((e,t)=>e-t),c=new Set([n,a,o]);for(let e of r)c.add(e-12),c.add(e+12);for(let e=1;e<s.length;e+=1)c.add((s[e-1]+s[e])/2);return[...c].filter(e=>e>=a&&e<=o).sort((e,t)=>e-t)}function Co(e,t,n){let r=Math.min(e.x-t.x,t.x+t.width-e.x,e.y-t.y,t.y+t.height-e.y),i=1/0;for(let{rect:t}of n){let n=e.x<t.x?t.x-e.x:Math.max(0,e.x-(t.x+t.width)),r=e.y<t.y?t.y-e.y:Math.max(0,e.y-(t.y+t.height));i=Math.min(i,Math.max(n,r))}return{parentEdge:r,competitor:i}}function wo(e){let t=Math.min(e.width,e.height);return Math.max(0,Math.min(12,Math.floor(t/2)-1))}const To=`replay_target_guard_mismatch`,Eo=re.landmarkIdentityMismatch;function Do(e,t,r){let i=ke(e,t,we.act,{platform:r});if(i.kind===`none`)return null;if(i.kind===`resolved`)return i.resolution;let a=Oa(e,i.matchedNodes);if(a.kind===`ambiguous`)throw new n(`AMBIGUOUS_MATCH`,`Selector matched ${a.candidates.length} distinct actionable elements: ${i.selector}`,{selector:i.selector,matches:a.candidates.length,candidates:a.candidates.slice(0,5).map(e=>M(e,0,!1))});return{node:a.node,selector:i.selector,selectorIndex:i.selectorIndex,matches:i.matchedNodes.length,diagnostics:[{selector:i.selector,matches:i.matchedNodes.length}],disambiguation:{matchCount:i.matchedNodes.length,tiebreak:`structural-equivalence`,alternatives:i.matchedNodes.filter(e=>e.index!==a.node.index)}}}function Oo(e,t,r,i,a){if(!r)return;let o=b(e),s=fe(e,t);if(!(me(o,r.identity)&&he(s,r.structural)))throw new n(`COMMAND_FAILED`,`${i} resolved to a different element than replay verification isolated; the action was not sent`,{reason:To,observed:o,observedStructural:s,expected:r.identity,expectedStructural:r.structural,...a?{targetRole:a}:{}})}async function X(e,t,n){return await Zo(e,t,n.action),t.target.kind===`point`?await Ao(e,t,t.target,n):t.target.kind===`ref`?await Po(e,t,t.target,n):await Fo(e,t,t.target,n)}async function ko(e,t,n){let r=t.session??`default`,i=await e.sessions.get(r);if(!i?.snapshot)return;let a={x:n.x,y:n.y,width:0,height:0},o=Te(i.snapshot.nodes,a);if(!o)return;let s={x:n.x,y:n.y};if(!de(o,s.x,s.y))return`Coordinates (${s.x}, ${s.y}) are outside the last-known viewport (${o.width}x${o.height}). The tap will be forwarded anyway; take a fresh snapshot if the screen changed.`}async function Ao(e,t,n,r){let i=await ko(e,t,n);if(!r.captureEvidenceBaseline)return{kind:`point`,point:{x:n.x,y:n.y},...i?{warning:i}:{}};let a=await jo(e,t);return{kind:`point`,point:{x:n.x,y:n.y},...a?{preActionNodes:a}:{},...i?{warning:i}:{}}}async function jo(e,t){try{return(await Z(e,t,!0)).snapshot.nodes}catch{return}}function Mo(e,t){let r=o(e.ref);if(!r)throw new n(`INVALID_ARGS`,`Invalid ref: ${e.ref}`);let i=o(t.ref),a=t.node.ref?o(t.node.ref):null;if(i!==r||a!==r||!t.nodes.includes(t.node))throw new n(`COMMAND_FAILED`,`Internal find target provenance does not match the interaction ref`);return{nodes:t.nodes,resolved:zo(r,t.node,`exact`)}}async function No(e,t,n){let r=await $o(e,t,n);return{nodes:r.snapshot.nodes,resolved:r.resolved}}async function Po(e,t,n,r){let{nodes:i,resolved:a}=r.preresolvedTarget?Mo(n,r.preresolvedTarget):await No(e,t,n);Io(a.node,i,r);let s=r.promoteToHittableAncestor?qo(i,a.node,{action:r.action,label:`Ref ${n.ref}`}):a.node;Jo(s,`Ref ${n.ref}`,r.action);let c=await as(e,t,s,i,n.ref,r.action);return{kind:`ref`,point:ns(c,i,{invalidMessage:`Ref ${n.ref} not found or has invalid bounds`,blockedTargetLabel:`Ref ${n.ref}`,blockedTargetDetails:{ref:`@${o(n.ref)??c.ref}`}}),target:{kind:`ref`,ref:`@${a.ref}`},...Uo(e,c,i,r.action,a.resolution)}}async function Fo(e,t,r,i){let a=r.selector,o=await Z(e,t,i.requireInteractive),s=Do(Ko(o.snapshot.nodes),a,e.backend.platform);if((!s||!s.node.rect)&&i.requireInteractive&&(o=await Z(e,t,!1),s=Do(Ko(o.snapshot.nodes),a,e.backend.platform)),!s||!s.node.rect){let t=be(o.snapshot.nodes,a,{platform:e.backend.platform,...Se(we.actCoveredDiagnosis)});throw t?.node&&q(t.node)?Yo({label:`Selector ${t.selector}`,node:t.node,action:i.action,selector:t.selector}):new n(`COMMAND_FAILED`,Me(a,s?.diagnostics??[],{unique:!0}),{hint:je(s?.diagnostics??[])})}Io(s.node,o.snapshot.nodes,i);let c=i.promoteToHittableAncestor?qo(o.snapshot.nodes,s.node,{action:i.action,label:`Selector ${s.selector}`}):s.node;Jo(c,`Selector ${s.selector}`,i.action);let l=await is(e,t,c,o.snapshot.nodes,s.selector,i.action);return{kind:`selector`,point:ns(l,o.snapshot.nodes,{invalidMessage:`Selector ${s.selector} resolved to invalid bounds`,blockedTargetLabel:`Selector ${a}`,blockedTargetDetails:{selector:a}}),target:{kind:`selector`,selector:s.selector},...Uo(e,l,o.snapshot.nodes,i.action,Vo(s,o.snapshot.nodes))}}function Io(e,t,n){Oo(e,t,n.expectedResolvedTarget,n.action,n.replayTargetRole)}const Lo={source:`ref`,phase:`pre-action`,kind:`exact`},Ro={source:`ref`,phase:`pre-action`,kind:`label-fallback`};function zo(e,t,n){return{ref:e,node:t,resolution:n===`exact`?Lo:Ro}}const Bo={source:`runtime`,phase:`pre-action`,kind:`unique`};function Vo(e,t){return e.disambiguation?{source:`runtime`,phase:`pre-action`,kind:`disambiguated`,matchCount:e.disambiguation.matchCount,winnerDiagnostic:Ho(e.node,t),tiebreak:e.disambiguation.tiebreak,alternatives:e.disambiguation.alternatives.slice(0,5).map(e=>Ho(e,t))}:Bo}function Ho(e,t){let n=y(e.type??``),r=G(e,t);return{diagnosticRef:`diag-${e.ref}`,...n?{role:po(n,256)}:{},...r===void 0?{}:{label:po(r,256)}}}function Uo(e,t,n,r,i){return{node:t,selectorChain:ve(t,e.backend.platform,{action:r===`fill`?`fill`:`click`,nodes:n}),refLabel:G(t,n),...Go(t,r),preActionNodes:n,resolution:i,...Wo(e,t,n,r)}}function Wo(e,t,n,r){if(r!==`click`&&r!==`press`)return{};let i=Wa(t,n);return i===t?{}:{recordingTarget:{node:i,selectorChain:ve(i,e.backend.platform,{action:`click`,nodes:n}),refLabel:G(i,n)}}}function Go(e,t){return e.hittable===!1?{targetHittable:!1,hint:`The resolved element reports hittable: false, so this ${t} may have had no visible effect. Verify with a snapshot, or prefer a @ref or a longer/more specific selector to target the intended element.`}:{}}function Ko(e){return e.filter(e=>!q(e))}function qo(e,t,n){let r=Y(e,t);if(r.reason===`covered`)throw Yo({label:n.label,node:t,action:n.action});return r.node}function Jo(e,t,n){if(q(e))throw Yo({label:t,node:e,action:n})}function Yo(e){return new n(`COMMAND_FAILED`,`${e.label} is covered by another visible element and cannot ${Xo(e.action)} safely`,{hint:`Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.`,...e.selector?{selector:e.selector}:{},ref:`@${e.node.ref}`,interactionBlocked:e.node.interactionBlocked})}function Xo(e){switch(e){case`fill`:return`be filled`;case`focus`:return`be focused`;case`longPress`:return`be long-pressed`;default:return`be tapped`}}async function Z(e,t,r){if(!e.backend.captureSnapshot)throw new n(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let i=t.session??`default`,a=await e.sessions.get(i);if(!a)throw new n(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let o=await e.backend.captureSnapshot(R(e,t),{interactiveOnly:r,includeRects:!0}),s=o.snapshot??{nodes:o.nodes??[],truncated:o.truncated,backend:o.backend,createdAt:z(e)};return await e.sessions.set({...a,snapshot:s}),{snapshot:s}}async function Zo(e,t,r){if(e.backend.platform!==`macos`)return;let i=await Qo(e,t);if(!(i!==`desktop`&&i!==`menubar`)&&!(i===`menubar`&&(r===`click`||r===`press`)))throw new n(`UNSUPPORTED_OPERATION`,`${r} is not supported on macOS ${i} sessions yet. Open an app session to act, or use the ${i} surface to inspect.`)}async function Qo(e,t){return(await e.sessions.get(t.session??`default`))?.metadata?.surface}async function $o(e,t,r){let{session:i,snapshot:a}=await co(e,t.session),o=r.fallbackLabel??``,s=ts(a.nodes,r.ref,{fallbackLabel:o});if(!s)throw new n(`COMMAND_FAILED`,`Ref ${r.ref} not found or has no bounds`,{hint:ie});return es({session:i,frameTree:a,target:r,fallbackLabel:o,authorized:s})}function es(e){let{session:t,frameTree:n,target:r,fallbackLabel:i,authorized:a}=e,o=t.snapshot;if(!o||o===n)return{snapshot:n,resolved:a};let s=ts(o.nodes,r.ref,{fallbackLabel:i});return s&&me(b(a.node),b(s.node))?{snapshot:o,resolved:s}:{snapshot:n,resolved:a}}function ts(e,t,i){let a=o(t);if(!a)throw new n(`INVALID_ARGS`,`Invalid ref: ${t}`);let s=r(e,a);if(rs(s))return zo(a,s,`exact`);let c=i.fallbackLabel.length>0?ta(e,i.fallbackLabel):null;return rs(c)?zo(a,c,`label-fallback`):null}function ns(e,t,r){let i=mo(t,e,{bounds:[pe(e,t),e.rect?Te(t,e.rect):null].filter(e=>e!==null)});if(i.kind===`resolved`)return i.point;throw i.kind===`invalid`?new n(`COMMAND_FAILED`,r.invalidMessage):new n(`COMMAND_FAILED`,`${r.blockedTargetLabel} has no parent-owned touch point outside its interactive descendants`,{reason:`covered_by_interactive_descendants`,...r.blockedTargetDetails,competitorRefs:i.competitorRefs.slice(0,5).map(e=>`@${e}`),competitorCount:i.competitorRefs.length,hint:`Tap the specific interactive child you intend, or use a more specific selector. Every safely tappable region of the parent belongs to one of its child controls.`})}function rs(e){return e?H(e.rect)!==null:!1}async function is(e,t,n,r,i,a){return await cs(e,t,n,r,{message:`Selector ${i} resolved to an off-screen element and is not safe to ${a}`,details:{reason:`offscreen_selector`,selector:i},hint:e=>`${os(e)} in small steps, retrying ${a} with the same selector after each (it re-resolves against a fresh snapshot). A single large scroll can overshoot the target; a short bounded gesture pan lands it more reliably. If it is inside a closed drawer or another tab, open that container first.`})}async function as(e,t,n,r,i,a){return await cs(e,t,n,r,{message:`Ref ${i} is off-screen and not safe to ${a}`,details:{reason:`offscreen_ref`,ref:o(i)},hint:e=>`${os(e)} in small steps (a single large scroll can overshoot; a short bounded gesture pan lands it more reliably), then retry ${a} with a selector (e.g. text=/id=) rather than this @ref — the scroll expires the ref frame, so re-run snapshot -i before reusing any @ref.`})}function os(e){return e?`Scroll ${e} toward it`:`Scroll toward it`}async function ss(e,t,n,r){let i=(await e.sessions.get(t.session??`default`))?.snapshot?.nodes;if(!i||o(n.ref)===null)return{};let a=ts(i,n.ref,{fallbackLabel:n.fallbackLabel??``});if(!a)return{};Jo(a.node,`Ref ${n.ref}`,r);let s=await as(e,t,a.node,i,n.ref,r);return{...Go(s,r),node:s,preActionNodes:i}}async function cs(e,t,r,i,a){let o=r.rect?pe(r,i):null;if(!r.rect||!o||Pe(r,i))return r;let s=Te(i,r.rect),c=await e.backend.confirmOffscreenTargetVisible?.(R(e,t),r,s);if(c)return{...r,rect:c};let l=_(r,i);throw new n(`COMMAND_FAILED`,a.message,{...a.details,rect:r.rect,viewport:o,...l?{scrollDirection:l}:{},hint:a.hint(l)})}function ls(e,t){let n=P(e.type??`Element`),r=N(e,n),i=e.enabled===!1?`disabled`:`enabled`,a=e.selected===!0?`selected`:`unselected`,o=e.hittable===!0?`hittable`:`not-hittable`;return[String(t??e.depth??0),n,r,i,a,o,e.actions?JSON.stringify(e.actions):``].join(`|`)}function us(e,t,n={}){let r=ps(fs(e,n),fs(t,n)),i={additions:0,removals:0,unchanged:0};for(let e of r)e.kind===`added`&&(i.additions+=1),e.kind===`removed`&&(i.removals+=1),e.kind===`unchanged`&&(i.unchanged+=1);return{summary:i,lines:r}}function ds(e,t={}){return fs(e,t).length}function fs(e,t){return t.flatten?e.map(e=>({text:M(e,0,!1),comparable:ls(e,0),...t.withRefs&&e.ref?{ref:e.ref}:{}})):Ar(e).map(e=>({text:e.text,comparable:ls(e.node,e.depth),...t.withRefs&&e.node.ref?{ref:e.node.ref}:{}}))}function ps(e,t){let n=e.length,r=t.length,i=n+r,a=new Map,o=[];a.set(1,0);for(let s=0;s<=i;s+=1){o.push(new Map(a));for(let i=-s;i<=s;i+=2){let c=hs(a,i,s)?Q(a,i+1):Q(a,i-1)+1,l=c-i;for(;c<n&&l<r&&e[c].comparable===t[l].comparable;)c+=1,l+=1;if(a.set(i,c),c>=n&&l>=r)return ms(o,e,t,n,r)}}return[]}function ms(e,t,n,r,i){let a=[],o=r,s=i;for(let r=e.length-1;r>=0;--r){let i=e[r],c=o-s,l=hs(i,c,r)?c+1:c-1,u=Q(i,l),d=u-l;for(;o>u&&s>d;)a.push({kind:`unchanged`,text:n[s-1].text}),--o,--s;if(r===0)break;if(o===u){let e=n[d];a.push({kind:`added`,text:e.text,...e.ref?{ref:e.ref}:{}}),s=d}else a.push({kind:`removed`,text:t[u].text}),o=u}return a.reverse(),a}function hs(e,t,n){return t===-n||t!==n&&Q(e,t-1)<Q(e,t+1)}function Q(e,t){return e.get(t)??0}function gs(e){return e?ge({packageName:e.bundleId,resourceId:e.identifier}).inputMethodOwned:!1}const _s=new Set([`textfield`,`securetextfield`,`textview`,`textarea`,`searchfield`,`edittext`]),vs={strippedIndexes:new Set,refs:new Set};function ys(e){let t=new Set(e.filter(e=>y(e.type??``)===`keyboard`).map(e=>e.index));if(t.size===0)return vs;let n=new Map(e.map(e=>[e.index,e])),r=ws(e,n,t),i=new Set(r),a=Ms(e,n,r);for(let t of ws(e,n,a))i.add(t);for(let o of bs(e,n,a,t,r))i.delete(o);let o=new Set(e.filter(e=>e.ref&&i.has(e.index)).map(e=>e.ref));return{strippedIndexes:new Set([...i].filter(e=>!t.has(e))),refs:o}}function bs(e,t,n,r,i){let a=new Set;if(n.size===0)return a;let o=Ss(t,n,r);if(o.size===0)return a;let s=Cs(t,r);for(let n of e)!i.has(n.index)&&!s.has(n.index)&&n.rect&&xs(n,t,o)&&a.add(n.index);return a}function xs(e,t,n){if(!e.rect)return!1;let r=Ns(e,t);if(r===void 0)return!1;let i=n.get(r);return i!==void 0&&e.rect.y+e.rect.height/2<i}function Ss(e,t,n){let r=new Map;for(let i of n){let n=e.get(i);if(!n?.rect)continue;let a=Ns(n,e);if(a===void 0||!t.has(a))continue;let o=r.get(a);(o===void 0||n.rect.y<o)&&r.set(a,n.rect.y)}return r}function Cs(e,t){let n=new Set;for(let r of t){let t=e.get(r),i=t&&typeof t.parentIndex==`number`?e.get(t.parentIndex):void 0;for(;i;)n.add(i.index),i=typeof i.parentIndex==`number`?e.get(i.parentIndex):void 0}return n}function ws(e,t,n){let r=new Set(n);if(n.size===0)return r;for(let i of e)Ps(i,t,n)&&r.add(i.index);return r}function Ts(e,t){if(e.bundleId!==`com.android.systemui`)return!1;if(Ae(e))return!0;let n=new Set,r=e;for(;r?.bundleId===`com.android.systemui`&&!n.has(r.index);){if(ue(r.identifier))return!0;n.add(r.index),r=r.parentIndex===void 0?void 0:t.get(r.parentIndex)}return!1}function Es(e,t){let n=new Map(e.map(e=>[e.index,e])),r=new Set(e.filter(e=>gs(e)).map(e=>e.index)),i=new Set([...r].filter(e=>{let t=n.get(e)?.parentIndex,i=t===void 0?void 0:n.get(t);return!i||!r.has(i.index)})),a=t===`com.android.systemui`?new Set:Ds(e,n,r),o=new Set([...r].filter(e=>!i.has(e)));for(let e of a)o.add(e);let s=new Set(e.filter(e=>e.ref&&(r.has(e.index)||a.has(e.index))).map(e=>e.ref));return o.size===0&&s.size===0?vs:{strippedIndexes:o,refs:s}}function Ds(e,t,n){return new Set(e.filter(e=>!n.has(e.index)&&Ts(e,t)).map(e=>e.index))}function Os(e,t){let n=ys(e),r=Es(e,t);return n.strippedIndexes.size===0&&n.refs.size===0?r:r.strippedIndexes.size===0&&r.refs.size===0?n:{strippedIndexes:new Set([...n.strippedIndexes,...r.strippedIndexes]),refs:new Set([...n.refs,...r.refs])}}function ks(e,t){let{strippedIndexes:n}=Os(e,t);return n.size===0?e:e.filter(e=>!n.has(e.index))}function As(e,t){return Os(e,t).refs}function js(e){return ys(e).refs}function Ms(e,t,n){let r=new Set;for(let e of n){let n=t.get(e);if(!n||y(n.type??``)!==`keyboard`)continue;let i=Ns(n,t);i!==void 0&&r.add(i)}for(let i of r){let a=new Set([i]);e.some(e=>_s.has(y(e.type??``))&&!n.has(e.index)&&Ps(e,t,a))&&r.delete(i)}return r}function Ns(e,t){let n=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0;for(;n;){if(y(n.type??``)===`window`)return n.index;n=typeof n.parentIndex==`number`?t.get(n.parentIndex):void 0}}function Ps(e,t,n){let r=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0;for(;r;){if(n.has(r.index))return!0;r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}return!1}async function Fs(e,t,n,r){let i=new AbortController,a=[t.signal,e.signal].filter(e=>e!==void 0),o=AbortSignal.any([...a,i.signal]),s=!1,c=setTimeout(()=>{s=!0,i.abort(new DOMException(`Wait deadline exceeded`,`TimeoutError`))},Math.max(0,n));c.unref();try{let e=await r(o);return s&&!a.some(e=>e.aborted)?{timedOut:!0}:(o.throwIfAborted(),{timedOut:!1,value:e})}catch(e){if(s&&!a.some(e=>e.aborted))return{timedOut:!0};throw e}finally{clearTimeout(c)}}const Is=`Settled on a nearly-empty tree — the app may still be loading. Wait for specific content (wait text ...) before interacting.`;async function Ls(e,t,n){let{quietMs:r,timeoutMs:i}=n,a=z(e),o=a+i,s=!1,c=Math.min(300,Math.max(25,r)),l=0,u,d=0,f,p=a;for(;z(e)<o;){let m=await Bs(e,t,o-z(e));if(!m)return{settled:!1,stalled:!0,waitedMs:z(e)-a,captures:l,nodeCount:d,lastCapture:f};l+=1,f=m;let h=Vs(m.snapshot.nodes),g=z(e);if(n.resetBudgetOnPrivateAxRecovery===!0&&!s&&Rs(m.snapshot.snapshotQuality)){s=!0,o=Math.max(o,g+i),p=g,u=h,d=m.snapshot.nodes.length;let t=zs({nowMs:g,quietSinceMs:p,quietMs:r,pollMs:c,deadlineMs:o});if(t<=0)break;await Ui(e,t);continue}if(h!==u)u=h,d=m.snapshot.nodes.length,p=g;else if(l>=2&&g-p>=r)return{settled:!0,stalled:!1,waitedMs:g-a,captures:l,nodeCount:d,lastCapture:f};let _=zs({nowMs:g,quietSinceMs:p,quietMs:r,pollMs:c,deadlineMs:o});if(_<=0)break;await Ui(e,_)}return{settled:!1,stalled:!1,waitedMs:z(e)-a,captures:l,nodeCount:d,lastCapture:f}}function Rs(e){return e?.state===`recovered`&&e.backend===`private-ax`&&e.reasonCode!==`deferred`}function zs(e){let t=e.quietSinceMs+e.quietMs-e.nowMs,n=t>e.pollMs?e.pollMs:Math.max(25,t+2),r=e.deadlineMs-e.nowMs,i=r-1;return i<2?r>=2?r:0:Math.min(n,i)}async function Bs(e,t,n){let r=await Fs(e,t,n,async n=>await lo(e,{...t,signal:n},{updateSession:!1,interactiveOnly:!0}));return r.timedOut?void 0:r.value}function Vs(e){return e.map(Hs).join(`|`)}function Hs(e){let t=e.rect?`${Math.round(e.rect.x)},${Math.round(e.rect.y)},${Math.round(e.rect.width)},${Math.round(e.rect.height)}`:``;return`${e.type??``}#${e.label??``}#${e.identifier??``}#${t}`}const Us=`The UI kept changing for the whole settle budget (animation, carousel, or ticker?), so no settled diff is shown. Raise --timeout, wait for specific content, or take a fresh snapshot.`,Ws=`A snapshot capture stalled past the settle budget, so no settled diff is shown. The action itself succeeded; observe with wait stable or snapshot.`;async function Gs(e,t,n){return await qs(e,t,{...n,baselineNodes:Xs(n.resolved),actionPoint:n.resolved.point})}const Ks=async(e,t)=>(await qs(e,t,t)).observation;async function qs(e,t,n){let r=n.quietMs??500,i=n.timeoutMs??1e4,a={settled:!1,waitedMs:0,captures:0,quietMs:r,timeoutMs:i};try{return await Js(e,t,n,a,await Ls(e,t,{quietMs:r,timeoutMs:i,resetBudgetOnPrivateAxRecovery:!0}))}catch(e){return{observation:{...a,hint:`Settle observation unavailable (${e instanceof Error?e.message:String(e)}). The action itself succeeded; take a snapshot to observe the result.`}}}}async function Js(e,t,n,r,i){let a={...r,settled:i.settled,waitedMs:i.waitedMs,captures:i.captures};if(!i.lastCapture)return{observation:{...a,hint:i.stalled?Ws:Us}};let{stored:o,session:s}=await ac(e,t,i.lastCapture),c=i.lastCapture.snapshot.nodes;return{observation:{...a,...i.settled&&o?Qs(n.baselineNodes,c,n.actionPoint,s?.appBundleId):{},...ic(i,o,c.length)},settledNodes:c}}function Ys(e,t){if(!e)return;let n=V(e),r=t!==void 0&&n.digest!==V(t).digest;return{...n,changedFromBefore:r}}function Xs(e){return`preActionNodes`in e&&e.preActionNodes?e.preActionNodes:[]}function Zs(e,t,n){let r=us(ks(e,n),ks(t,n),{flatten:!0,withRefs:!0}),i=r.lines.filter(e=>e.kind!==`unchanged`),a=rc(i).map(e=>({kind:e.kind,text:e.text,...e.ref?{ref:e.ref}:{}}));return{summary:r.summary,lines:a,...i.length>a.length?{truncated:!0}:{}}}function Qs(e,t,n,r){let i=Zs(e,t,r);return{diff:i,...$s(i,t,n,r)}}function $s(e,t,n,r){let i=new Set(e.lines.filter(e=>e.kind===`added`&&e.ref).map(e=>e.ref)),a=As(t,r),o=new Map(t.filter(e=>e.ref).map(e=>[e.ref,e]));return[...i].some(e=>e!==void 0&&!a.has(e)&&!ec(o.get(e),n))?{}:nc(t,i,r)}function ec(e,t){if(!e?.rect||!t)return!1;let{x:n,y:r,width:i,height:a}=e.rect;return t.x>=n&&t.x<=n+i&&t.y>=r&&t.y<=r+a}const tc=new Set([`application`,`window`]);function nc(e,t,n){let r=As(e,n),i=e.filter(e=>e.ref&&e.interactionBlocked!==`covered`&&!t.has(e.ref)&&!r.has(e.ref)&&!tc.has(P(e.type??`Element`)));if(i.length===0)return{};let a=i.slice(0,20).map(e=>{let t=P(e.type??`Element`),n=N(e,t);return{ref:e.ref,role:t,...n?{label:n}:{}}});return{tail:a,...i.length>a.length?{tailTruncated:!0}:{}}}function rc(e){if(e.length<=80)return e;let t=e.filter(e=>e.kind===`added`),n=new Set(t.slice(0,80)),r=80-n.size,i=[];for(let t of e)n.has(t)?i.push(t):t.kind===`removed`&&r>0&&(i.push(t),--r);return i}function ic(e,t,n){return e.stalled?{hint:Ws}:e.settled?t?n<5?{hint:Is}:{}:{hint:`Settled on a sparse, unreadable tree — the diff is omitted and its refs/selectors are invalid. Use screenshot as visual truth and coordinate taps; retry snapshot after navigating.`}:{hint:Us}}async function ac(e,t,n){if(Xa(n.snapshot.snapshotQuality))return{stored:!1};let r=await e.sessions.get(t.session??`default`);return r?(await e.sessions.set({...r,snapshot:n.snapshot}),{stored:!0,session:r}):{stored:!1}}function oc(e){let t=e.verify===!0;return{verify:t,needsPreActionBaseline:t||e.settle!==void 0,...e.settle===void 0?{}:{settle:e.settle}}}async function sc(e,t,n,r,i){let a=await cc(e,t,n,i);return uc({...r,...a})}async function cc(e,t,n,r){if(r.settle!==void 0){let i=await Gs(e,t,{...r.settle,resolved:n}),a=r.verify?Ys(i.settledNodes,`preActionNodes`in n?n.preActionNodes:void 0):void 0;return{settle:i.observation,...a?{evidence:a}:{}}}if(!r.verify)return{};let i=await lc(e,t,n);return i?{evidence:i}:{}}async function lc(e,t,n){let r=`preActionNodes`in n?n.preActionNodes:void 0;try{let n=V((await Z(e,t,!0)).snapshot.nodes),i=r!==void 0&&n.digest!==V(r).digest;return{...n,changedFromBefore:i}}catch{return}}function uc(e){let t=e;if(t.targetHittable!==!1||!dc(t)||t.hint===void 0)return e;let{hint:n,...r}=t;return r}function dc(e){if(e.evidence?.changedFromBefore===!0)return!0;let t=e.settle?.diff?.summary;return!!t&&(t.additions>0||t.removals>0)}function fc(e,t){let r=e.filter(t=>se(t,e)).map(e=>e.rect).filter(pc),i=r.length>0?r:e.map(e=>e.rect).filter(pc);if(i.length===0)throw new n(`COMMAND_FAILED`,`Cannot infer viewport for ${t}`);let a=Math.min(...i.map(e=>e.x)),o=Math.min(...i.map(e=>e.y)),s=Math.max(...i.map(e=>e.x+e.width)),c=Math.max(...i.map(e=>e.y+e.height));return{x:a,y:o,width:s-a,height:c-o}}function pc(e){return!!(e&&e.width>0&&e.height>0)}async function mc(e,t){return await e.backend.resolveGestureViewport?.(R(e,t))||fc((await Z(e,t,!1)).snapshot.nodes,`gesture`)}const hc=async(e,t)=>{let r=await X(e,t,{action:`focus`,requireInteractive:!0,promoteToHittableAncestor:!1});if(!e.backend.focus)throw new n(`UNSUPPORTED_OPERATION`,`focus is not supported by this backend`);let i=$(r),a=B(await e.backend.focus(R(e,t),i));return{...r,...a?{backendResult:a}:{},...C(`Focused (${i.x}, ${i.y})`)}},gc=async(e,t)=>{let r=oc(t),i=await X(e,t,{action:`longPress`,requireInteractive:!0,promoteToHittableAncestor:!0,captureEvidenceBaseline:r.needsPreActionBaseline,expectedResolvedTarget:t.expectedResolvedTarget});if(!e.backend.longPress)throw new n(`UNSUPPORTED_OPERATION`,`longPress is not supported by this backend`);let a=t.durationMs===void 0?void 0:Hi(t.durationMs,`durationMs`,0,12e4),o=$(i),s=B(await e.backend.longPress(R(e,t),o,{durationMs:a}));return await sc(e,t,i,{...i,...a===void 0?{}:{durationMs:a},...s?{backendResult:s}:{},...C(`Long pressed (${o.x}, ${o.y})`)},r)},_c=async(e,t)=>{if(!e.backend.performGesture)throw new n(`UNSUPPORTED_OPERATION`,`gesture is not supported by this backend`);await Zo(e,t,`drag`);let r=await mc(e,t),i=await vc(e,t,`source`),a=await vc(e,t,`destination`),o=u({from:$(i),to:$(a),sourceHoldMs:t.gesture.sourceHoldMs,moveMs:t.gesture.moveMs,destinationHoldMs:t.gesture.destinationHoldMs},r),s=B(await e.backend.performGesture(R(e,t),o)),{start:c,end:d}=l(o);return{kind:`drag`,durationMs:o.durationMs,pointerCount:1,from:c,to:d,targets:{source:yc(i),destination:yc(a)},recording:bc(i,a),...s?{backendResult:s}:{},...C(`Dragged ${t.gesture.source} to ${t.gesture.destination}`)}};async function vc(e,t,n){let r=t.gesture[n];return await X(e,{...t,target:r.startsWith(`@`)?{kind:`ref`,ref:r}:{kind:`selector`,selector:r}},{action:`drag`,requireInteractive:!1,promoteToHittableAncestor:!1,expectedResolvedTarget:t.expectedResolvedTargets?.[n],replayTargetRole:n})}function yc(e){if(e.kind===`point`||!e.resolution)throw new n(`COMMAND_FAILED`,`gesture drag target resolution was not disclosed`);let t=`selectorChain`in e?e.selectorChain:void 0;return{...t?.length?{selectorChain:t}:{},resolution:e.resolution}}function bc(e,t){let n=xc(e),r=xc(t),i=Sc(e),a=Sc(t);return{...n?{sourceSelector:n}:{},...r?{destinationSelector:r}:{},...i?{sourceTarget:i}:{},...a?{destinationTarget:a}:{}}}function xc(e){return`selectorChain`in e&&e.selectorChain?.length?e.selectorChain.join(` || `):void 0}function Sc(e){if(!(!(`selectorChain`in e)||!e.selectorChain?.length||!e.node||!e.preActionNodes))return{selectorChain:e.selectorChain,node:e.node,preActionNodes:e.preActionNodes}}const Cc=async(e,t)=>{if(!e.backend.scroll)throw new n(`UNSUPPORTED_OPERATION`,`scroll is not supported by this backend`);let r=Tc(t.direction),i=kc(t.amount,`scroll amount`),a=jc(t.pixels,`scroll pixels`),o=d(t.durationMs);c({amount:i,pixels:a},`scroll accepts either amount or pixels, not both`);let s=await wc(e,t),l=s.kind===`viewport`?{kind:`viewport`}:{kind:`point`,point:$(s)},u=e.backend.scroll,f=async()=>await u(R(e,t),l,{direction:r.direction,...i===void 0?{}:{amount:i},...a===void 0?{}:{pixels:a},...o===void 0?{}:{durationMs:o}}),p,m=0;if(r.edge){let n=r.edge,i=Ec(s),a=await Oi({edge:n,captureState:async r=>await Dc(e,t,n,i,r),scroll:f});p=a.result,m=a.passes}else p=await f(),m=1;let h=B(p),_=g(h);return{...s,direction:r.direction,...r.edge?{edge:r.edge,passes:m}:{},...i===void 0?{}:{amount:i},...a===void 0?{}:{pixels:a},..._===void 0?{}:{durationMs:_},...h?{backendResult:h}:{},...C(ki(r.direction,r.edge,m,i,a))}};async function wc(e,t){let n=t.target??{kind:`viewport`};return n.kind===`viewport`?(await Zo(e,t,`scroll`),{kind:`viewport`}):await X(e,{...t,target:n},{action:`scroll`,requireInteractive:!1,promoteToHittableAncestor:!1})}function Tc(e){return e===`bottom`?{direction:`down`,edge:`bottom`}:e===`top`?{direction:`up`,edge:`top`}:{direction:Oc(e,`scroll direction`)}}function Ec(e){return e.kind===`viewport`?{}:{point:e.point,nodeIndex:`node`in e?e.node?.index:void 0}}function $(e){if(!e.point)throw new n(`COMMAND_FAILED`,`Interaction target resolved without coordinates`);return e.point}async function Dc(e,t,r,i,a){if(!e.backend.captureSnapshot)throw new n(`UNSUPPORTED_OPERATION`,`scroll ${r} requires snapshot support to verify hidden content before scrolling`);let{captureSnapshot:o}=e.backend;return await Di({edge:r,target:i,scope:a,captureNodes:async n=>{let r=await o(R(e,t),{scope:n});return r.snapshot?.nodes??r.nodes??[]}})}function Oc(e,t){switch(e){case`up`:case`down`:case`left`:case`right`:return e;default:throw new n(`INVALID_ARGS`,`${t} must be up, down, left, or right`)}}function kc(e,t){return e===void 0?void 0:Ac(e,t)}function Ac(e,t){if(!Number.isFinite(e)||e<=0)throw new n(`INVALID_ARGS`,`${t} must be a positive number`);return e}function jc(e,t){if(e!==void 0){if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw new n(`INVALID_ARGS`,`${t} must be a positive integer`);return e}}const Mc=/^e\d+$/;function Nc(e){if(e[0]?.startsWith(`@`)){let t=Hc(e.slice(1));return{ref:e[0],...t===void 0?{}:{label:t}}}if(Mc.test(e[0]??``))throw new n(`INVALID_ARGS`,`Did you mean "@${e[0]}"? Snapshot refs need the @ prefix.`);let t=Ne(e);if(t){if(t.rest.length>0)throw new n(`INVALID_ARGS`,zc(e,t));return{selector:t.selectorExpression}}return Fc(e)}function Pc(e){let t=e[0];if(t?.startsWith(`@`)){let n=e.length>=3?e.slice(2).join(` `):e.slice(1).join(` `);return{kind:`ref`,target:{ref:t,label:e.length>=3?Hc(e.slice(1,2)):void 0},text:n}}if(Mc.test(t??``))throw new n(`INVALID_ARGS`,`Did you mean "@${t}"? Snapshot refs need the @ prefix.`);let r=Ne(e,{preferTrailingValue:!0});return r?{kind:`selector`,target:{selector:r.selectorExpression},text:r.rest.join(` `)}:{kind:`point`,target:Fc(e.slice(0,2)),text:e.slice(2).join(` `)}}function Fc(e){let t=e[0]??``,r=De(t);if(r){let i=Ic(t)?r.value:[r.value,...e.slice(1)].join(` `).trim();throw new n(`INVALID_ARGS`,Lc({key:r.key,value:i}))}let i=Number(e[0]),a=Number(e[1]);if(Number.isFinite(i)&&Number.isFinite(a))return{x:i,y:a};throw new n(`INVALID_ARGS`,Rc(e))}function Ic(e){let t=e.slice(e.indexOf(`=`)+1).trim();if(t.length<2)return!1;let n=t[0];return(n===`"`||n===`'`)&&t.endsWith(n)}function Lc(e){let{key:t,value:n}=e;return`Unknown selector key "${t}". Supported: ${Oe.join(`, `)}. ${Ce(t)?`Did you mean role=${t} label=${Vc(n)}?`:`Did you mean label=${Vc(n)}?`}`}function Rc(e){let t=e.filter(e=>e!==void 0).join(` `);if(!t.trim())return`Missing target. Pass an @ref from snapshot, a selector like text="Sign in", or "x y" coordinates.`;let n=`Target "${t}" is not a @ref, selector, or "x y" point.`;return e.some(e=>xe(e??``))?`${n} Selector values with spaces need quotes, e.g. text="Sign in".`:`${n} To match by visible text, use text=${Vc(t)} (or label=/id=/role=), or pass an @ref from snapshot.`}function zc(e,t){return`${`Selector ${t.selectorExpression} is followed by unexpected extra arguments: "${t.rest.join(` `)}".`} Selector values with spaces need quotes, e.g. ${Bc(e,t)??`text="Sign in"`}.`}function Bc(e,t){let n=e.length-t.rest.length,r=e[n-1];if(r===void 0)return;let i=r.indexOf(`=`);if(i<=0)return;let a=[r.slice(i+1),...t.rest].join(` `),o=`${r.slice(0,i+1)}${Vc(a)}`;return[...e.slice(0,n-1),o].join(` `)}function Vc(e){return`"${e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}"`}function Hc(e){return e.join(` `).trim()||void 0}function Uc(e,t={}){let n=pi(process.stderr);if(e===`pass`){let e=t.passFormat??`green`;return n?Wc(`✓`,e):`✓`}return e===`fail`?n?Wc(`⨯`,`red`):`⨯`:e===`warn`?n?Wc(`!`,`yellow`):`!`:n?Wc(`-`,`dim`):`-`}function Wc(e,t){return I(e,t,{validateStream:!1})}function Gc(e){return`${Uc(qc(e.status))} ${Jc(e)}`}function Kc(e){return e.status!==`fail`&&e.status!==`warn`?[]:typeof e.command==`string`?[` run: ${e.command}`]:typeof e.hint==`string`?[` hint: ${e.hint}`]:[]}function qc(e){return e===`pass`?`pass`:e===`fail`?`fail`:e===`warn`?`warn`:`skip`}function Jc(e){let t=typeof e.id==`string`&&e.id.length>0?e.id:`check`,n=typeof e.summary==`string`&&e.summary.length>0?e.summary:t;return n===t?t:`${t}: ${n}`}let Yc=!1;function Xc(){Yc=!0}function Zc(){let e=Yc;return Yc=!1,e}function Qc(e,t){let r=e===void 0?NaN:Number(e);if(!Number.isInteger(r)||r<1)throw new n(`INVALID_ARGS`,`viewport ${t} must be a positive integer`);return r}const $c=[`auto`,`react-native`,`expo`,`repack`];function el(e){if(e!==void 0){if($c.includes(e))return e;throw new n(`INVALID_ARGS`,`metro prepare --kind must be auto, react-native, expo, or repack`)}}export{$i as $,Et as $t,X as A,Qt as At,io as B,nn as Bt,gs as C,Ze as Cn,M as Ct,Oo as D,et as Dn,nr as Dt,Lo as E,Qe as En,lr as Et,co as F,Wt as Ft,Y as G,zt as Gt,$a as H,sn as Ht,fo as I,tn as It,oa as J,Lt as Jt,ua as K,Rt as Kt,oo as L,$t as Lt,Eo as M,Zt as Mt,lo as N,Vt as Nt,Zo as O,$e as On,Vn as Ot,uo as P,en as Pt,G as Q,Mt as Qt,so as R,Ut as Rt,As as S,qe as Sn,P as St,ds as T,tt as Tn,rr as Tt,Za as U,an as Ut,Ja as V,on as Vt,ja as W,Bt as Wt,ta as X,Ot as Xt,aa as Y,kt as Yt,ra as Z,Nt as Zt,Ks as _,w as _n,Gr as _t,Kc as a,st as an,V as at,Fs as b,nt as bn,pi as bt,Pc as c,_t as cn,z as ct,hc as d,ht as dn,Di as dt,Dt as en,Qi as et,gc as f,gt as fn,ki as ft,oc as g,C as gn,ii as gt,sc as h,at as hn,ai as ht,Xc as i,ot as in,H as it,To as j,Ht as jt,ss as k,Ye as kn,Un as kt,Nc as l,pt as ln,R as lt,Cc as m,vt as mn,I as mt,Qc as n,bt as nn,W as nt,Gc as o,ft as on,Wi as ot,mc as p,ut as pn,Oi as pt,q,Ft as qt,Zc as r,Tt as rn,Xi as rt,Uc as s,mt as sn,B as st,el as t,xt as tn,ea as tt,_c as u,dt as un,Hi as ut,Is as v,Ge as vn,Wr as vt,us as w,Xe as wn,sr as wt,js as x,Je as xn,N as xt,Ls as y,rt as yn,Ur as yt,Xa as z,rn as zt};
|
|
7
|
+
`)}function Kr(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(Math.round(e/100)/10).toFixed(1)}s`;let t=e/6e4;if(t<60)return`${(Math.round(t*10)/10).toFixed(1)}m`;let n=t/60;return`${(Math.round(n*10)/10).toFixed(1)}h`}function qr(e){let t=typeof e.appName==`string`?e.appName:void 0,n=typeof e.appBundleId==`string`?e.appBundleId:void 0,r=[];return t&&r.push(`Page: ${t}`),n&&r.push(`App: ${n}`),r.length>0?`${r.join(`
|
|
8
|
+
`)}\n`:``}function Jr(e,t,n){let r=n?` (truncated)`:``;return t?.partial?t.totalNodeCount>t.visibleNodeCount?`Snapshot: ${t.visibleNodeCount} visible nodes (${t.totalNodeCount} total)${r}`:`Snapshot: ${t.visibleNodeCount} visible nodes${r}`:`Snapshot: ${e} nodes${r}`}function Yr(e){return e.map(e=>JSON.stringify(e)).join(`
|
|
9
|
+
`)}function Xr(e){return bi(e).join(`
|
|
10
|
+
`)}function Zr(e){return _i(Or(e,{summarizeTextSurfaces:!0})).join(`
|
|
11
|
+
`)}function Qr(e){return e&&e.summaryLines.length>0?`\n${e.summaryLines.join(`
|
|
12
|
+
`)}`:``}function $r(e,t,n,r,i=0){let a=ei(e);if(i===0&&a)return a;let o=(t?.hiddenCount??0)+i,s=t?t.nodes.some(e=>e.hiddenContentAbove||e.hiddenContentBelow):!1;return o>0?{partial:!0,visibleNodeCount:n,totalNodeCount:Math.max(r,a?.totalNodeCount??r),reasons:ti([...a?.reasons??[],`offscreen-nodes`])}:a||(s?{partial:!0,visibleNodeCount:n,totalNodeCount:n,reasons:[]}:null)}function ei(e){let t=e.visibility;if(!t||typeof t!=`object`)return null;let n=t;return typeof n.partial!=`boolean`||typeof n.visibleNodeCount!=`number`||typeof n.totalNodeCount!=`number`||!Array.isArray(n.reasons)?null:{partial:n.partial,visibleNodeCount:n.visibleNodeCount,totalNodeCount:n.totalNodeCount,reasons:n.reasons.filter(e=>typeof e==`string`)}}function ti(e){return[...new Set(e)]}function ni(e){let t=e.baselineInitialized===!0,n=e.summary??{},r=F(n.additions),i=F(n.removals),a=F(n.unchanged),o=I(),s=gi(e),c=s.length>0?`${s.join(`
|
|
13
|
+
`)}\n`:``;if(t)return`${c}Baseline initialized (${a} lines).\n`;let l=ui(Array.isArray(e.lines)?e.lines:[],1).map(e=>{let t=typeof e.text==`string`?e.text:``;if(e.kind===`added`){let e=t.startsWith(` `)?`+${t}`:`+ ${t}`;return o?L(e,`green`):e}if(e.kind===`removed`){let e=t.startsWith(` `)?`-${t}`:`- ${t}`;return o?L(e,`red`):e}return o?L(t,`dim`):t}),u=l.length>0?`${l.join(`
|
|
14
|
+
`)}\n`:``;return o?`${c}${u}${[`${L(String(r),`green`)} additions`,`${L(String(i),`red`)} removals`,`${L(String(a),`dim`)} unchanged`].join(`, `)}\n`:`${c}${u}${r} additions, ${i} removals, ${a} unchanged\n`}function ri(e){let t=I(),n=e.match===!0,r=e.dimensionMismatch,i=[];return i.push(...ii(e,t)),i.push(...ai(e,n,t)),!n&&!r&&(i.push(...oi(e,t)),i.push(...si(e,t))),`${i.join(`
|
|
15
|
+
`)}\n`}function ii(e,t){if(e.match===!0)return[`${t?L(`✓`,`green`):`✓`} Screenshots match.`];let n=e.dimensionMismatch,r=t?L(`✗`,`red`):`✗`;if(n){let e=n.expected,t=n.actual;return[`${r} Screenshots have different dimensions: expected ${e?.width}x${e?.height}, got ${t?.width}x${t?.height}`]}let i=F(e.differentPixels),a=F(e.mismatchPercentage),o=`${a===0&&i>0?`<0.01`:String(a)}% pixels differ`;return[`${r} ${t?L(o,`red`):o}`]}function ai(e,t,n){if(t)return[];let r=[];if(e.diffPath){let t=li(e.diffPath),i=n?L(`Diff image:`,`dim`):`Diff image:`,a=n?L(t,`green`):t;r.push(` ${i} ${a}`)}if(e.currentOverlayPath){let t=li(e.currentOverlayPath),i=n?L(`Current overlay:`,`dim`):`Current overlay:`,a=n?L(t,`green`):t,o=F(e.currentOverlayRefCount),s=o>0?` (${o} refs)`:``;r.push(` ${i} ${a}${s}`)}return r}function oi(e,t){let n=F(e.differentPixels),r=F(e.totalPixels);return[` ${t?L(String(n),`red`):String(n)} different / ${r} total pixels`]}function si(e,t){let n=Array.isArray(e.regions)?e.regions:[];if(n.length===0)return[];let r=[` ${di(`Changed regions:`,t)}`];for(let e of n.slice(0,5))r.push(...ci(e));return r}function ci(e){let t=e.shareOfDiffPercentage===0&&e.differentPixels>0?`<0.01`:String(e.shareOfDiffPercentage),n=e.rect,r=[` ${e.index}. x=${n.x} y=${n.y} ${n.width}x${n.height}, ${t}% of diff`],i=e.currentOverlayMatches?.[0];if(i){let e=i.label?` "${i.label}"`:``;r.push(` overlaps @${i.ref}${e}, ${i.regionCoveragePercentage}% of region`)}return r}function li(e){let t=process.cwd(),n=ze.relative(t,e);return n===``||!n.startsWith(`..`)&&!ze.isAbsolute(n)?n===``?`.`:`.${ze.sep}${n}`:e}function F(e){return typeof e==`number`&&Number.isFinite(e)?e:0}function ui(e,t){if(e.length===0)return e;let n=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>e.kind===`added`||e.kind===`removed`).map(e=>e.index);if(n.length===0)return e;let r=Array(e.length).fill(!1);for(let i of n){let n=Math.max(0,i-t),a=Math.min(e.length-1,i+t);for(let e=n;e<=a;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])}function I(e=process.stdout){let t=process.env.FORCE_COLOR;return typeof t==`string`?t!==`0`:typeof process.env.NO_COLOR==`string`?!1:!!e.isTTY}function L(e,t,n){return Be(t,e,n)}function di(e,t){return t?L(e,`dim`):e}function fi(e,t,n,r={nodes:t,filteredCount:0}){let i=gi(e);if(pi(e)){let e=hi(t,n);e&&i.push(e)}!n.raw&&r.filteredCount>0&&i.push(`Collapsed ${r.filteredCount} Android helper node${r.filteredCount===1?``:`s`} from the agent-facing text snapshot; use --raw or --json for the full hierarchy.`);let a=r.filteredCount>0?r.nodes:t;return!n.raw&&Jn(a)&&i.push(`Warning: possible repeated nav subtree detected.`),i}function pi(e){return!e.snapshotQuality&&!mi(e)}function mi(e){let t=e.snapshotDiagnostics;if(!t||typeof t!=`object`)return!1;let n=t.stats;return!!(n&&typeof n==`object`&&n.platform===`web`)}function hi(e,t){if(t.scoped===!0||t.depthLimited===!0||e.length>3)return null;let n=e.length===1?`node`:`nodes`;return`Hint: sparse accessibility snapshot returned ${e.length} ${n}; snapshot state is invalid or unavailable for this screen. Use plain screenshot, not screenshot --overlay-refs, as visual truth. If screenshot shows the Home Screen or another app, run open for this app again first. Then navigate away with coordinates if needed and retry snapshot -i on the next screen.`}function gi(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.length>0):[]}function _i(e){let t=[],n=[],r=new Map(e.map(e=>[e.node.index,e.node])),i=e=>{for(;n.length>0&&(!e||vi(e,n[n.length-1],r));)t.push(...xi(n.pop(),`below`))};for(let r of e)i(r),t.push(r.text),t.push(...xi(r,`above`)),r.node.hiddenContentBelow&&n.push(r);return i(),t}function vi(e,t,n){return yi(e.node,t.node,n)?!1:e.depth<=t.depth}function yi(e,t,n){let r=e;for(;typeof r.parentIndex==`number`;){if(r.parentIndex===t.index)return!0;let e=n.get(r.parentIndex);if(!e)return!1;r=e}return!1}function bi(e){return Or(e,{summarizeTextSurfaces:!0}).flatMap(e=>[M(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...xi({...e,depth:0})])}function xi(e,t){let n=Si(e.type);if(!n)return[];let r=[];if(e.node.hiddenContentAbove&&t!==`below`&&r.push(`[content above ${n} hidden]`),e.node.hiddenContentBelow&&t!==`above`&&r.push(`[content below ${n} hidden]`),r.length===0)return[];let i=` `.repeat(e.depth+1);return r.map(e=>`${i}${e}`)}function Si(e){return e===`scroll-area`||e===`list`||e===`collection`||e===`table`?e:null}function Ci(e,t,n={}){let r=Oi(e);if(r.length===0)return{canScroll:!1,emptySnapshot:!0};let i=te(r),a=ki(r,i,t,n);return a?{canScroll:ji(a,i.get(a.index),t),emptySnapshot:!1,scope:Mi(a,r)}:{canScroll:!1,emptySnapshot:!1}}async function wi(e){let{edge:t,target:n={},scope:r,captureNodes:i}=e;try{let e=Ci(await i(r),t,n);return r&&e.emptySnapshot?await wi({edge:t,target:n,captureNodes:i}):e}catch(e){throw Di(t,r,e)}}async function Ti(e){let{edge:t,captureState:r,scroll:i}=e,a=await r();a.scope&&(a=await r(a.scope));let o=0,s;for(;a.canScroll;){if(o>=40)throw new n(`COMMAND_FAILED`,`scroll ${t} reached the safety limit before the snapshot showed the edge`,{hint:`The scoped scroll container still reports hidden content. Use a smaller manual scroll + snapshot loop to inspect the current state.`});s=await i(),o+=1,a=await r(a.scope)}return{passes:o,result:s}}function Ei(e,t,n,r,i){return t&&n===0?`Already at ${t}; no hidden content ${t===`bottom`?`below`:`above`} detected`:t?`Scrolled to ${t} with ${n} ${e} passes`:i===void 0?r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`:`Scrolled ${e} by ${i}px`}function Di(e,t,r){return t?new n(`COMMAND_FAILED`,`Failed to verify scroll ${e} state for scoped container`,{scope:t,hint:`scroll ${e} could not verify the scoped scroll container. Run snapshot -i for the current screen and retry with a visible scroll target.`},r):new n(`COMMAND_FAILED`,`Failed to verify scroll ${e} state`,{hint:`scroll ${e} needs a snapshot showing hidden content ${e===`bottom`?`below`:`above`} before it will move.`},r)}function Oi(e){return e.map((e,t)=>({...e,ref:`ref`in e&&e.ref?e.ref:`e${t+1}`}))}function ki(e,t,n,r){let i=new Map(e.map(e=>[e.index,e])),a=e.filter(e=>_e(e)&&Ri(e.rect));if(a.length===0)return null;let o=Ai(r.nodeIndex,i);if(o)return o;let s=r.point;if(s){let e=a.filter(e=>e.rect&&Li(e.rect,s)).sort(Fi);if(e.length>0)return e.find(e=>ji(e,t.get(e.index),n))??e[0]??null}let c=a.filter(e=>ji(e,t.get(e.index),n)).sort(Ii);return c.length>0?c[0]??null:a.filter(t=>Ae(t,e)).sort(Ii)[0]??a.sort(Ii)[0]??null}function Ai(e,t){if(e===void 0)return null;let n=t.get(e);for(;n;){if(_e(n)&&Ri(n.rect))return n;n=n.parentIndex===void 0?void 0:t.get(n.parentIndex)}return null}function ji(e,t,n){return n===`bottom`?e.hiddenContentBelow===!0||t?.hiddenContentBelow===!0:e.hiddenContentAbove===!0||t?.hiddenContentAbove===!0}function Mi(e,t){return[e.identifier,e.label].filter(e=>typeof e==`string`).map(e=>e.trim()).find(n=>Pi(n)&&Ni(n,e,t))}function Ni(e,t,n){let r=e.toLowerCase(),i=n.filter(e=>[e.identifier,e.label,e.value].some(e=>typeof e==`string`&&e.trim().toLowerCase().includes(r)));return i.length===1&&i[0]?.index===t.index}function Pi(e){return e.length>0&&e.length<=80&&!/^(true|false)$/i.test(e)&&!/^\d+$/.test(e)&&!/^\d+%$/.test(e)}function Fi(e,t){return R(e.rect)-R(t.rect)}function Ii(e,t){return R(t.rect)-R(e.rect)}function R(e){return e?e.width*e.height:0}function Li(e,t){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}function Ri(e){return!!(e&&e.width>0&&e.height>0)}function zi(e,t,r,i){if(!Number.isFinite(e)||!Number.isInteger(e)||e<r||e>i)throw new n(`INVALID_ARGS`,`${t} must be an integer between ${r} and ${i}`);return e}function z(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}function B(e){return e.clock?.now()??Date.now()}async function Bi(e,t){e.clock?await e.clock.sleep(t):await new Promise(e=>setTimeout(e,t))}function Vi(e,t){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,e=>n(t,e)]))}function V(e){return e&&typeof e==`object`?e:void 0}function Hi(e){let t=Buffer.alloc(16);for(let n of e)Wi(t,Ui(n));return{digest:`ax1:${Ve(`sha256`).update(t).update(`\0`).update(String(e.length)).digest(`hex`).slice(0,16)}`,nodeCount:e.length}}function Ui(e){return Ve(`sha256`).update(e.type??``).update(`\0`).update(e.label??``).update(`\0`).update(e.identifier??``).digest().subarray(0,16)}function Wi(e,t){for(let n=0;n<e.length;n+=1)e[n]=(e[n]??0)^(t[n]??0)}function H(e){let{digest:t,nodeCount:n}=Hi(e),r=e.reduce((e,t)=>t.hittable===!1?e:e+1,0),i=Gi(e);return{digest:t,nodeCount:n,interactiveNodeCount:r,...i?{foregroundApp:i}:{}}}function Gi(e){for(let t of e)if(t.bundleId)return t.bundleId;for(let t of e)if(t.appName)return t.appName}const Ki=[`x`,`y`,`width`,`height`];function U(e){let t=W(e);if(!t)return null;let n=s(t);return!Number.isFinite(n.x)||!Number.isFinite(n.y)?null:n}function W(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),i=Number(e.height);return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||r<0||i<0?null:{x:t,y:n,width:r,height:i}}function G(e,t){return!e||!t?!1:Ki.every(n=>Math.abs(e[n]-t[n])<=.5)}function qi(e){return{x:Ji(e.x,e.width),y:Ji(e.y,e.height)}}function Ji(e,t){if(t<=1)return Math.floor(e);let n=Math.ceil(e),r=Math.floor(e+t-1);return Math.round(Math.min(r,Math.max(n,e+t/2)))}function Yi(e){let t=new Map;for(let n of e)t.set(n.index,n);return t}function Xi(e,t,n){let r=[],i=new Set([e.index]),a=e;for(;r.length<n;){if(typeof a.parentIndex!=`number`)return{chain:r,broken:!1};let e=t.get(a.parentIndex);if(!e||i.has(e.index))return{chain:r,broken:!0};i.add(e.index);let n=x(e);r.push({role:n.role,...n.label===void 0?{}:{label:n.label}}),a=e}return{chain:r,broken:!1}}function Zi(e,t,n,r){return e.filter(e=>{if(!oe(x(e),n))return!1;let i=Xi(e,t,Math.max(r.length,1));return!i.broken&&Ee(i.chain,r)})}function Qi(e,t){let n=t.toLowerCase();return e.find(e=>{let t=(e.label??``).toLowerCase(),r=(e.value??``).toLowerCase(),i=(e.identifier??``).toLowerCase();return t.includes(n)||r.includes(n)||i.includes(n)})??null}function K(e,t){let n=[e.label,e.value,e.identifier].map(e=>typeof e==`string`?e.trim():``).find(e=>e&&e.length>0);return n&&$i(n)?n:ea(e,t)??(n&&$i(n)?n:void 0)}function $i(e){let t=e.trim();return!(!t||/^(true|false)$/i.test(t)||/^\d+$/.test(t))}function ea(e,t){if(!e.rect)return;let n=e.rect.y+e.rect.height/2,r=null;for(let e of t){if(!e.rect)continue;let t=[e.label,e.value,e.identifier].map(e=>typeof e==`string`?e.trim():``).find(e=>e&&e.length>0);if(!t||!$i(t))continue;let i=e.rect.y+e.rect.height/2,a=Math.abs(i-n);(!r||a<r.distance)&&(r={label:t,distance:a})}return r?.label}function ta(e){let t=[],n=[];for(let r of e){let e=r.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let i=v(r.type??``),a=[r.label,r.value,r.identifier].map(e=>typeof e==`string`?e.trim():``).find(e=>e&&e.length>0),o=a?$i(a):!1;if((i===`group`||i===`ioscontentgroup`)&&!o){t.push(e);continue}let s=Math.max(0,e-t.length);n.push({...r,depth:s})}return n}function na(e,t){return t.hittable?t:ra(e,t,e=>e.hittable===!0)}function ra(e,t,n){return se(e,t,Ne(e),e=>n(e)?e:null)}function ia(e){return Le(e)}const aa=[`tabbar`,`toolbar`,`navigationbar`,`bottomnavigation`,`bottomnavigationview`,`sheet`,`dialog`,`alert`,`popover`,`menu`],oa=[`tabbar`,`toolbar`,`navigationbar`],sa=[`button`,`link`,`menuitem`,`tabitem`,`textfield`,`searchfield`,`edittext`,`checkbox`,`radio`,`switch`,`cell`];function ca(e,t={}){if(e.length<2)return e;let n=new Map(e.map(e=>[e.index,e])),r={nodes:e,byIndex:n,overlayPositions:e.flatMap((e,r)=>ha(e,n,t)?[r]:[]),coverCache:new Map},i=[];for(let[n,a]of e.entries())ma(a)&&la(r,n,a,t)&&i.push(n);if(i.length===0)return e;let a=[...e];for(let t of i){let n=e[t];a[t]={...n,hittable:!1,interactionBlocked:`covered`,presentationHints:Ta(n.presentationHints)}}return a}function q(e){return e.interactionBlocked!==void 0}function la(e,t,n,r){let i=e.coverCache.get(t);if(i!==void 0)return i;e.coverCache.set(t,null);let a=J(n.rect);if(!a)return da(e,t,null);let o=s(a),c=r.isAdditionalOverlayNode?.(n)===!0;for(let i of e.overlayPositions){if(!ua(e,i,t,c,r))continue;let s=e.nodes[i];if(fa(e,i,n,a,o,r))return da(e,t,s)}return da(e,t,null)}function ua(e,t,n,r,i){let a=e.nodes[t];return a?t>n?!0:t===n||r?!1:i.isAdditionalOverlayNode?.(a)===!0:!1}function da(e,t,n){return e.coverCache.set(t,n),n}function fa(e,t,n,r,i,a){if(!e.nodes[t])return!1;let o=pa(e,t,n,r,a);return!!(o&&y(o,i.x,i.y))}function pa(e,t,n,r,i){let a=e.nodes[t];if(!a||!ha(a,e.byIndex,i)||Ca(n,a,e.byIndex))return null;let o=J(a.rect);return!o||G(r,o)||la(e,t,a,i)?null:o}function ma(e){return J(e.rect)?e.hittable===!0||ba(e)?!0:!!(e.label?.trim()||e.value?.trim()||e.identifier?.trim()):!1}function ha(e,t,n){return!J(e.rect)||b(e)||ga(e,t)?!1:xa(e,aa)||_a(e,t,n)}function ga(e,t){if(!xa(e,oa))return!1;let n=J(e.rect);if(!n)return!1;let r=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(b(r)){let e=J(r.rect);return!!(e&&G(n,e))}i.add(r.index),r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}return!1}function _a(e,t,n){return n.isAdditionalOverlayNode?.(e)===!0?!va(e,t,n):!1}function va(e,t,n){let r=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(ya(r,n))return!0;i.add(r.index),r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}return!1}function ya(e,t){return t.isAdditionalOverlayNode?.(e)===!0&&J(e.rect)!==null&&!b(e)}function ba(e){return xa(e,sa)}function xa(e,t){let n=Sa(e);return t.some(e=>n.includes(e))}function Sa(e){return[e.type,e.role,e.subrole].map(e=>v(e??``)).join(` `)}function Ca(e,t,n){return wa(e,t,n)||wa(t,e,n)}function wa(e,t,n){let r=typeof t.parentIndex==`number`?n.get(t.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(r.index===e.index)return!0;i.add(r.index),r=typeof r.parentIndex==`number`?n.get(r.parentIndex):void 0}return!1}function J(e){let t=W(e);return t&&t.width>0&&t.height>0?t:null}function Ta(e){return Array.from(new Set([...e??[],`covered`]))}const Ea=[`button`,`link`,`menuitem`,`tabitem`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];function Da(e,t){let n=t[0];if(!n||!Oa(t,new Map(e.map(e=>[e.index,e]))))return{kind:`ambiguous`,candidates:t};let r=Y(e,n).node;for(let n of t.slice(1))if(Y(e,n).node.index!==r.index)return{kind:`ambiguous`,candidates:t};return{kind:`equivalent`,node:r}}function Oa(e,t){for(let n=0;n<e.length;n+=1)for(let r=n+1;r<e.length;r+=1){let i=e[n],a=e[r];if(!ka(i,a,t)&&!ka(a,i,t))return!1}return!0}function ka(e,t,n){let r=t,i=new Set;for(;r.parentIndex!==void 0&&!i.has(r.index);){if(i.add(r.index),r.parentIndex===e.index)return!0;let t=n.get(r.parentIndex);if(!t)return!1;r=t}return!1}function Aa(e,t){return Y(e,t).node}function Y(e,t){if(q(t))return{node:t,reason:`covered`};let n=ja(e,t);if(n?.rect&&U(n.rect))return{node:n,reason:`same-rect-descendant`};if(Ma(t)&&t.rect&&U(t.rect))return{node:t,reason:`semantic-target`};let r=na(e,t);return r?.rect&&!q(r)&&U(r.rect)?Pa(t,r,e)?{node:t,reason:`overly-broad-ancestor`}:{node:r,reason:`hittable-ancestor`}:{node:t,reason:`original`}}function ja(e,t){let n=W(t.rect);if(!n)return null;let r=t,i=new Set;for(;!i.has(r.ref);){i.add(r.ref);let t=e.filter(e=>{if(e.parentIndex!==r.index||!e.hittable||q(e))return!1;let t=W(e.rect);return t?G(t,n):!1});if(t.length!==1)break;r=t[0]}return r===t?null:r}function Ma(e){return[e.type,e.role,e.subrole].map(e=>v(e??``)).some(Na)}function Na(e){return e===`tab`||Ea.some(t=>e.includes(t))}function Pa(e,t,n){let r=W(e.rect),i=W(t.rect);if(!r||!i)return!1;if(Fa(t)&&!G(r,i))return!0;let a=Ia(n,r);return!a||!La(i,a)?!1:!G(r,i)}function Fa(e){let t=v(e.type??``);return t.includes(`scrollview`)||t.includes(`scrollarea`)||t.includes(`listview`)||t.includes(`recyclerview`)||t.includes(`collectionview`)||t===`list`||t===`table`||t===`collection`}function Ia(e,t){let n=s(t),r=e.filter(b).map(e=>W(e.rect)).filter(e=>e!==null);if(r.length===0)return null;let i=r.filter(e=>y(e,n.x,n.y));return le(i.length>0?i:r)}function La(e,t){let n=ee(e,t),r=e.width*e.height,i=t.width*t.height;if(n<=0||r<=0||i<=0)return!1;let a=n/i,o=n/r;return a>=.9&&o>=.8}function Ra(e){return e.hittable===!0||Ma(e)}function za(e,t){let n=ge(x(e),t);return n.id!==void 0||n.label!==void 0?!1:ce(e.value)===null}function Ba(e,t,n){let r=new Set,i=e;for(;typeof i.parentIndex==`number`;){if(r.has(i.index))return!1;if(r.add(i.index),i.parentIndex===t.index)return!0;let e=n.get(i.parentIndex);if(!e)return!1;i=e}return!1}function Va(e,t){let n=Yi(t);return t.filter(t=>t.index!==e.index&&Ba(t,e,n)).sort((e,t)=>e.index-t.index)}function Ha(e,t){let n=U(e.rect);return!n||!t.rect?!1:y(t.rect,n.x,n.y)}function Ua(e,t){if(!za(e,t))return e;let n=Va(e,t);if(n.some(Ra))return e;let r=n.find(e=>x(e).label!==void 0);return!r||!Ha(r,e)?e:r}const Wa=new Set([`healthy`,`recovered`,`sparse`]),Ga=new Set([`tree`,`queries`,`private-ax`]),Ka=new Set([`ax-rejected`,`sparse-tree`,`budget`,`no-nodes`,`capture-failed`,`deferred`,`requested-backend`]);function qa(e){if(!e||typeof e!=`object`)return;let t=e;if(!(typeof t.state!=`string`||!Wa.has(t.state))&&!(typeof t.backend!=`string`||!Ga.has(t.backend)))return{state:t.state,backend:t.backend,reason:typeof t.reason==`string`?t.reason:void 0,reasonCode:typeof t.reasonCode==`string`&&Ka.has(t.reasonCode)?t.reasonCode:void 0,customActions:Ja(t.customActions),effectiveDepth:typeof t.effectiveDepth==`number`?t.effectiveDepth:void 0,collapsedLeafIndexes:Array.isArray(t.collapsedLeafIndexes)?t.collapsedLeafIndexes.filter(e=>typeof e==`number`):void 0}}function Ja(e){if(!e||typeof e!=`object`)return;let t=e;if(!(typeof t.read!=`number`||typeof t.candidates!=`number`))return{read:t.read,candidates:t.candidates,truncated:typeof t.truncated==`number`?t.truncated:0,blocked:t.blocked===!0}}function Ya(e){return e?.state===`sparse`}function Xa(e,t){return[...$a(e),...Za(e),...eo(e),...to(e,t)]}function Za(e){let t=e.customActions;if(!t)return[];let n=[];return t.blocked?n.push(`Custom actions were not read: an earlier accessibility read is still hung, so this capture skipped the read pass instead of queueing behind it. No element’s actions list is authoritative here. Reads resume once that call returns.`):t.read<t.candidates&&n.push(`Custom actions were read for ${t.read} of ${t.candidates} merged elements, on-screen ones first; the remaining ${t.candidates-t.read} were not read, so an absent actions list on those is not evidence that they have none. Scroll them into view and re-run to read them.`),t.truncated>0&&n.push(`${t.truncated} element(s) published more custom actions than are shown; those lists are clipped to the first 8 names, and long names are shortened.`),n}function Qa(e){return`Detected an overly complex or slow accessibility tree. Fell back to the ${e} snapshot backend. It is OK to continue; use --json to inspect snapshotQuality.reason if you need recovery details.`}function $a(e){return e.state===`recovered`?e.reasonCode===`deferred`||e.reasonCode===`requested-backend`?[]:[Qa(e.backend)]:e.state===`sparse`?[`No snapshot backend could read this screen`+(e.reason?` (${e.reason})`:``)+`. Its refs and selectors are invalid. Use screenshot as visual truth and coordinate taps; retry snapshot after navigating.`]:[]}function eo(e){return e.effectiveDepth===void 0?[]:[`Some deeper accessibility nodes were omitted; this tree is capped at depth ${e.effectiveDepth}. Re-run with --depth ${e.effectiveDepth} --scope <container> only if you need deeper content.`]}function to(e,t){let n=[];for(let r of e.collapsedLeafIndexes??[]){let e=t.find(e=>e.index===r);if(!e)continue;let i=e.identifier?` (${e.identifier})`:``;n.push(`@${e.ref} [${e.type??`element`}]${i} merges many labels into a single accessibility element. The app likely marks a container as accessible, which hides every descendant from assistive tech and automation — the children cannot be addressed individually. Fix the app's accessibility (mark the rows, not the container); until then use screenshot as visual truth and coordinate taps.`)}return n}const no=new Set([`empty-helper-output`,`system-window-only`,`content-poor-app-window`]);function ro(e){if(!e||typeof e!=`object`)return!1;let t=e.details?.androidSnapshotHelperFailureReason;return typeof t==`string`&&no.has(t)}function io(e){return e===`text`||e===`label`||e===`any`}function ao(e,t,n,r){if(!(r||e===`web`))return io(t)?n:void 0}function oo(e){return new n(`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.`})}async function so(e,t){let r=t??`default`,i=await e.sessions.get(r);if(!i)throw new n(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let a=i.refFrameSnapshot??i.snapshot;if(!a)throw new n(`INVALID_ARGS`,`No snapshot in session. Run snapshot first.`);return{sessionName:r,session:i,snapshot:a}}async function co(e,t,r={updateSession:!0}){let i=e.backend.captureSnapshot;if(!i)throw new n(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let a=t.session??`default`,o=await e.sessions.get(a),s=await i(z(e,t),{interactiveOnly:r.interactiveOnly??!1,depth:t.depth,scope:r.scope??t.scope,raw:t.raw,includeRects:r.includeRects,...r.includeHiddenContentHints===void 0?{}:{includeHiddenContentHints:r.includeHiddenContentHints}}),c=s.snapshot??{nodes:s.nodes??[],truncated:s.truncated,backend:s.backend,...s.quality?{snapshotQuality:s.quality}:{},createdAt:B(e)};return(t.signal??e.signal)?.throwIfAborted(),r.updateSession&&o&&!Ya(c.snapshotQuality)&&await e.sessions.set({...o,snapshot:c}),{sessionName:a,session:o,snapshot:c}}async function lo(e,t,n){if(e.backend.readText){let r=await e.backend.readText(z(e,{session:t.sessionName}),n);if(r.text.trim())return r.text}return Le(n)}function uo(e,t,i){let a=o(t);if(!a)throw new n(`INVALID_ARGS`,i.invalidRefMessage);let s=r(e,a)??(i.fallbackLabel.length>0?Qi(e,i.fallbackLabel):null);if(!s)throw new n(`COMMAND_FAILED`,i.notFoundMessage);return{ref:a,node:s}}function fo(e,t){if(Buffer.byteLength(e,`utf8`)<=t)return e;let n=Buffer.byteLength(`…`,`utf8`),r=Math.max(0,t-n),i=Buffer.from(e,`utf8`),a=Math.min(r,i.length);for(;a>0&&(i[a]&192)==128;)--a;return i.subarray(0,a).toString(`utf8`)+`…`}function po(e,t,n={}){let r=W(t.rect),i=U(r??void 0);if(!r||!i)return{kind:`invalid`};let a=mo(e,t,r);if(a.length===0)return{kind:`resolved`,point:i,strategy:`center`};let o=(n.bounds??[]).reduce((e,t)=>e?go(e,t):null,r),s=o?_o(r,o,i,a):null;return s?{kind:`resolved`,point:s,strategy:`parent-owned`}:{kind:`blocked`,competitorRefs:a.map(e=>e.ref)}}function mo(e,t,n){let r=new Map(e.map(e=>[e.index,e]));return e.filter(e=>e.index!==t.index).filter(e=>ho(e,t,r)).filter(Ma).flatMap(e=>{let t=W(e.rect);if(!t||G(t,n))return[];let r=go(t,n);return r&&r.width>0&&r.height>0?[{ref:e.ref,index:e.index,rect:r}]:[]}).sort((e,t)=>e.index-t.index)}function ho(e,t,n){let r=new Set,i=e;for(;typeof i.parentIndex==`number`&&!r.has(i.index);){if(r.add(i.index),i.parentIndex===t.index)return!0;let e=n.get(i.parentIndex);if(!e)return!1;i=e}return!1}function go(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width),a=Math.min(e.y+e.height,t.y+t.height);return i<=n||a<=r?null:{x:n,y:r,width:i-n,height:a-r}}function _o(e,t,n,r){let i=Co(e),a=xo(t.x,t.width,n.x,r.flatMap(({rect:e})=>[e.x,e.x+e.width]),i),o=xo(t.y,t.height,n.y,r.flatMap(({rect:e})=>[e.y,e.y+e.height]),i);return a.flatMap(a=>o.flatMap(o=>{let s={x:Math.round(a),y:Math.round(o)};if(!vo(t,s))return[];let c=yo(s,e,n,r,i);return c?[c]:[]})).sort(bo)[0]?.point??null}function vo(e,t){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}function yo(e,t,n,r,i){let a=So(e,t,r);return a.parentEdge<i||a.competitor<12?null:{point:e,distanceSquared:(e.x-n.x)**2+(e.y-n.y)**2,clearance:Math.min(a.parentEdge,a.competitor)}}function bo(e,t){return e.distanceSquared-t.distanceSquared||t.clearance-e.clearance||e.point.y-t.point.y||e.point.x-t.point.x}function xo(e,t,n,r,i){let a=e+i,o=e+t-i;if(a>o)return[];let s=[...new Set([e,e+t,...r])].sort((e,t)=>e-t),c=new Set([n,a,o]);for(let e of r)c.add(e-12),c.add(e+12);for(let e=1;e<s.length;e+=1)c.add((s[e-1]+s[e])/2);return[...c].filter(e=>e>=a&&e<=o).sort((e,t)=>e-t)}function So(e,t,n){let r=Math.min(e.x-t.x,t.x+t.width-e.x,e.y-t.y,t.y+t.height-e.y),i=1/0;for(let{rect:t}of n){let n=e.x<t.x?t.x-e.x:Math.max(0,e.x-(t.x+t.width)),r=e.y<t.y?t.y-e.y:Math.max(0,e.y-(t.y+t.height));i=Math.min(i,Math.max(n,r))}return{parentEdge:r,competitor:i}}function Co(e){let t=Math.min(e.width,e.height);return Math.max(0,Math.min(12,Math.floor(t/2)-1))}const wo=`replay_target_guard_mismatch`,To=re.landmarkIdentityMismatch;function Eo(e,t,r){let i=Ce(e,t,ie.act,{platform:r});if(i.kind===`none`)return null;if(i.kind===`resolved`)return i.resolution;let a=Da(e,i.matchedNodes);if(a.kind===`ambiguous`)throw new n(`AMBIGUOUS_MATCH`,`Selector matched ${a.candidates.length} distinct actionable elements: ${i.selector}`,{selector:i.selector,matches:a.candidates.length,candidates:a.candidates.slice(0,5).map(e=>M(e,0,!1))});return{node:a.node,selector:i.selector,selectorIndex:i.selectorIndex,matches:i.matchedNodes.length,diagnostics:[{selector:i.selector,matches:i.matchedNodes.length}],disambiguation:{matchCount:i.matchedNodes.length,tiebreak:`structural-equivalence`,alternatives:i.matchedNodes.filter(e=>e.index!==a.node.index)}}}function Do(e,t,r,i,a){if(!r)return;let o=x(e),s=ue(e,t);if(!(de(o,r.identity)&&fe(s,r.structural)))throw new n(`COMMAND_FAILED`,`${i} resolved to a different element than replay verification isolated; the action was not sent`,{reason:wo,observed:o,observedStructural:s,expected:r.identity,expectedStructural:r.structural,...a?{targetRole:a}:{}})}async function X(e,t,n){return await Zo(e,t,n.action),t.target.kind===`point`?await ko(e,t,t.target,n):t.target.kind===`ref`?await No(e,t,t.target,n):await Po(e,t,t.target,n)}async function Oo(e,t,n){let r=t.session??`default`,i=await e.sessions.get(r);if(!i?.snapshot)return;let a={x:n.x,y:n.y,width:0,height:0},o=ae(i.snapshot.nodes,a);if(!o)return;let s={x:n.x,y:n.y};if(!y(o,s.x,s.y))return`Coordinates (${s.x}, ${s.y}) are outside the last-known viewport (${o.width}x${o.height}). The tap will be forwarded anyway; take a fresh snapshot if the screen changed.`}async function ko(e,t,n,r){let i=await Oo(e,t,n);if(!r.captureEvidenceBaseline)return{kind:`point`,point:{x:n.x,y:n.y},...i?{warning:i}:{}};let a=await Ao(e,t);return{kind:`point`,point:{x:n.x,y:n.y},...a?{preActionNodes:a}:{},...i?{warning:i}:{}}}async function Ao(e,t){try{return(await Z(e,t,!0)).snapshot.nodes}catch{return}}function jo(e,t){let r=o(e.ref);if(!r)throw new n(`INVALID_ARGS`,`Invalid ref: ${e.ref}`);let i=o(t.ref),a=t.node.ref?o(t.node.ref):null;if(i!==r||a!==r||!t.nodes.includes(t.node))throw new n(`COMMAND_FAILED`,`Internal find target provenance does not match the interaction ref`);return{nodes:t.nodes,resolved:zo(r,t.node,`exact`)}}async function Mo(e,t,n){let r=await $o(e,t,n);return{nodes:r.snapshot.nodes,resolved:r.resolved}}async function No(e,t,n,r){let{nodes:i,resolved:a}=r.preresolvedTarget?jo(n,r.preresolvedTarget):await Mo(e,t,n);Io(a.node,i,r);let s=r.promoteToHittableAncestor?qo(i,a.node,{action:r.action,label:`Ref ${n.ref}`}):a.node;Jo(s,`Ref ${n.ref}`,r.action);let c=await as(e,t,s,i,n.ref,r.action);return{kind:`ref`,point:ns(c,i,{invalidMessage:`Ref ${n.ref} not found or has invalid bounds`,blockedTargetLabel:`Ref ${n.ref}`,blockedTargetDetails:{ref:`@${o(n.ref)??c.ref}`}}),target:{kind:`ref`,ref:`@${a.ref}`},...Uo(e,c,i,r.action,a.resolution)}}async function Po(e,t,n,r){let i=n.selector,a=await Z(e,t,r.requireInteractive),o=Eo(Ko(a.snapshot.nodes),i,e.backend.platform);if((!o||!o.node.rect)&&r.requireInteractive&&(a=await Z(e,t,!1),o=Eo(Ko(a.snapshot.nodes),i,e.backend.platform)),!o||!o.node.rect)throw Fo({runtime:e,nodes:a.snapshot.nodes,selectorExpression:i,action:r.action,resolved:o});Io(o.node,a.snapshot.nodes,r);let s=r.promoteToHittableAncestor?qo(a.snapshot.nodes,o.node,{action:r.action,label:`Selector ${o.selector}`}):o.node;Jo(s,`Selector ${o.selector}`,r.action);let c=await is(e,t,s,a.snapshot.nodes,o.selector,r.action);return{kind:`selector`,point:ns(c,a.snapshot.nodes,{invalidMessage:`Selector ${o.selector} resolved to invalid bounds`,blockedTargetLabel:`Selector ${i}`,blockedTargetDetails:{selector:i}}),target:{kind:`selector`,selector:o.selector},...Uo(e,c,a.snapshot.nodes,r.action,Vo(o,a.snapshot.nodes))}}function Fo(e){let{runtime:t,nodes:r,selectorExpression:i,action:a,resolved:o}=e,s=Ce(r,i,ie.actCoveredDiagnosis,{platform:t.backend.platform});if(s.kind===`resolved`&&q(s.resolution.node))return Yo({label:`Selector ${s.resolution.selector}`,node:s.resolution.node,action:a,selector:s.resolution.selector});let c=o?.diagnostics??[];return new n(`COMMAND_FAILED`,Oe(i,c,{unique:!0}),{hint:we(c)})}function Io(e,t,n){Do(e,t,n.expectedResolvedTarget,n.action,n.replayTargetRole)}const Lo={source:`ref`,phase:`pre-action`,kind:`exact`},Ro={source:`ref`,phase:`pre-action`,kind:`label-fallback`};function zo(e,t,n){return{ref:e,node:t,resolution:n===`exact`?Lo:Ro}}const Bo={source:`runtime`,phase:`pre-action`,kind:`unique`};function Vo(e,t){return e.disambiguation?{source:`runtime`,phase:`pre-action`,kind:`disambiguated`,matchCount:e.disambiguation.matchCount,winnerDiagnostic:Ho(e.node,t),tiebreak:e.disambiguation.tiebreak,alternatives:e.disambiguation.alternatives.slice(0,5).map(e=>Ho(e,t))}:Bo}function Ho(e,t){let n=v(e.type??``),r=K(e,t);return{diagnosticRef:`diag-${e.ref}`,...n?{role:fo(n,256)}:{},...r===void 0?{}:{label:fo(r,256)}}}function Uo(e,t,n,r,i){return{node:t,selectorChain:me(t,e.backend.platform,{action:r===`fill`?`fill`:`click`,nodes:n}),refLabel:K(t,n),...Go(t,r),preActionNodes:n,resolution:i,...Wo(e,t,n,r)}}function Wo(e,t,n,r){if(r!==`click`&&r!==`press`)return{};let i=Ua(t,n);return i===t?{}:{recordingTarget:{node:i,selectorChain:me(i,e.backend.platform,{action:`click`,nodes:n}),refLabel:K(i,n)}}}function Go(e,t){return e.hittable===!1?{targetHittable:!1,hint:`The resolved element reports hittable: false, so this ${t} may have had no visible effect. Verify with a snapshot, or prefer a @ref or a longer/more specific selector to target the intended element.`}:{}}function Ko(e){return e.filter(e=>!q(e))}function qo(e,t,n){let r=Y(e,t);if(r.reason===`covered`)throw Yo({label:n.label,node:t,action:n.action});return r.node}function Jo(e,t,n){if(q(e))throw Yo({label:t,node:e,action:n})}function Yo(e){return new n(`COMMAND_FAILED`,`${e.label} is covered by another visible element and cannot ${Xo(e.action)} safely`,{hint:`Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.`,...e.selector?{selector:e.selector}:{},ref:`@${e.node.ref}`,interactionBlocked:e.node.interactionBlocked})}function Xo(e){switch(e){case`fill`:return`be filled`;case`focus`:return`be focused`;case`longPress`:return`be long-pressed`;default:return`be tapped`}}async function Z(e,t,r){if(!e.backend.captureSnapshot)throw new n(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let i=t.session??`default`,a=await e.sessions.get(i);if(!a)throw new n(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let o=await e.backend.captureSnapshot(z(e,t),{interactiveOnly:r,includeRects:!0}),s=o.snapshot??{nodes:o.nodes??[],truncated:o.truncated,backend:o.backend,createdAt:B(e)};return await e.sessions.set({...a,snapshot:s}),{snapshot:s}}async function Zo(e,t,r){if(e.backend.platform!==`macos`)return;let i=await Qo(e,t);if(!(i!==`desktop`&&i!==`menubar`)&&!(i===`menubar`&&(r===`click`||r===`press`)))throw new n(`UNSUPPORTED_OPERATION`,`${r} is not supported on macOS ${i} sessions yet. Open an app session to act, or use the ${i} surface to inspect.`)}async function Qo(e,t){return(await e.sessions.get(t.session??`default`))?.metadata?.surface}async function $o(e,t,r){let{session:i,snapshot:a}=await so(e,t.session),o=r.fallbackLabel??``,s=ts(a.nodes,r.ref,{fallbackLabel:o});if(!s)throw new n(`COMMAND_FAILED`,`Ref ${r.ref} not found or has no bounds`,{hint:be});return es({session:i,frameTree:a,target:r,fallbackLabel:o,authorized:s})}function es(e){let{session:t,frameTree:n,target:r,fallbackLabel:i,authorized:a}=e,o=t.snapshot;if(!o||o===n)return{snapshot:n,resolved:a};let s=ts(o.nodes,r.ref,{fallbackLabel:i});return s&&de(x(a.node),x(s.node))?{snapshot:o,resolved:s}:{snapshot:n,resolved:a}}function ts(e,t,i){let a=o(t);if(!a)throw new n(`INVALID_ARGS`,`Invalid ref: ${t}`);let s=r(e,a);if(rs(s))return zo(a,s,`exact`);let c=i.fallbackLabel.length>0?Qi(e,i.fallbackLabel):null;return rs(c)?zo(a,c,`label-fallback`):null}function ns(e,t,r){let i=po(t,e,{bounds:[Te(e,t),e.rect?ae(t,e.rect):null].filter(e=>e!==null)});if(i.kind===`resolved`)return i.point;throw i.kind===`invalid`?new n(`COMMAND_FAILED`,r.invalidMessage):new n(`COMMAND_FAILED`,`${r.blockedTargetLabel} has no parent-owned touch point outside its interactive descendants`,{reason:`covered_by_interactive_descendants`,...r.blockedTargetDetails,competitorRefs:i.competitorRefs.slice(0,5).map(e=>`@${e}`),competitorCount:i.competitorRefs.length,hint:`Tap the specific interactive child you intend, or use a more specific selector. Every safely tappable region of the parent belongs to one of its child controls.`})}function rs(e){return e?U(e.rect)!==null:!1}async function is(e,t,n,r,i,a){return await cs(e,t,n,r,{message:`Selector ${i} resolved to an off-screen element and is not safe to ${a}`,details:{reason:`offscreen_selector`,selector:i},hint:e=>`${os(e)} in small steps, retrying ${a} with the same selector after each (it re-resolves against a fresh snapshot). A single large scroll can overshoot the target; a short bounded gesture pan lands it more reliably. If it is inside a closed drawer or another tab, open that container first.`})}async function as(e,t,n,r,i,a){return await cs(e,t,n,r,{message:`Ref ${i} is off-screen and not safe to ${a}`,details:{reason:`offscreen_ref`,ref:o(i)},hint:e=>`${os(e)} in small steps (a single large scroll can overshoot; a short bounded gesture pan lands it more reliably), then retry ${a} with a selector (e.g. text=/id=) rather than this @ref — the scroll expires the ref frame, so re-run snapshot -i before reusing any @ref.`})}function os(e){return e?`Scroll ${e} toward it`:`Scroll toward it`}async function ss(e,t,n,r){let i=(await e.sessions.get(t.session??`default`))?.snapshot?.nodes;if(!i||o(n.ref)===null)return{};let a=ts(i,n.ref,{fallbackLabel:n.fallbackLabel??``});if(!a)return{};Jo(a.node,`Ref ${n.ref}`,r);let s=await as(e,t,a.node,i,n.ref,r);return{...Go(s,r),node:s,preActionNodes:i}}async function cs(e,t,r,i,a){let o=r.rect?Te(r,i):null;if(!r.rect||!o||he(r,i))return r;let s=ae(i,r.rect),c=await e.backend.confirmOffscreenTargetVisible?.(z(e,t),r,s);if(c)return{...r,rect:c};let l=_(r,i);throw new n(`COMMAND_FAILED`,a.message,{...a.details,rect:r.rect,viewport:o,...l?{scrollDirection:l}:{},hint:a.hint(l)})}function ls(e,t){let n=P(e.type??`Element`),r=N(e,n),i=e.enabled===!1?`disabled`:`enabled`,a=e.selected===!0?`selected`:`unselected`,o=e.hittable===!0?`hittable`:`not-hittable`;return[String(t??e.depth??0),n,r,i,a,o,e.actions?JSON.stringify(e.actions):``].join(`|`)}function us(e,t,n={}){let r=ps(fs(e,n),fs(t,n)),i={additions:0,removals:0,unchanged:0};for(let e of r)e.kind===`added`&&(i.additions+=1),e.kind===`removed`&&(i.removals+=1),e.kind===`unchanged`&&(i.unchanged+=1);return{summary:i,lines:r}}function ds(e,t={}){return fs(e,t).length}function fs(e,t){return t.flatten?e.map(e=>({text:M(e,0,!1),comparable:ls(e,0),...t.withRefs&&e.ref?{ref:e.ref}:{}})):Or(e).map(e=>({text:e.text,comparable:ls(e.node,e.depth),...t.withRefs&&e.node.ref?{ref:e.node.ref}:{}}))}function ps(e,t){let n=e.length,r=t.length,i=n+r,a=new Map,o=[];a.set(1,0);for(let s=0;s<=i;s+=1){o.push(new Map(a));for(let i=-s;i<=s;i+=2){let c=hs(a,i,s)?Q(a,i+1):Q(a,i-1)+1,l=c-i;for(;c<n&&l<r&&e[c].comparable===t[l].comparable;)c+=1,l+=1;if(a.set(i,c),c>=n&&l>=r)return ms(o,e,t,n,r)}}return[]}function ms(e,t,n,r,i){let a=[],o=r,s=i;for(let r=e.length-1;r>=0;--r){let i=e[r],c=o-s,l=hs(i,c,r)?c+1:c-1,u=Q(i,l),d=u-l;for(;o>u&&s>d;)a.push({kind:`unchanged`,text:n[s-1].text}),--o,--s;if(r===0)break;if(o===u){let e=n[d];a.push({kind:`added`,text:e.text,...e.ref?{ref:e.ref}:{}}),s=d}else a.push({kind:`removed`,text:t[u].text}),o=u}return a.reverse(),a}function hs(e,t,n){return t===-n||t!==n&&Q(e,t-1)<Q(e,t+1)}function Q(e,t){return e.get(t)??0}function gs(e){return e?ke({packageName:e.bundleId,resourceId:e.identifier}).inputMethodOwned:!1}const _s=new Set([`textfield`,`securetextfield`,`textview`,`textarea`,`searchfield`,`edittext`]),vs={strippedIndexes:new Set,refs:new Set};function ys(e){let t=new Set(e.filter(e=>v(e.type??``)===`keyboard`).map(e=>e.index));if(t.size===0)return vs;let n=new Map(e.map(e=>[e.index,e])),r=ws(e,n,t),i=new Set(r),a=Ms(e,n,r);for(let t of ws(e,n,a))i.add(t);for(let o of bs(e,n,a,t,r))i.delete(o);let o=new Set(e.filter(e=>e.ref&&i.has(e.index)).map(e=>e.ref));return{strippedIndexes:new Set([...i].filter(e=>!t.has(e))),refs:o}}function bs(e,t,n,r,i){let a=new Set;if(n.size===0)return a;let o=Ss(t,n,r);if(o.size===0)return a;let s=Cs(t,r);for(let n of e)!i.has(n.index)&&!s.has(n.index)&&n.rect&&xs(n,t,o)&&a.add(n.index);return a}function xs(e,t,n){if(!e.rect)return!1;let r=Ns(e,t);if(r===void 0)return!1;let i=n.get(r);return i!==void 0&&e.rect.y+e.rect.height/2<i}function Ss(e,t,n){let r=new Map;for(let i of n){let n=e.get(i);if(!n?.rect)continue;let a=Ns(n,e);if(a===void 0||!t.has(a))continue;let o=r.get(a);(o===void 0||n.rect.y<o)&&r.set(a,n.rect.y)}return r}function Cs(e,t){let n=new Set;for(let r of t){let t=e.get(r),i=t&&typeof t.parentIndex==`number`?e.get(t.parentIndex):void 0;for(;i;)n.add(i.index),i=typeof i.parentIndex==`number`?e.get(i.parentIndex):void 0}return n}function ws(e,t,n){let r=new Set(n);if(n.size===0)return r;for(let i of e)Ps(i,t,n)&&r.add(i.index);return r}function Ts(e,t){if(e.bundleId!==`com.android.systemui`)return!1;if(ve(e))return!0;let n=new Set,r=e;for(;r?.bundleId===`com.android.systemui`&&!n.has(r.index);){if(pe(r.identifier))return!0;n.add(r.index),r=r.parentIndex===void 0?void 0:t.get(r.parentIndex)}return!1}function Es(e,t){let n=new Map(e.map(e=>[e.index,e])),r=new Set(e.filter(e=>gs(e)).map(e=>e.index)),i=new Set([...r].filter(e=>{let t=n.get(e)?.parentIndex,i=t===void 0?void 0:n.get(t);return!i||!r.has(i.index)})),a=t===`com.android.systemui`?new Set:Ds(e,n,r),o=new Set([...r].filter(e=>!i.has(e)));for(let e of a)o.add(e);let s=new Set(e.filter(e=>e.ref&&(r.has(e.index)||a.has(e.index))).map(e=>e.ref));return o.size===0&&s.size===0?vs:{strippedIndexes:o,refs:s}}function Ds(e,t,n){return new Set(e.filter(e=>!n.has(e.index)&&Ts(e,t)).map(e=>e.index))}function Os(e,t){let n=ys(e),r=Es(e,t);return n.strippedIndexes.size===0&&n.refs.size===0?r:r.strippedIndexes.size===0&&r.refs.size===0?n:{strippedIndexes:new Set([...n.strippedIndexes,...r.strippedIndexes]),refs:new Set([...n.refs,...r.refs])}}function ks(e,t){let{strippedIndexes:n}=Os(e,t);return n.size===0?e:e.filter(e=>!n.has(e.index))}function As(e,t){return Os(e,t).refs}function js(e){return ys(e).refs}function Ms(e,t,n){let r=new Set;for(let e of n){let n=t.get(e);if(!n||v(n.type??``)!==`keyboard`)continue;let i=Ns(n,t);i!==void 0&&r.add(i)}for(let i of r){let a=new Set([i]);e.some(e=>_s.has(v(e.type??``))&&!n.has(e.index)&&Ps(e,t,a))&&r.delete(i)}return r}function Ns(e,t){let n=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0;for(;n;){if(v(n.type??``)===`window`)return n.index;n=typeof n.parentIndex==`number`?t.get(n.parentIndex):void 0}}function Ps(e,t,n){let r=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0;for(;r;){if(n.has(r.index))return!0;r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}return!1}async function Fs(e,t,n,r){let i=new AbortController,a=[t.signal,e.signal].filter(e=>e!==void 0),o=AbortSignal.any([...a,i.signal]),s=!1,c=setTimeout(()=>{s=!0,i.abort(new DOMException(`Wait deadline exceeded`,`TimeoutError`))},Math.max(0,n));c.unref();try{let e=await r(o);return s&&!a.some(e=>e.aborted)?{timedOut:!0}:(o.throwIfAborted(),{timedOut:!1,value:e})}catch(e){if(s&&!a.some(e=>e.aborted))return{timedOut:!0};throw e}finally{clearTimeout(c)}}const Is=`Settled on a nearly-empty tree — the app may still be loading. Wait for specific content (wait text ...) before interacting.`;async function Ls(e,t,n){let{quietMs:r,timeoutMs:i}=n,a=B(e),o=a+i,s=!1,c=Math.min(300,Math.max(25,r)),l=0,u,d=0,f,p=a;for(;B(e)<o;){let m=await Bs(e,t,o-B(e));if(!m)return{settled:!1,stalled:!0,waitedMs:B(e)-a,captures:l,nodeCount:d,lastCapture:f};l+=1,f=m;let h=Vs(m.snapshot.nodes),g=B(e);if(n.resetBudgetOnPrivateAxRecovery===!0&&!s&&Rs(m.snapshot.snapshotQuality)){s=!0,o=Math.max(o,g+i),p=g,u=h,d=m.snapshot.nodes.length;let t=zs({nowMs:g,quietSinceMs:p,quietMs:r,pollMs:c,deadlineMs:o});if(t<=0)break;await Bi(e,t);continue}if(h!==u)u=h,d=m.snapshot.nodes.length,p=g;else if(l>=2&&g-p>=r)return{settled:!0,stalled:!1,waitedMs:g-a,captures:l,nodeCount:d,lastCapture:f};let _=zs({nowMs:g,quietSinceMs:p,quietMs:r,pollMs:c,deadlineMs:o});if(_<=0)break;await Bi(e,_)}return{settled:!1,stalled:!1,waitedMs:B(e)-a,captures:l,nodeCount:d,lastCapture:f}}function Rs(e){return e?.state===`recovered`&&e.backend===`private-ax`&&e.reasonCode!==`deferred`}function zs(e){let t=e.quietSinceMs+e.quietMs-e.nowMs,n=t>e.pollMs?e.pollMs:Math.max(25,t+2),r=e.deadlineMs-e.nowMs,i=r-1;return i<2?r>=2?r:0:Math.min(n,i)}async function Bs(e,t,n){let r=await Fs(e,t,n,async n=>await co(e,{...t,signal:n},{updateSession:!1,interactiveOnly:!0}));return r.timedOut?void 0:r.value}function Vs(e){return e.map(Hs).join(`|`)}function Hs(e){let t=e.rect?`${Math.round(e.rect.x)},${Math.round(e.rect.y)},${Math.round(e.rect.width)},${Math.round(e.rect.height)}`:``;return`${e.type??``}#${e.label??``}#${e.identifier??``}#${t}`}const Us=`The UI kept changing for the whole settle budget (animation, carousel, or ticker?), so no settled diff is shown. Raise --timeout, wait for specific content, or take a fresh snapshot.`,Ws=`A snapshot capture stalled past the settle budget, so no settled diff is shown. The action itself succeeded; observe with wait stable or snapshot.`;async function Gs(e,t,n){return await qs(e,t,{...n,baselineNodes:Xs(n.resolved),actionPoint:n.resolved.point})}const Ks=async(e,t)=>(await qs(e,t,t)).observation;async function qs(e,t,n){let r=n.quietMs??500,i=n.timeoutMs??1e4,a={settled:!1,waitedMs:0,captures:0,quietMs:r,timeoutMs:i};try{return await Js(e,t,n,a,await Ls(e,t,{quietMs:r,timeoutMs:i,resetBudgetOnPrivateAxRecovery:!0}))}catch(e){return{observation:{...a,hint:`Settle observation unavailable (${e instanceof Error?e.message:String(e)}). The action itself succeeded; take a snapshot to observe the result.`}}}}async function Js(e,t,n,r,i){let a={...r,settled:i.settled,waitedMs:i.waitedMs,captures:i.captures};if(!i.lastCapture)return{observation:{...a,hint:i.stalled?Ws:Us}};let{stored:o,session:s}=await ac(e,t,i.lastCapture),c=i.lastCapture.snapshot.nodes;return{observation:{...a,...i.settled&&o?Qs(n.baselineNodes,c,n.actionPoint,s?.appBundleId):{},...ic(i,o,c.length)},settledNodes:c}}function Ys(e,t){if(!e)return;let n=H(e),r=t!==void 0&&n.digest!==H(t).digest;return{...n,changedFromBefore:r}}function Xs(e){return`preActionNodes`in e&&e.preActionNodes?e.preActionNodes:[]}function Zs(e,t,n){let r=us(ks(e,n),ks(t,n),{flatten:!0,withRefs:!0}),i=r.lines.filter(e=>e.kind!==`unchanged`),a=rc(i).map(e=>({kind:e.kind,text:e.text,...e.ref?{ref:e.ref}:{}}));return{summary:r.summary,lines:a,...i.length>a.length?{truncated:!0}:{}}}function Qs(e,t,n,r){let i=Zs(e,t,r);return{diff:i,...$s(i,t,n,r)}}function $s(e,t,n,r){let i=new Set(e.lines.filter(e=>e.kind===`added`&&e.ref).map(e=>e.ref)),a=As(t,r),o=new Map(t.filter(e=>e.ref).map(e=>[e.ref,e]));return[...i].some(e=>e!==void 0&&!a.has(e)&&!ec(o.get(e),n))?{}:nc(t,i,r)}function ec(e,t){if(!e?.rect||!t)return!1;let{x:n,y:r,width:i,height:a}=e.rect;return t.x>=n&&t.x<=n+i&&t.y>=r&&t.y<=r+a}const tc=new Set([`application`,`window`]);function nc(e,t,n){let r=As(e,n),i=e.filter(e=>e.ref&&e.interactionBlocked!==`covered`&&!t.has(e.ref)&&!r.has(e.ref)&&!tc.has(P(e.type??`Element`)));if(i.length===0)return{};let a=i.slice(0,20).map(e=>{let t=P(e.type??`Element`),n=N(e,t);return{ref:e.ref,role:t,...n?{label:n}:{}}});return{tail:a,...i.length>a.length?{tailTruncated:!0}:{}}}function rc(e){if(e.length<=80)return e;let t=e.filter(e=>e.kind===`added`),n=new Set(t.slice(0,80)),r=80-n.size,i=[];for(let t of e)n.has(t)?i.push(t):t.kind===`removed`&&r>0&&(i.push(t),--r);return i}function ic(e,t,n){return e.stalled?{hint:Ws}:e.settled?t?n<5?{hint:Is}:{}:{hint:`Settled on a sparse, unreadable tree — the diff is omitted and its refs/selectors are invalid. Use screenshot as visual truth and coordinate taps; retry snapshot after navigating.`}:{hint:Us}}async function ac(e,t,n){if(Ya(n.snapshot.snapshotQuality))return{stored:!1};let r=await e.sessions.get(t.session??`default`);return r?(await e.sessions.set({...r,snapshot:n.snapshot}),{stored:!0,session:r}):{stored:!1}}function oc(e){let t=e.verify===!0;return{verify:t,needsPreActionBaseline:t||e.settle!==void 0,...e.settle===void 0?{}:{settle:e.settle}}}async function sc(e,t,n,r,i){let a=await cc(e,t,n,i);return uc({...r,...a})}async function cc(e,t,n,r){if(r.settle!==void 0){let i=await Gs(e,t,{...r.settle,resolved:n}),a=r.verify?Ys(i.settledNodes,`preActionNodes`in n?n.preActionNodes:void 0):void 0;return{settle:i.observation,...a?{evidence:a}:{}}}if(!r.verify)return{};let i=await lc(e,t,n);return i?{evidence:i}:{}}async function lc(e,t,n){let r=`preActionNodes`in n?n.preActionNodes:void 0;try{let n=H((await Z(e,t,!0)).snapshot.nodes),i=r!==void 0&&n.digest!==H(r).digest;return{...n,changedFromBefore:i}}catch{return}}function uc(e){let t=e;if(t.targetHittable!==!1||!dc(t)||t.hint===void 0)return e;let{hint:n,...r}=t;return r}function dc(e){if(e.evidence?.changedFromBefore===!0)return!0;let t=e.settle?.diff?.summary;return!!t&&(t.additions>0||t.removals>0)}function fc(e,t){let r=e.filter(t=>Ae(t,e)).map(e=>e.rect).filter(pc),i=r.length>0?r:e.map(e=>e.rect).filter(pc);if(i.length===0)throw new n(`COMMAND_FAILED`,`Cannot infer viewport for ${t}`);let a=Math.min(...i.map(e=>e.x)),o=Math.min(...i.map(e=>e.y)),s=Math.max(...i.map(e=>e.x+e.width)),c=Math.max(...i.map(e=>e.y+e.height));return{x:a,y:o,width:s-a,height:c-o}}function pc(e){return!!(e&&e.width>0&&e.height>0)}async function mc(e,t){return await e.backend.resolveGestureViewport?.(z(e,t))||fc((await Z(e,t,!1)).snapshot.nodes,`gesture`)}const hc=async(e,t)=>{let r=await X(e,t,{action:`focus`,requireInteractive:!0,promoteToHittableAncestor:!1});if(!e.backend.focus)throw new n(`UNSUPPORTED_OPERATION`,`focus is not supported by this backend`);let i=$(r),a=V(await e.backend.focus(z(e,t),i));return{...r,...a?{backendResult:a}:{},...w(`Focused (${i.x}, ${i.y})`)}},gc=async(e,t)=>{let r=oc(t),i=await X(e,t,{action:`longPress`,requireInteractive:!0,promoteToHittableAncestor:!0,captureEvidenceBaseline:r.needsPreActionBaseline,expectedResolvedTarget:t.expectedResolvedTarget});if(!e.backend.longPress)throw new n(`UNSUPPORTED_OPERATION`,`longPress is not supported by this backend`);let a=t.durationMs===void 0?void 0:zi(t.durationMs,`durationMs`,0,12e4),o=$(i),s=V(await e.backend.longPress(z(e,t),o,{durationMs:a}));return await sc(e,t,i,{...i,...a===void 0?{}:{durationMs:a},...s?{backendResult:s}:{},...w(`Long pressed (${o.x}, ${o.y})`)},r)},_c=async(e,t)=>{if(!e.backend.performGesture)throw new n(`UNSUPPORTED_OPERATION`,`gesture is not supported by this backend`);await Zo(e,t,`drag`);let r=await mc(e,t),i=await vc(e,t,`source`),a=await vc(e,t,`destination`),o=u({from:$(i),to:$(a),sourceHoldMs:t.gesture.sourceHoldMs,moveMs:t.gesture.moveMs,destinationHoldMs:t.gesture.destinationHoldMs},r),s=V(await e.backend.performGesture(z(e,t),o)),{start:c,end:d}=l(o);return{kind:`drag`,durationMs:o.durationMs,pointerCount:1,from:c,to:d,targets:{source:yc(i),destination:yc(a)},recording:bc(i,a),...s?{backendResult:s}:{},...w(`Dragged ${t.gesture.source} to ${t.gesture.destination}`)}};async function vc(e,t,n){let r=t.gesture[n];return await X(e,{...t,target:r.startsWith(`@`)?{kind:`ref`,ref:r}:{kind:`selector`,selector:r}},{action:`drag`,requireInteractive:!1,promoteToHittableAncestor:!1,expectedResolvedTarget:t.expectedResolvedTargets?.[n],replayTargetRole:n})}function yc(e){if(e.kind===`point`||!e.resolution)throw new n(`COMMAND_FAILED`,`gesture drag target resolution was not disclosed`);let t=`selectorChain`in e?e.selectorChain:void 0;return{...t?.length?{selectorChain:t}:{},resolution:e.resolution}}function bc(e,t){let n=xc(e),r=xc(t),i=Sc(e),a=Sc(t);return{...n?{sourceSelector:n}:{},...r?{destinationSelector:r}:{},...i?{sourceTarget:i}:{},...a?{destinationTarget:a}:{}}}function xc(e){return`selectorChain`in e&&e.selectorChain?.length?e.selectorChain.join(` || `):void 0}function Sc(e){if(!(!(`selectorChain`in e)||!e.selectorChain?.length||!e.node||!e.preActionNodes))return{selectorChain:e.selectorChain,node:e.node,preActionNodes:e.preActionNodes}}const Cc=async(e,t)=>{if(!e.backend.scroll)throw new n(`UNSUPPORTED_OPERATION`,`scroll is not supported by this backend`);let r=Tc(t.direction),i=kc(t.amount,`scroll amount`),a=jc(t.pixels,`scroll pixels`),o=d(t.durationMs);c({amount:i,pixels:a},`scroll accepts either amount or pixels, not both`);let s=await wc(e,t),l=s.kind===`viewport`?{kind:`viewport`}:{kind:`point`,point:$(s)},u=e.backend.scroll,f=async()=>await u(z(e,t),l,{direction:r.direction,...i===void 0?{}:{amount:i},...a===void 0?{}:{pixels:a},...o===void 0?{}:{durationMs:o}}),p,m=0;if(r.edge){let n=r.edge,i=Ec(s),a=await Ti({edge:n,captureState:async r=>await Dc(e,t,n,i,r),scroll:f});p=a.result,m=a.passes}else p=await f(),m=1;let h=V(p),_=g(h);return{...s,direction:r.direction,...r.edge?{edge:r.edge,passes:m}:{},...i===void 0?{}:{amount:i},...a===void 0?{}:{pixels:a},..._===void 0?{}:{durationMs:_},...h?{backendResult:h}:{},...w(Ei(r.direction,r.edge,m,i,a))}};async function wc(e,t){let n=t.target??{kind:`viewport`};return n.kind===`viewport`?(await Zo(e,t,`scroll`),{kind:`viewport`}):await X(e,{...t,target:n},{action:`scroll`,requireInteractive:!1,promoteToHittableAncestor:!1})}function Tc(e){return e===`bottom`?{direction:`down`,edge:`bottom`}:e===`top`?{direction:`up`,edge:`top`}:{direction:Oc(e,`scroll direction`)}}function Ec(e){return e.kind===`viewport`?{}:{point:e.point,nodeIndex:`node`in e?e.node?.index:void 0}}function $(e){if(!e.point)throw new n(`COMMAND_FAILED`,`Interaction target resolved without coordinates`);return e.point}async function Dc(e,t,r,i,a){if(!e.backend.captureSnapshot)throw new n(`UNSUPPORTED_OPERATION`,`scroll ${r} requires snapshot support to verify hidden content before scrolling`);let{captureSnapshot:o}=e.backend;return await wi({edge:r,target:i,scope:a,captureNodes:async n=>{let r=await o(z(e,t),{scope:n});return r.snapshot?.nodes??r.nodes??[]}})}function Oc(e,t){switch(e){case`up`:case`down`:case`left`:case`right`:return e;default:throw new n(`INVALID_ARGS`,`${t} must be up, down, left, or right`)}}function kc(e,t){return e===void 0?void 0:Ac(e,t)}function Ac(e,t){if(!Number.isFinite(e)||e<=0)throw new n(`INVALID_ARGS`,`${t} must be a positive number`);return e}function jc(e,t){if(e!==void 0){if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw new n(`INVALID_ARGS`,`${t} must be a positive integer`);return e}}const Mc=/^e\d+$/;function Nc(e){if(e[0]?.startsWith(`@`)){let t=Hc(e.slice(1));return{ref:e[0],...t===void 0?{}:{label:t}}}if(Mc.test(e[0]??``))throw new n(`INVALID_ARGS`,`Did you mean "@${e[0]}"? Snapshot refs need the @ prefix.`);let t=Me(e);if(t){if(t.rest.length>0)throw new n(`INVALID_ARGS`,zc(e,t));return{selector:t.selectorExpression}}return Fc(e)}function Pc(e){let t=e[0];if(t?.startsWith(`@`)){let n=e.length>=3?e.slice(2).join(` `):e.slice(1).join(` `);return{kind:`ref`,target:{ref:t,label:e.length>=3?Hc(e.slice(1,2)):void 0},text:n}}if(Mc.test(t??``))throw new n(`INVALID_ARGS`,`Did you mean "@${t}"? Snapshot refs need the @ prefix.`);let r=Me(e,{preferTrailingValue:!0});return r?{kind:`selector`,target:{selector:r.selectorExpression},text:r.rest.join(` `)}:{kind:`point`,target:Fc(e.slice(0,2)),text:e.slice(2).join(` `)}}function Fc(e){let t=e[0]??``,r=Se(t);if(r){let i=Ic(t)?r.value:[r.value,...e.slice(1)].join(` `).trim();throw new n(`INVALID_ARGS`,Lc({key:r.key,value:i}))}let i=Number(e[0]),a=Number(e[1]);if(Number.isFinite(i)&&Number.isFinite(a))return{x:i,y:a};throw new n(`INVALID_ARGS`,Rc(e))}function Ic(e){let t=e.slice(e.indexOf(`=`)+1).trim();if(t.length<2)return!1;let n=t[0];return(n===`"`||n===`'`)&&t.endsWith(n)}function Lc(e){let{key:t,value:n}=e;return`Unknown selector key "${t}". Supported: ${De.join(`, `)}. ${xe(t)?`Did you mean role=${t} label=${Vc(n)}?`:`Did you mean label=${Vc(n)}?`}`}function Rc(e){let t=e.filter(e=>e!==void 0).join(` `);if(!t.trim())return`Missing target. Pass an @ref from snapshot, a selector like text="Sign in", or "x y" coordinates.`;let n=`Target "${t}" is not a @ref, selector, or "x y" point.`;return e.some(e=>ye(e??``))?`${n} Selector values with spaces need quotes, e.g. text="Sign in".`:`${n} To match by visible text, use text=${Vc(t)} (or label=/id=/role=), or pass an @ref from snapshot.`}function zc(e,t){return`${`Selector ${t.selectorExpression} is followed by unexpected extra arguments: "${t.rest.join(` `)}".`} Selector values with spaces need quotes, e.g. ${Bc(e,t)??`text="Sign in"`}.`}function Bc(e,t){let n=e.length-t.rest.length,r=e[n-1];if(r===void 0)return;let i=r.indexOf(`=`);if(i<=0)return;let a=[r.slice(i+1),...t.rest].join(` `),o=`${r.slice(0,i+1)}${Vc(a)}`;return[...e.slice(0,n-1),o].join(` `)}function Vc(e){return`"${e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}"`}function Hc(e){return e.join(` `).trim()||void 0}function Uc(e,t={}){let n=I(process.stderr);if(e===`pass`){let e=t.passFormat??`green`;return n?Wc(`✓`,e):`✓`}return e===`fail`?n?Wc(`⨯`,`red`):`⨯`:e===`warn`?n?Wc(`!`,`yellow`):`!`:n?Wc(`-`,`dim`):`-`}function Wc(e,t){return L(e,t,{validateStream:!1})}function Gc(e){return`${Uc(qc(e.status))} ${Jc(e)}`}function Kc(e){return e.status!==`fail`&&e.status!==`warn`?[]:typeof e.command==`string`?[` run: ${e.command}`]:typeof e.hint==`string`?[` hint: ${e.hint}`]:[]}function qc(e){return e===`pass`?`pass`:e===`fail`?`fail`:e===`warn`?`warn`:`skip`}function Jc(e){let t=typeof e.id==`string`&&e.id.length>0?e.id:`check`,n=typeof e.summary==`string`&&e.summary.length>0?e.summary:t;return n===t?t:`${t}: ${n}`}let Yc=!1;function Xc(){Yc=!0}function Zc(){let e=Yc;return Yc=!1,e}function Qc(e,t){let r=e===void 0?NaN:Number(e);if(!Number.isInteger(r)||r<1)throw new n(`INVALID_ARGS`,`viewport ${t} must be a positive integer`);return r}const $c=[`auto`,`react-native`,`expo`,`repack`];function el(e){if(e!==void 0){if($c.includes(e))return e;throw new n(`INVALID_ARGS`,`metro prepare --kind must be auto, react-native, expo, or repack`)}}export{Xi as $,Ct as $t,X as A,Yt as At,ro as B,$t as Bt,gs as C,Je as Cn,M as Ct,Do as D,Ze as Dn,er as Dt,Lo as E,Ye as En,sr as Et,so as F,Vt as Ft,Y as G,It as Gt,Qa as H,rn as Ht,uo as I,Qt as It,ia as J,Pt as Jt,ca as K,Ft as Kt,ao as L,Xt as Lt,To as M,Jt as Mt,co as N,Rt as Nt,Zo as O,Xe as On,zn as Ot,lo as P,Zt as Pt,K as Q,kt as Qt,oo as R,Bt as Rt,As as S,We as Sn,P as St,ds as T,Qe as Tn,tr as Tt,Xa as U,tn as Ut,qa as V,nn as Vt,Aa as W,Lt as Wt,Qi as X,Tt as Xt,ra as Y,Et as Yt,ta as Z,At as Zt,Ks as _,T as _n,Ur as _t,Kc as a,it as an,H as at,Fs as b,$e as bn,I as bt,Pc as c,mt as cn,B as ct,hc as d,ft as dn,wi as dt,wt as en,Yi as et,gc as f,pt as fn,Ei as ft,oc as g,w as gn,ni as gt,sc as h,nt as hn,ri as ht,Xc as i,rt as in,U as it,wo as j,zt as jt,ss as k,Ke as kn,Vn as kt,Nc as l,ut as ln,z as lt,Cc as m,ht as mn,L as mt,Qc as n,_t as nn,G as nt,Gc as o,lt as on,Vi as ot,mc as p,st as pn,Ti as pt,q,Mt as qt,Zc as r,St as rn,qi as rt,Uc as s,dt as sn,V as st,el as t,vt as tn,Zi as tt,_c as u,ct as un,zi as ut,Is as v,He as vn,Hr as vt,us as w,qe as wn,ar as wt,js as x,Ge as xn,N as xt,Ls as y,et as yn,Vr as yt,Ya as z,en as zt};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./version.js";import{
|
|
1
|
+
import{n as e}from"./version.js";import{v as t}from"./sdk-android-adb.js";import{t as n}from"./src3.js";const r=n({clientVersion:e(),runHostCommand:async(e,n)=>({stdout:(await t(e,[...n],{maxBuffer:10*1024*1024,timeoutMs:3e4})).stdout})});export{r as t};
|
package/dist/src/proxy.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{S as e,_ as t}from"./sdk-contracts.js";import{bt as n,mt as r}from"./prepare-kind.js";import{a as i,i as a}from"./agent-device-client.js";import{
|
|
1
|
+
import{S as e,_ as t}from"./sdk-contracts.js";import{bt as n,mt as r}from"./prepare-kind.js";import{a as i,i as a}from"./agent-device-client.js";import{ct as o,dt as s,lt as c,ot as l,pt as u,r as d,st as f}from"./screenshot-result.js";import{t as p}from"./timing-safe-equal.js";import{t as m}from"./shared.js";import{randomBytes as h,randomUUID as g}from"node:crypto";import{pipeline as ee}from"node:stream/promises";import{Readable as _}from"node:stream";import v from"node:http";const y=`${l}/`,b=[`content-type`,`content-range`,`x-artifact-type`,`x-artifact-filename`,`x-artifact-hash`,`x-artifact-hash-algorithm`,f],x=[`content-type`,`content-disposition`,`x-request-id`];function S(e){let t=P(e);return v.createServer((e,n)=>{C(e,n,t).catch(e=>{X(n,e)})})}async function C(e,t,n){let r=te(e.url??`/`);if(e.method===`GET`&&r===`/health`){await w(t,n);return}if(!L(r,e.method)){t.statusCode=404,t.end(`Not found`);return}let i;if(r===`/rpc`&&(i=(await u(e,n.maxRpcBodyBytes,`Proxy request body is too large.`)).toString(`utf8`)),!U(e,n.clientToken,i)){Y(t,r,q(i));return}await E({req:e,res:t,route:r,options:n,rpcBody:i})}async function w(e,t){let n=await T(t);e.statusCode=200,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify(d(`agent-device-proxy`,{upstream:n})))}async function T(e){let t=new URL(s(e.upstreamBaseUrl,`health`)),n=await e.fetchImpl(t,{method:`GET`,headers:V({headers:{}},e.upstreamToken,`/health`),signal:AbortSignal.timeout(e.upstreamTimeoutMs)}),r=await n.text();try{return r?JSON.parse(r):{ok:n.ok,status:n.status}}catch{return{ok:n.ok,status:n.status}}}async function E(e){let{req:t,res:n,route:r,options:i,rpcBody:a}=e,o=B(i.upstreamBaseUrl,r,t.url??`/`),s=t.method??`GET`,c=V(t,i.upstreamToken,r),l=H(t,r,a,i.upstreamToken);await D({req:t,res:n,route:r,response:await i.fetchImpl(o,{method:s,headers:c,signal:AbortSignal.timeout(i.upstreamTimeoutMs),...l?{body:l,duplex:`half`}:{}}),clientToken:i.clientToken})}async function D(e){let{req:t,res:n,route:r,response:i,clientToken:a}=e;if(n.statusCode=i.status,O(i,n),k(t,n),z(r)){await A({req:t,res:n,response:i,clientToken:a});return}await N(i,n)}function O(e,t){for(let n of x){let r=e.headers.get(n);r&&t.setHeader(n,r)}}function k(e,t){t.hasHeader(`x-request-id`)||t.setHeader(`x-request-id`,J(e))}async function A(e){let{req:t,res:n,response:r,clientToken:i}=e,a=await r.text();n.setHeader(`content-type`,r.headers.get(`content-type`)??`application/json`),n.end(j(a,t,i))}function j(e,t,n){let r;try{r=JSON.parse(e)}catch{return e}if(!r||typeof r!=`object`)return e;let i=r;if(!i.upload||typeof i.upload.url!=`string`)return e;let a=M(i.upload.url,t);if(!a)return e;let s=i.upload.headers&&typeof i.upload.headers==`object`?{...i.upload.headers}:{};return Object.assign(s,o(n)),JSON.stringify({...r,upload:{...i.upload,url:a,headers:s}})}function M(e,t){let n;try{n=new URL(e)}catch{return null}if(!n.pathname.startsWith(`/upload/`))return null;let r=typeof t.headers.host==`string`?t.headers.host:``;if(!r)return null;let i=new URL(t.url??`/`,`http://127.0.0.1`).pathname,a=i.lastIndexOf(`/upload/preflight`),o=a>=0?i.slice(0,a):``,s=t.headers[`x-forwarded-proto`],c=Array.isArray(s)?s[0]:s,l=new URL(`${c||`http`}://${r}`);return l.pathname=`${o}${n.pathname}`,l.search=n.search,l.toString()}async function N(e,t){if(!e.body){t.end();return}await ee(_.fromWeb(e.body),t)}function P(e){return{upstreamBaseUrl:F(e.upstreamBaseUrl,`upstreamBaseUrl`),upstreamToken:I(e.upstreamToken,`upstreamToken`),clientToken:I(e.clientToken,`clientToken`),maxRpcBodyBytes:e.maxRpcBodyBytes??1048576,upstreamTimeoutMs:e.upstreamTimeoutMs??3e5,fetchImpl:e.fetchImpl??fetch}}function F(e,n){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`unsupported protocol`);return t.toString().replace(/\/+$/,``)}catch(r){throw new t(`INVALID_ARGS`,`Invalid ${n}`,{[n]:e},r)}}function I(e,n){let r=e.trim();if(!r)throw new t(`INVALID_ARGS`,`Proxy ${n} is required.`);return r}function te(e){let t=new URL(e,`http://127.0.0.1`).pathname;return t===`/agent-device`?`/`:t.startsWith(y)?`/${t.slice(y.length)}`:t}function L(e,t){return e===`/rpc`?t===`POST`:R(e,t)?!0:e===`/artifacts`||e===`/artifacts/`||e.startsWith(`/artifacts/`)?t===`GET`:!1}function R(e,t){return e===`/upload`||z(e)||e===`/upload/finalize`?t===`POST`:e.startsWith(`/upload/direct/`)?t===`PUT`:!1}function z(e){return e===`/upload/preflight`}function B(e,t,n){let r=new URL(s(e,t)),i=n.indexOf(`?`);return i>=0&&(r.search=n.slice(i)),r}function V(e,t,n){let r=new Headers;for(let t of b){let n=e.headers[t];typeof n==`string`&&n.trim()&&r.set(t,n)}n===`/rpc`&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);for(let[e,n]of Object.entries(o(t)))r.set(e,n);return r}function H(e,t,n,r){if(!(e.method===`GET`||e.method===`HEAD`))return t===`/rpc`?G(n??``,r):e}function U(e,t,n){let r=W(e,n);return r.length>0&&p(r,t)}function W(e,t){let n=typeof e.headers.authorization==`string`?e.headers.authorization:``;if(n.toLowerCase().startsWith(`bearer `))return n.slice(7);let r=e.headers[`x-agent-device-token`];if(typeof r==`string`)return r;if(t){let e=K(t);if(e)return e}return``}function G(e,t){let n=JSON.parse(e);return n.params={...n.params??{},token:t},JSON.stringify(n)}function K(e){try{let t=JSON.parse(e);return typeof t.params?.token==`string`?t.params.token:``}catch{return``}}function q(e){if(!e)return null;try{return JSON.parse(e).id??null}catch{return null}}function J(e){let t=e.headers[`x-request-id`];return typeof t==`string`&&t.trim()?t.trim().slice(0,128):g()}function Y(n,r,i){if(n.statusCode=401,n.setHeader(`content-type`,`application/json`),r===`/rpc`){n.end(JSON.stringify({jsonrpc:`2.0`,id:i,error:{code:-32001,message:`Invalid proxy token`,data:e(new t(`UNAUTHORIZED`,`Invalid proxy token`))}}));return}n.end(JSON.stringify({ok:!1,error:`Invalid proxy token`,code:`UNAUTHORIZED`}))}function X(t,n){if(t.headersSent){t.destroy(n instanceof Error?n:void 0);return}let r=e(n);t.statusCode=r.code===`INVALID_ARGS`?400:500,t.setHeader(`content-type`,`application/json`),t.end(JSON.stringify({ok:!1,error:r.message,code:r.code}))}const Z=async({positionals:e,flags:n})=>{if(e.length>0)throw new t(`INVALID_ARGS`,`proxy does not accept positional arguments.`);let r=await Q(n);return m(n,r,()=>oe(r)),await se(),!0};async function Q(e){let n=i({session:`default`,command:`proxy`,positionals:[],flags:{stateDir:e.stateDir,daemonBaseUrl:``,daemonTransport:`http`,daemonServerMode:`http`}}),r=await a(n),o=ne(r.info.httpPort),s=re(e),l=S({upstreamBaseUrl:o,upstreamToken:r.info.token,clientToken:s});await ie(l,e.proxyHost?.trim()||`127.0.0.1`,e.proxyPort??0);let u=l.address();if(!u||typeof u==`string`)throw new t(`COMMAND_FAILED`,`Proxy did not bind to a TCP address.`);let d=`http://${ae(u.address)}:${u.port}`;return{proxyBaseUrl:d,agentDeviceBaseUrl:c(d),token:s,upstreamBaseUrl:o,stateDir:n.paths.baseDir}}function ne(e){if(!e)throw new t(`COMMAND_FAILED`,`Local daemon HTTP endpoint is unavailable.`,{hint:`Retry after cleaning daemon state, or run proxy with a fresh --state-dir.`});return`http://127.0.0.1:${e}`}function re(e){return e.daemonAuthToken?.trim()||h(32).toString(`hex`)}function ie(e,t,n){return new Promise((r,i)=>{e.once(`error`,i),e.listen(n,t,()=>{e.off(`error`,i),r()})})}function ae(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function oe(e,t={}){let r=t.useColor??n(),i=$(`✓`,`green`,r),a=$(e.proxyBaseUrl,`cyan`,r),o=$(`<tunnel URL>`,`cyan`,r),s=$(e.token,`yellow`,r);return[`${i} Proxy listening at ${a}`,``,`Provide this to the agent-device instance connecting:`,``,`Daemon base URL: ${o}`,`Daemon auth token: ${s}`].join(`
|
|
2
2
|
`)}function $(e,t,n){return n?r(e,t,{validateStream:!1}):e}function se(){return new Promise(()=>{})}export{Z as proxyCommand};
|
package/dist/src/react-native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{S as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{S as e}from"./sdk-contracts.js";import{nr as t}from"./sdk-batch-runner.js";import{Xt as n,gn as r,z as i}from"./prepare-kind.js";import{p as a}from"./runtime.js";import{c as o,o as s,s as c,t as l}from"./dispatch.js";import{tn as u}from"./internal/daemon.js";import{t as d}from"./interaction-snapshot.js";import{r as f,t as p}from"./interaction-touch-reference-frame.js";async function m(t){let{req:r,sessionName:s,sessionStore:l}=t;if(r.command!==n.reactNative)return null;let u=h(r.positionals??[]);if(!u.ok)return u.response;let f=l.get(s);if(!f)return c();let p=o(n.reactNative,f.device,{message:`react-native dismiss-overlay is not supported on this device`});if(p)return p;try{let e=await d(f,r.flags,l,t.contextFromFlags,{interactiveOnly:!0});if(i(e.snapshotQuality))return _(e.snapshotQuality);let n=a(e.nodes),o=n.primaryAction;return o?await v(t,f,e,o):g(n.detected)}catch(t){return{ok:!1,error:e(t)}}}function h(e){return e.length===1&&e[0]===`dismiss-overlay`?{ok:!0}:{ok:!1,response:s(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}}function g(e){return e?s(`COMMAND_FAILED`,`React Native overlay detected, but no safe dismiss target was found`,{hint:`Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`}):{ok:!0,data:{action:`dismiss-overlay`,detected:!1,dismissed:!1,...r(`No React Native overlay detected`)}}}function _(e){return s(`COMMAND_FAILED`,`React Native overlay state could not be determined because the accessibility tree is unreadable`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth; if an overlay is visible, report it or navigate with coordinates, then retry snapshot or dismiss-overlay on a readable screen.`})}async function v(e,n,i,a){let{req:o,sessionStore:s}=e,c=Date.now();u(n);let d=await l(n.device,`press`,[String(a.point.x),String(a.point.y)],o.flags?.out,e.contextFromFlags(o.flags,n.appBundleId,n.trace?.outPath))??{},m=Date.now(),h=await y(e,n),g=t({...p(i.nodes),...d,action:`dismiss-overlay`,overlayAction:a.action,x:a.point.x,y:a.point.y,ref:a.ref,label:a.label,warning:a.warning,dismissed:!0,verified:h.verified,verificationRequired:!h.verified,verificationWarning:h.verificationWarning,nextCommand:h.nextCommand,...r(b(h))});return f({session:n,sessionStore:s,command:o.command,positionals:o.positionals??[],flags:o.flags,result:g,responseData:g,actionStartedAt:c,actionFinishedAt:m})}async function y(e,t){let{req:n,sessionStore:r}=e,o=await d(t,n.flags,r,e.contextFromFlags,{interactiveOnly:!0});return i(o.snapshotQuality)?{verified:!1,verificationWarning:`React Native overlay dismissal could not be verified because the post-dismiss accessibility tree is unreadable. Use screenshot as visual truth.`,nextCommand:`agent-device screenshot`}:a(o.nodes).detected?{verified:!1,verificationWarning:`React Native overlay is still detected after dismissal. Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`,nextCommand:`agent-device screenshot --overlay-refs`}:{verified:!0}}function b(e){return e.verified?`React Native overlay dismiss action sent and verified gone`:`React Native overlay dismiss action sent, but verification still detects an overlay`}export{m as handleReactNativeCommands};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{S as e,_ as t}from"./sdk-contracts.js";import{Mt as n}from"./version.js";import{M as r,N as i,j as a}from"./sdk-batch-runner.js";import{C as o,E as s}from"./sdk-device.js";import{en as c,nn as l,rn as u}from"./prepare-kind.js";import{i as d}from"./output-path.js";import{g as f}from"./dispatch.js";import{Mt as p,Pt as m,d as h,f as g,l as _,u as v}from"./internal/daemon.js";import{t as y}from"./device-ready.js";import{t as b}from"./handler-utils.js";import{t as x}from"./recording-telemetry.js";import S from"node:path";function C(e){let r=n(`record`,e.flags);if(r)throw new t(`INVALID_ARGS`,r);let i=e.flags?.fps;if(i!==void 0&&(!Number.isInteger(i)||i<1||i>120))throw new t(`INVALID_ARGS`,`fps must be an integer between 1 and 120`);let a=u(e.flags?.quality);if(e.flags?.quality!==void 0&&a===void 0)throw new t(`INVALID_ARGS`,`quality must be one of: ${l.join(`, `)} (legacy numeric values 5-10 are accepted)`);return{scope:w(e.flags?.recordingScope),...i===void 0?{}:{fps:i},...a===void 0?{}:{exportQuality:a},showTouches:e.flags?.hideTouches!==!0,hideTouchesRequested:e.flags?.hideTouches===!0}}function w(e){if(e===void 0)return`app`;if(e===`app`||e===`device`||e===`system`)return e;throw new t(`INVALID_ARGS`,`record scope must be app, device, or system`)}function T(e){return{ok:!1,error:{code:`INVALID_ARGS`,message:p(e)?`record start with app scope and an explicit session requires an active app session; run open <app> first, or use --scope device to record the full screen`:`record start defaults to app scope and requires an active app session; run open <app> first, or use --scope device to record the full screen`}}}function E(e,t,n){return{ok:!0,data:{recording:`started`,outPath:e.clientOutPath??n,sessionStateDir:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,showTouches:e.showTouches}}}function D(e){return{action:`start`,...e.clientOutPath?{requestedFileName:S.basename(e.clientOutPath)}:{},showTouches:e.showTouches}}function O(e){return{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`record is not supported on this device`,hint:e.hint??`Select an Apple, Android, physical HarmonyOS, or web target that supports screen recording.`,details:{reason:e.reason}}}}function k(e){let t=[A(e)];if(e.chunks&&e.chunks.length>1&&t.push(...e.chunks.slice(1).map(e=>({field:`chunkPath`,artifactType:`screen-recording-chunk`,path:e.path,localPath:e.clientOutPath,fileName:S.basename(e.clientOutPath??e.path)}))),e.telemetryPath){let n=e.clientOutPath?x(e.clientOutPath):void 0;t.push({field:`telemetryPath`,artifactType:`screen-recording-telemetry`,path:e.telemetryPath,localPath:n,fileName:S.basename(e.telemetryPath)})}return{ok:!0,data:{recording:`stopped`,outPath:e.outPath,telemetryPath:e.telemetryPath,artifacts:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,durationMs:Math.max(0,e.completedAt-e.startedAt),showTouches:e.showTouches,warning:e.warning,overlayWarning:e.overlayWarning,chunks:e.chunks?.map(e=>({index:e.index,path:e.clientOutPath??e.path}))}}}function A(e){return{field:`outPath`,artifactType:`screen-recording`,path:e.outPath,localPath:e.clientOutPath,fileName:S.basename(e.clientOutPath??e.outPath)}}async function j(t){try{return await M(t)}catch(t){return{ok:!1,error:e(t)}}}async function M(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),{plan:a,scope:o}=N(t,i);if(a.kind===`start`&&!c(o)&&!i)return T(t);let s=await P(e,i);return a.kind===`start`?await F(e,s,C(t),a.use):await z(e,s,a.kind)}function N(e,t){let n=w(e.flags?.recordingScope);return{scope:n,plan:a({action:e.positionals?.[0],scope:n,hasLiveHandle:t?.screenRecording!==void 0})}}async function P(e,t){let n=t?.device??await f(e.req.flags??{});return await e.retainDeviceExecutionLock(n.id),t||(await y(n),H(e,n))}async function F(e,t,n,i){if(t.screenRecording)return{ok:!1,error:{code:`INVALID_ARGS`,message:`recording already in progress`}};let a=(await e.bindDevice(t.device,r)).facts.screenRecordingStart;if(!a.available)return O(a);let o=await e.bindDevice(t.device,i),{fence:s,outputPaths:c}=I(e,t),l=await o.operations.screenRecordingStart(L(e,t,n,s,c.outputPath));await _({admissionLedger:e.admissionLedger,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore,device:t.device,owner:o.owner,fence:s,...l,throwIfCanceled:e.throwIfCanceled});let u=e.sessionStore.get(e.sessionName)?.screenRecording;if(!u)throw TypeError(`Screen recording adoption did not publish a live handle`);let d=u.handle.inspect();return b(e.sessionStore,t,e.req,e.req.command,D(d)),E(d,e.sessionStore.ensureSessionDir(e.sessionName),c.requestedPath)}function I(e,t){let n=g.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName));return{fence:g.createNextFence({admissionLedger:e.admissionLedger,resourcePath:n,device:t.device}),outputPaths:d({requestedPath:e.req.positionals?.[1],platform:t.device.platform,cwd:e.req.meta?.cwd})}}function L(e,t,n,r,i){return{sessionId:e.sessionName,outputPath:i,clientOutputPath:e.req.meta?.clientArtifactPaths?.outPath,scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:n.hideTouchesRequested,recordOnlySession:t.recordOnlySession===!0,activeSessionApp:R(t),exportQuality:n.exportQuality,fps:n.fps,fence:r}}function R(e){if(e.appBundleId)return{bundleId:e.appBundleId,...e.appName?{name:e.appName}:{}}}async function z(e,t,n){let r;try{r=n===`stop-live`?await v({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore}):await V(e,t)}catch(n){throw B(e,t),n}let i=k(r);return b(e.sessionStore,t,e.req,e.req.command,{action:`stop`,outPath:r.outPath,...r.clientOutPath?{requestedFileName:S.basename(r.clientOutPath)}:{},showTouches:r.showTouches}),t.recordOnlySession&&e.sessionStore.delete(e.sessionName),i}function B(e,t){if(!t.recordOnlySession)return;let n=g.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),r=g.store.read(n);r.status===`decoded`&&r.envelope.lifecycle===`completed`&&e.sessionStore.delete(e.sessionName)}async function V(e,n){let r=g.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),a=g.store.read(r);if(a.status!==`decoded`||a.envelope.lifecycle!==`open`)throw new t(`INVALID_ARGS`,`no active recording`);if(a.envelope.sessionId!==e.sessionName)throw new t(`COMMAND_FAILED`,`Screen recording recovery record does not belong to the requested session`,{reason:`runtime-contract-invalid`});if(!s(a.envelope.device,o(n.device)))throw new t(`COMMAND_FAILED`,`Screen recording recovery device does not match the selected device`,{reason:`runtime-contract-invalid`});return await h({resourcePath:r,scope:e.requestScope,acquireControl:async(t,r)=>{let a=await e.bindExactDevice(n.device,t.owner,t.fence,i,r);return{reattach:async e=>await a.operations.screenRecordingReattach({envelope:e}),cleanup:async e=>await a.operations.screenRecordingCleanup({envelope:e}),[Symbol.asyncDispose]:async()=>{}}}})}function H(e,t){return{name:e.sessionName,sessionScope:m(e.req),device:t,createdAt:Date.now(),recordOnlySession:!0,actions:[]}}export{j as t};
|
package/dist/src/record-trace.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{x as e}from"./screenshot-result.js";import{
|
|
1
|
+
import{x as e}from"./screenshot-result.js";import{o as t}from"./dispatch.js";import{t as n}from"./handler-utils.js";import{t as r}from"./record-runtime.js";import i from"node:path";import a from"node:fs";function o(e){let n=(e.req.positionals?.[0]??``).toLowerCase();if(n!==`start`&&n!==`stop`)return t(`INVALID_ARGS`,`trace requires start|stop`);let r=e.sessionStore.get(e.sessionName);return r?n===`start`?s(e.req,e.sessionStore,r):c(e.req,e.sessionStore,r):t(`SESSION_NOT_FOUND`,`No active session`)}function s(r,o,s){if(s.trace)return t(`INVALID_ARGS`,`trace already in progress`);let c=e.expandHome(r.positionals?.[1]??o.defaultTracePath(s));return a.mkdirSync(i.dirname(c),{recursive:!0}),a.appendFileSync(c,``),s.trace={outPath:c,startedAt:Date.now()},n(o,s,r,r.command,{action:`start`,outPath:c}),{ok:!0,data:{trace:`started`,outPath:c}}}function c(e,r,a){if(!a.trace)return t(`INVALID_ARGS`,`no active trace`);let o=l(a.trace.outPath,e.positionals?.[1]);a.trace=void 0,n(r,a,e,e.command,{action:`stop`,outPath:o});let s=e.meta?.clientArtifactPaths?.outPath??o;return{ok:!0,data:{trace:`stopped`,outPath:o,artifacts:[{field:`outPath`,artifactType:`trace-log`,path:o,localPath:s,fileName:i.basename(s)}]}}}function l(t,n){if(!n)return t;let r=e.expandHome(n);return a.mkdirSync(i.dirname(r),{recursive:!0}),a.existsSync(t)?a.renameSync(t,r):a.appendFileSync(r,``),r}async function u(e){let{req:t,sessionName:n,sessionStore:i}=e,a=t.command;return a===`record`?r({req:t,sessionName:n,sessionStore:i,bindDevice:e.bindDevice,bindExactDevice:e.bindExactDevice,admissionLedger:e.admissionLedger,requestScope:e.requestScope,retainDeviceExecutionLock:e.retainDeviceExecutionLock,throwIfCanceled:e.throwIfCanceled}):a===`trace`?o({req:t,sessionName:n,sessionStore:i}):null}export{u as handleRecordTraceCommands};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"node:path";import t from"node:fs";function n(t){let n=e.parse(t);return e.join(n.dir,`${n.name}.gesture-telemetry.json`)}function r(e,t){return i(t>0?e.flatMap(e=>{let n=e.tMs-t,r=`durationMs`in e?e.durationMs:void 0;return(typeof r==`number`?n+r:n)<=0?[]:[{...e,tMs:Math.max(0,n)}]}):e)}function i(e){return[...e].sort((e,t)=>e.tMs-t.tMs)}function a(e){let i=n(e.videoPath),a={version:1,generatedAt:new Date().toISOString(),events:r(e.events,e.trimStartMs??0)};return t.writeFileSync(i,JSON.stringify(a,null,2)),i}function o(e){let{recording:t,trimStartMs:n}=e,r=a({videoPath:t.outPath,events:t.gestureEvents,trimStartMs:n});return t.telemetryPath=r,r}export{o as n,n as t};
|