agent-device 0.20.6 → 0.20.7

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.
Files changed (175) hide show
  1. package/README.md +3 -3
  2. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.6.apk → agent-device-android-ime-helper-0.20.7.apk} +0 -0
  3. package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.7.apk.sha256 +1 -0
  4. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.6.manifest.json → agent-device-android-ime-helper-0.20.7.manifest.json} +4 -4
  5. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.6.apk → agent-device-android-snapshot-helper-0.20.7.apk} +0 -0
  6. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.7.apk.sha256 +1 -0
  7. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.6.manifest.json → agent-device-android-snapshot-helper-0.20.7.manifest.json} +6 -6
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +20 -0
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +67 -0
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +339 -4
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSelectorMatchPolicy.swift +78 -0
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +31 -2
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +29 -7
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CoordinateTextEntryTests.swift +4 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +36 -28
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +7 -0
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SelectorMatchPolicyTests.swift +4 -0
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +2 -1
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +100 -12
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +4 -0
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +57 -0
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +1 -0
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +18 -3
  24. package/dist/src/agent-browser-tool.js +1 -1
  25. package/dist/src/agent-device-client.js +2 -2
  26. package/dist/src/android-adb.js +1 -1
  27. package/dist/src/android.js +1 -1
  28. package/dist/src/app-helpers.js +1 -1
  29. package/dist/src/app-lifecycle.js +7 -7
  30. package/dist/src/app-lifecycle2.js +2 -0
  31. package/dist/src/app-log-files.js +1 -0
  32. package/dist/src/app-log-reconnect.js +1 -0
  33. package/dist/src/app-log-runtime.js +4 -0
  34. package/dist/src/app-resolution.js +2 -1
  35. package/dist/src/apps.js +5 -5
  36. package/dist/src/audio-probe.js +1 -1
  37. package/dist/src/auth-session.js +1 -0
  38. package/dist/src/auth.js +2 -0
  39. package/dist/src/boot-diagnostics.js +2 -2
  40. package/dist/src/cli-config.js +1 -1
  41. package/dist/src/cli-grammar.js +1 -0
  42. package/dist/src/cli-help.js +199 -259
  43. package/dist/src/cli-output.js +1 -0
  44. package/dist/src/cli-runner.js +1 -2
  45. package/dist/src/cli.js +6 -16
  46. package/dist/src/client-metro.js +1 -1
  47. package/dist/src/cloud-artifacts.d.ts +2 -137
  48. package/dist/src/command-schema.js +3 -3
  49. package/dist/src/connection-runtime.js +1 -0
  50. package/dist/src/connection.js +5 -0
  51. package/dist/src/context.js +1 -1
  52. package/dist/src/daemon-shutdown-report.js +1 -0
  53. package/dist/src/daemon.js +2 -0
  54. package/dist/src/debug-symbols.js +3 -3
  55. package/dist/src/device-claim-inspection.js +1 -0
  56. package/dist/src/device-input-state.js +2 -2
  57. package/dist/src/device.js +1 -1
  58. package/dist/src/device2.js +2 -0
  59. package/dist/src/find.js +1 -1
  60. package/dist/src/finders.js +1 -1
  61. package/dist/src/generic-settle.js +1 -1
  62. package/dist/src/generic.js +1 -1
  63. package/dist/src/harmonyos.js +1 -0
  64. package/dist/src/helper.js +1 -1
  65. package/dist/src/host-process.js +2 -2
  66. package/dist/src/ime-lifecycle.js +7 -7
  67. package/dist/src/index.d.ts +43 -12
  68. package/dist/src/input-actions.js +4 -4
  69. package/dist/src/input-actions2.js +1 -1
  70. package/dist/src/input-actions3.js +1 -0
  71. package/dist/src/install-artifact.js +1 -5
  72. package/dist/src/install-artifact2.js +1 -1
  73. package/dist/src/install-source2.js +1 -1
  74. package/dist/src/interaction-runtime.js +1 -1
  75. package/dist/src/interaction-snapshot.js +1 -1
  76. package/dist/src/interaction-touch-reference-frame.js +1 -1
  77. package/dist/src/interaction.js +1 -1
  78. package/dist/src/interactor.js +2 -2
  79. package/dist/src/interactor2.js +1 -1
  80. package/dist/src/internal/bin.js +2 -2
  81. package/dist/src/internal/daemon.js +8 -15
  82. package/dist/src/inventory.js +5 -0
  83. package/dist/src/inventory2.js +1 -0
  84. package/dist/src/inventory3.js +2 -0
  85. package/dist/src/inventory4.js +1 -0
  86. package/dist/src/inventory5.js +1 -0
  87. package/dist/src/inventory6.js +1 -0
  88. package/dist/src/lease-context.js +1 -1
  89. package/dist/src/lease.js +1 -1
  90. package/dist/src/limrun-runtime-dependencies.js +1 -0
  91. package/dist/src/limrun.d.ts +10 -125
  92. package/dist/src/limrun.js +1 -1
  93. package/dist/src/linux.js +1 -1
  94. package/dist/src/logcat.js +1 -1
  95. package/dist/src/manifest.js +1 -1
  96. package/dist/src/owner-identity.js +1 -0
  97. package/dist/src/physical-device-control.js +1 -1
  98. package/dist/src/platform-runtime-app-log-android-transport.js +1 -0
  99. package/dist/src/platform-runtime-app-log-process.js +1 -0
  100. package/dist/src/platform-runtime-host.js +1 -0
  101. package/dist/src/platform-runtime-network-web-transport.js +1 -0
  102. package/dist/src/platform-runtime-operation-host.js +5 -0
  103. package/dist/src/platform-runtime-toolchain-host.js +1 -0
  104. package/dist/src/platform-runtime.js +1 -0
  105. package/dist/src/prepare-kind.js +15 -0
  106. package/dist/src/process-entry.js +1 -0
  107. package/dist/src/process-lock.js +1 -1
  108. package/dist/src/provider-webdriver.js +1 -0
  109. package/dist/src/provider.js +1 -0
  110. package/dist/src/proxy.js +2 -0
  111. package/dist/src/react-native.js +1 -1
  112. package/dist/src/record-trace.js +1 -1
  113. package/dist/src/registry.js +24 -24
  114. package/dist/src/remote-config2.js +1 -1
  115. package/dist/src/replay.js +3 -0
  116. package/dist/src/reporting.js +3 -3
  117. package/dist/src/runner-client.js +1 -1
  118. package/dist/src/runner-disposal.js +1 -1
  119. package/dist/src/runner-lease.js +1 -1
  120. package/dist/src/runtime.js +2 -2
  121. package/dist/src/runtime2.js +4 -0
  122. package/dist/src/runtime3.js +3 -0
  123. package/dist/src/runtime4.js +1 -0
  124. package/dist/src/runtime5.js +1 -0
  125. package/dist/src/runtime6.js +1 -0
  126. package/dist/src/runtime7.js +1 -0
  127. package/dist/src/screenshot-result.js +4 -4
  128. package/dist/src/screenshot.js +1 -0
  129. package/dist/src/sdk-android-adb.js +2 -2
  130. package/dist/src/sdk-batch-runner.js +3 -3
  131. package/dist/src/sdk-contracts.d.ts +31 -5
  132. package/dist/src/sdk-contracts.js +1 -1
  133. package/dist/src/sdk-device.js +1 -1
  134. package/dist/src/sdk-finders.js +1 -1
  135. package/dist/src/sdk-remote-config.js +1 -1
  136. package/dist/src/sdk-selectors.d.ts +280 -4
  137. package/dist/src/sdk-selectors.js +1 -1
  138. package/dist/src/selector-runtime.js +1 -1
  139. package/dist/src/selector-vocabulary.js +1 -1
  140. package/dist/src/selectors.js +1 -1
  141. package/dist/src/server.js +3 -3
  142. package/dist/src/session-target-evidence.js +1 -1
  143. package/dist/src/session.js +10 -9
  144. package/dist/src/shared.js +2 -0
  145. package/dist/src/shell-quote.js +1 -0
  146. package/dist/src/simulator.js +1 -1
  147. package/dist/src/snapshot-runtime.js +1 -0
  148. package/dist/src/snapshot-session.js +1 -0
  149. package/dist/src/snapshot.js +1 -1
  150. package/dist/src/snapshot2.js +1 -1
  151. package/dist/src/src.js +1 -1
  152. package/dist/src/src2.js +2 -0
  153. package/dist/src/src3.js +1 -0
  154. package/dist/src/text-surface.js +1 -1
  155. package/dist/src/timing-safe-equal.js +1 -0
  156. package/dist/src/tool-provider.js +3 -3
  157. package/dist/src/tool-provider2.js +1 -1
  158. package/dist/src/tool-provider3.js +1 -1
  159. package/dist/src/update-check.js +1 -1
  160. package/dist/src/version.js +1 -1
  161. package/dist/src/web.js +1 -1
  162. package/package.json +36 -20
  163. package/server.json +2 -2
  164. package/skills/agent-device/SKILL.md +6 -31
  165. package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.6.apk.sha256 +0 -1
  166. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.6.apk.sha256 +0 -1
  167. package/dist/src/app-log-request-scope.js +0 -1
  168. package/dist/src/devices.js +0 -1
  169. package/dist/src/devices2.js +0 -1
  170. package/dist/src/devices3.js +0 -1
  171. package/dist/src/devices4.js +0 -1
  172. package/dist/src/provider-limrun-runtime.js +0 -1
  173. package/dist/src/register-builtins.js +0 -1
  174. package/dist/src/screenshot-geometry.js +0 -1
  175. package/dist/src/viewport-dimension.js +0 -15
@@ -0,0 +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 ur(e,t){if(typeof e!=`string`)return[];let n=pr(e,t);return[`Repair hint: ${e}${n?` — ${n}`:``}`]}function dr(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 fr(e){return e?.repairSessionHeld===!0}function pr(e,t){let n=mr(e,dr(t));if(n!==void 0)return fr(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 mr(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). ${gr(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. ${gr(t)}`;case`caution`:return hr({lead:`something already matches the recorded selector; a blind re-press may repeat the mistake.`,guidance:t});case`manual`:return hr({lead:`no safe automated repair could be proven; inspect the screen and repair by hand.`,guidance:t});default:return}}function hr(e){let{lead:t,guidance:n}=e;if(!n?.allowed)return`${t} ${gr(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 gr(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 _r(e,t){if(typeof e!=`string`||e===`action-failure`)return[];let n=t;return n?[vr(e,n.matchCount),...yr(n.mismatches),...br(n.candidates)]:[]}function vr(e,t){return`Target binding: ${e}${typeof t==`number`?` (matchCount ${t})`:``} — recorded target evidence did not verify.`}function yr(e){return!Array.isArray(e)||e.length===0?[]:[` mismatches: ${e.slice(0,5).join(`; `)}`]}function br(e){return!Array.isArray(e)||e.length===0?[]:[` ${e.length} candidate(s) shared the recorded identity:`,...e.slice(0,5).map(e=>` ${Tr(e)}`)]}function xr(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 Sr(e){let t=e;return t?.state===`available`&&Array.isArray(t.refs)?Cr(t.refs,t.refsGeneration):t?.state===`unavailable`?[wr(t)]:[]}function Cr(e,t){let n=e.slice(0,8).map(Tr),r=e.length-n.length;return[`Screen: ${e.length} actionable ref(s) captured (refsGeneration ${t}).`,...n,...r>0?[` ... ${r} more`]:[]]}function wr(e){let t=typeof e.hint==`string`&&e.hint.length>0?` ${e.hint}`:``;return`Screen: unavailable (${String(e.reason??`unknown`)}).${t}`}function Tr(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` @${String(t.ref)} [${String(t.role)}]${n}`}function Er(e,t){return Array.isArray(e)&&e.length>0?[`Suggestions:`,...e.slice(0,5).map(Dr)]:typeof t==`number`&&t>0?[`Suggestions: ${t} available (omitted at this response level; rerun with --json for the full report).`]:[]}function Dr(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` - [${String(t.basis)}]${n} ${String(t.selector)}`}function Or(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 kr={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 Ar(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=ze(e,a),s=Lr(e,a,i,o),c=` `.repeat(t),l=e.ref?`@${e.ref}`:``,u=Rr(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=jr(e);return n?`${c}${l} [${a}]${d}${p}`.trimEnd():`${c}${l} [${a}]${f}${d}${p}`.trimEnd()}function jr(e){let t=e.actions?.filter(e=>e.trim().length>0);return!t||t.length===0?``:` actions: [${t.map(e=>`"${Vr(Mr(e))}"`).join(`, `)}]`}function Mr(e){return e.replace(/\s+/g,` `).replace(/[\u0000-\u001f\u007f-\u009f]/g,``).trim()}function N(e,t){let n=e.label?.trim();if(n&&Fr(t,n))return``;let r=e.value?.trim();if(Pr(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||Ir(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`:Nr(n)||n||`element`}function Nr(e){return Object.prototype.hasOwnProperty.call(kr,e)?kr[e]:void 0}function Pr(e){return e===`text-field`||e===`text-view`||e===`search`}function Fr(e,t){return e!==`scroll-area`&&e!==`list`&&e!==`collection`&&e!==`table`?!1:ne(t)}function Ir(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function Lr(e,t,n,r){return!n.summarizeTextSurfaces||!r.shouldSummarize?N(e,t):zr(e,t,r.text)||N(e,t)}function Rr(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`),Pr(t)&&i.push(`editable`),Br(e,t)&&i.push(`scrollable`),!r.shouldSummarize)?Hr(i):(i.push(`preview:"${Vr(Ve(r.text))}"`),i.push(`truncated`),Hr(i))}function zr(e,t,n){let r=Re(e.label);if(r&&r!==n)return r;let i=Re(e.identifier);if(i&&!Ir(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 Br(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 Vr(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Hr(e){return[...new Set(e)]}function Ur(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}function Wr(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=Vn(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=lr(i.details);o&&process.stderr.write(`${o}\n`),r.showDetails&&i.details&&process.stderr.write(`${JSON.stringify(i.details,null,2)}\n`)}function Gr(e,t={}){let n=e.nodes,r=Array.isArray(n)?n:[],o=a(i(e.backend)?e.backend:void 0),s=Pn(e,r,t),c=Yr(e),l=hi(e,r,t,s),u=l.length>0?`${l.join(`
4
+ `)}\n`:``,d=t.raw?null:Kr(e);if(d)return`${c}${u}${qr(d)}\n`;let f=t.raw||!o?null:p(s.nodes),m=!!e.truncated,h=f?.nodes??r,g=t.raw||!o?null:ti(e,f,h.length,r.length,s.filteredCount),_=Xr(r.length,g,m);return r.length===0?`${c}${_}\n${u}`:t.raw?`${c}${_}\n${u}${Zr(r)}\n`:t.flatten?`${c}${_}\n${u}${Qr(h)}${ei(f)}\n`:`${c}${_}\n${u}${$r(h)}${ei(f)}\n`}function Kr(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 qr(e){let t=Jr(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
+ `):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
+ `):[`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 Jr(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 Yr(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 Xr(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 Zr(e){return e.map(e=>JSON.stringify(e)).join(`
9
+ `)}function Qr(e){return Ci(e).join(`
10
+ `)}function $r(e){return bi(Ar(e,{summarizeTextSurfaces:!0})).join(`
11
+ `)}function ei(e){return e&&e.summaryLines.length>0?`\n${e.summaryLines.join(`
12
+ `)}`:``}function ti(e,t,n,r,i=0){let a=ni(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:ri([...a?.reasons??[],`offscreen-nodes`])}:a||(s?{partial:!0,visibleNodeCount:n,totalNodeCount:n,reasons:[]}:null)}function ni(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 ri(e){return[...new Set(e)]}function ii(e){let t=e.baselineInitialized===!0,n=e.summary??{},r=F(n.additions),i=F(n.removals),a=F(n.unchanged),o=pi(),s=yi(e),c=s.length>0?`${s.join(`
13
+ `)}\n`:``;if(t)return`${c}Baseline initialized (${a} lines).\n`;let l=fi(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?I(e,`green`):e}if(e.kind===`removed`){let e=t.startsWith(` `)?`-${t}`:`- ${t}`;return o?I(e,`red`):e}return o?I(t,`dim`):t}),u=l.length>0?`${l.join(`
14
+ `)}\n`:``;return o?`${c}${u}${[`${I(String(r),`green`)} additions`,`${I(String(i),`red`)} removals`,`${I(String(a),`dim`)} unchanged`].join(`, `)}\n`:`${c}${u}${r} additions, ${i} removals, ${a} unchanged\n`}function ai(e){let t=pi(),n=e.match===!0,r=e.dimensionMismatch,i=[];return i.push(...oi(e,t)),i.push(...si(e,n,t)),!n&&!r&&(i.push(...ci(e,t)),i.push(...li(e,t))),`${i.join(`
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};
@@ -0,0 +1 @@
1
+ import{exitAfterFlush as e}from"./process-exit.js";async function t(t,n=async()=>await import(`./cli.js`)){let{runCli:r}=await n();return await r(t),await e(0)}export{t as runCliProcess};
@@ -1 +1 @@
1
- import{_ as e}from"./sdk-contracts.js";import{t}from"./timeouts.js";import{n,o as r}from"./host-process.js";import i from"node:path";import a from"node:fs";async function o(n){let{lockDirPath:r,owner:o}=n,l=i.join(r,`owner.json`),d=Date.now()+(n.timeoutMs??3e4),f=n.pollMs??100,p=n.ownerGraceMs??5e3,m=n.description??`process lock`;for(a.mkdirSync(i.dirname(r),{recursive:!0});Date.now()<d;)try{a.mkdirSync(r),s(l,o);let e=!1;return async()=>{e||(e=!0,a.rmSync(r,{recursive:!0,force:!0}))}}catch(e){let n=e;if(n.code!==`EEXIST`)throw n;if(c(r,l,p))continue;await t(f)}throw new e(`COMMAND_FAILED`,`Timed out waiting for ${m}`,{lockDirPath:r,...u(r,l)})}function s(e,t){let n=`${e}.${process.pid}.${Date.now()}.tmp`;a.writeFileSync(n,JSON.stringify(t),`utf8`),a.renameSync(n,e)}function c(e,t,n){let r=null;try{r=a.statSync(e)}catch{return!0}let i=l(t);return i?d(i)?!1:(a.rmSync(e,{recursive:!0,force:!0}),!0):Date.now()-r.mtimeMs<n?!1:(a.rmSync(e,{recursive:!0,force:!0}),!0)}function l(e){try{return JSON.parse(a.readFileSync(e,`utf8`))}catch{return null}}function u(e,t){let n=Date.now(),r=l(t),i;try{i=Math.max(0,Math.round(n-a.statSync(e).mtimeMs))}catch{}return{...i===void 0?{}:{lockAgeMs:i},...r?{ownerPid:r.pid,ownerStartTime:r.startTime,ownerAgeMs:Math.max(0,Math.round(n-r.acquiredAtMs))}:{}}}function d(e){return!Number.isInteger(e.pid)||e.pid<=0||!n(e.pid)?!1:e.startTime?r(e.pid)===e.startTime:!0}export{o as t};
1
+ import{_ as e}from"./sdk-contracts.js";import{t}from"./timeouts.js";import{t as n}from"./owner-identity.js";import r from"node:path";import i from"node:fs";async function a(n){let{lockDirPath:a,owner:c}=n,u=r.join(a,`owner.json`),d=Date.now()+(n.timeoutMs??3e4),f=n.pollMs??100,p=n.ownerGraceMs??5e3,m=n.description??`process lock`;for(i.mkdirSync(r.dirname(a),{recursive:!0});Date.now()<d;)try{i.mkdirSync(a),o(u,c);let e=!1;return async()=>{e||(e=!0,i.rmSync(a,{recursive:!0,force:!0}))}}catch(e){let n=e;if(n.code!==`EEXIST`)throw n;if(s(a,u,p))continue;await t(f)}throw new e(`COMMAND_FAILED`,`Timed out waiting for ${m}`,{lockDirPath:a,...l(a,u)})}function o(e,t){let n=`${e}.${process.pid}.${Date.now()}.tmp`;i.writeFileSync(n,JSON.stringify(t),`utf8`),i.renameSync(n,e)}function s(e,t,n){let r=null;try{r=i.statSync(e)}catch{return!0}let a=c(t);return a?u(a)?!1:(i.rmSync(e,{recursive:!0,force:!0}),!0):Date.now()-r.mtimeMs<n?!1:(i.rmSync(e,{recursive:!0,force:!0}),!0)}function c(e){try{return JSON.parse(i.readFileSync(e,`utf8`))}catch{return null}}function l(e,t){let r=Date.now(),a=c(t),o;try{o=Math.max(0,Math.round(r-i.statSync(e).mtimeMs))}catch{}return{...o===void 0?{}:{lockAgeMs:o},...a?{ownerPid:a.pid,ownerStartTime:a.startTime,ownerAgeMs:Math.max(0,Math.round(r-a.acquiredAtMs)),ownerLiveness:n({owner:a})}:{}}}function u(e){return n({owner:e})!==`owner-process-dead`}export{a as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./version.js";import{_ 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};
@@ -0,0 +1 @@
1
+ import{o as e}from"./png-worker-contract.js";import{_ as t}from"./sdk-contracts.js";import{W as n,tr as r}from"./sdk-batch-runner.js";import{A as i,_ as a,f as o}from"./sdk-android-adb.js";import{t as s}from"./timeouts.js";import{c}from"./tool-provider.js";import{i as l,n as ee,o as te,r as ne}from"./agent-browser-tool.js";function u(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function d(e,t){return u(e)?e[t]:void 0}function f(e,t){let n=d(e,t);return typeof n==`string`?n:void 0}function re(e,t){let n=d(e,t);return typeof n==`boolean`?n:void 0}function p(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}const ie=[h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j];function ae(e){let t=ie.map(e=>`${e.toString()};`).join(``),n=se(e.action),r=m(e.durationMs),i=m(e.bucketMs);return`(()=>{${t}return ${j.name}({action:${n},durationMs:${r},bucketMs:${i}})})()`}function oe(e){let t=n(ce(e),{source:`media-elements`,backend:`agent-browser`,durationMs:0,elapsedMs:0,bucketMs:1e3,activeFallback:!1,mediaElementCount:0,sourceCount:0});return{...t,source:`media-elements`,mediaElementCount:t.mediaElementCount??0}}function se(e){switch(e){case`start`:return`'start'`;case`stop`:return`'stop'`;default:return`'status'`}}function m(e){return e===void 0||!Number.isFinite(e)?`undefined`:String(Math.trunc(e))}function h(e){return!Number.isFinite(e)||e<=0?-90:Math.max(-90,Math.min(0,Math.round(20*Math.log10(e))))}function g(e,t){e.notes.includes(t)||e.notes.push(t)}function _(){return Array.from(document.querySelectorAll(`audio,video`))}function v(e,t){if(!e||e.state===`stopped`)return e;clearInterval(e.timer),clearTimeout(e.timeout),e.timer=void 0,e.timeout=void 0,e.state=`stopped`,e.active=!1,e.reason=t,e.stoppedAt=Date.now();for(let t of e.analysers)try{t.analyser.disconnect(),t.source.disconnect(),t.audible&&t.source.connect(e.context.destination)}catch{}if(e.resumeOnGesture){for(let t of[`click`,`pointerdown`,`keydown`])window.removeEventListener(t,e.resumeOnGesture,!0);e.resumeOnGesture=void 0}return e}function y(e){let t=window.AudioContext||window.webkitAudioContext;if(!t)return;let n=window[e];if(n&&n.state!==`closed`)return n;let r=new t;return window[e]=r,r}function b(e,t,n){if(!(!t.currentSrc&&!t.src&&t.readyState===0))try{window[n]||(window[n]=new WeakMap);let r=window[n].get(t);return r||(r=e.context.createMediaElementSource(t),window[n].set(t,r)),r.disconnect(),{source:r,audible:!0}}catch{return}}function x(e,t){if(!(!t||typeof t.getAudioTracks!=`function`)&&t.getAudioTracks().length!==0)return{source:e.context.createMediaStreamSource(t),audible:!1}}function S(e,t){if(typeof t.captureStream==`function`)return x(e,t.captureStream())}function C(e,t){let n=e.context.createAnalyser();n.fftSize=2048,t.source.connect(n),n.connect(t.audible?e.context.destination:e.sink),e.analysers.push({...t,analyser:n,buffer:new Float32Array(n.fftSize)})}function w(e,t){let n=_();e.mediaElementCount=n.length;for(let r of n){if(e.seen.has(r))continue;let n=x(e,r.srcObject)??S(e,r)??b(e,r,t);if(!n){g(e,`Some media elements do not expose capturable audio to Web Audio.`);continue}e.seen.add(r),C(e,n)}e.sourceCount=e.analysers.length,e.sourceCount===0&&g(e,`No capturable page media audio sources were found yet.`)}function T(e){let t=0,n=0,r=0;for(let i of e.analysers){i.analyser.getFloatTimeDomainData(i.buffer);for(let e of i.buffer)t+=e*e,n+=1,r=Math.max(r,Math.abs(e))}return{rms:n>0?Math.sqrt(t/n):0,peak:r}}function E(e){let t=Math.ceil(e.durationMs/e.bucketMs)+2;e.rmsDbfs.length>t&&e.rmsDbfs.splice(0,e.rmsDbfs.length-t),e.peakDbfs.length>t&&e.peakDbfs.splice(0,e.peakDbfs.length-t)}function D(e,t){if(!e||e.state!==`running`)return;w(e,t);let n=T(e),r=h(n.rms),i=h(n.peak);e.rmsDbfs.push(r),e.peakDbfs.push(i),e.heard=e.heard||r>-90||i>-90,E(e),Date.now()-e.startedAt>=e.durationMs&&v(e,`duration`)}function O(e,t){return{audio:`probe`,state:`stopped`,active:!1,heard:!1,source:`media-elements`,backend:`agent-browser`,durationMs:Number(e.durationMs)||1e4,elapsedMs:0,bucketMs:Number(e.bucketMs)||1e3,sampleCount:0,mediaElementCount:_().length,sourceCount:0,rmsDbfs:[],peakDbfs:[],notes:t}}function k(e,t,n,r){return e?{audio:`probe`,state:e.state,active:e.state===`running`,heard:e.heard,source:`media-elements`,backend:`agent-browser`,durationMs:e.durationMs,elapsedMs:Math.max(0,Math.min((e.stoppedAt||Date.now())-e.startedAt,e.durationMs)),bucketMs:e.bucketMs,sampleCount:e.rmsDbfs.length,mediaElementCount:_().length,sourceCount:e.sourceCount,rmsDbfs:e.rmsDbfs.slice(),peakDbfs:e.peakDbfs.slice(),startedAt:new Date(e.startedAt).toISOString(),stoppedAt:e.stoppedAt?new Date(e.stoppedAt).toISOString():void 0,reason:e.reason,notes:[n,r,...e.notes]}:O(t,[n,r])}function A(e,t,n,r,i,a,o){t&&v(t,`restarted`);let s=y(r);if(!s)return O(e,[`Web Audio API is not available in this browser context.`]);let c=s.createGain();c.gain.value=0,c.connect(s.destination);let l={state:`running`,active:!0,context:s,sink:c,seen:new WeakSet,analysers:[],mediaElementCount:0,sourceCount:0,durationMs:Math.max(100,Number(e.durationMs)||1e4),bucketMs:Math.max(100,Number(e.bucketMs)||1e3),startedAt:Date.now(),stoppedAt:void 0,reason:void 0,heard:!1,rmsDbfs:[],peakDbfs:[],notes:[]};try{s.resume()}catch{g(l,`AudioContext could not be resumed by the probe.`)}l.resumeOnGesture=()=>{try{s.resume()}catch{g(l,`AudioContext could not be resumed from a user gesture.`)}};for(let e of[`click`,`pointerdown`,`keydown`])window.addEventListener(e,l.resumeOnGesture,{capture:!0,once:!0});return w(l,i),l.timer=setInterval(()=>D(l,i),l.bucketMs),l.timeout=setTimeout(()=>v(l,`duration`),l.durationMs),window[n]=l,k(l,e,a,o)}function j(e){let t=`__agentDeviceAudioProbe`,n=`__agentDeviceAudioProbeSources`,r=`Audio probe samples HTML media elements exposed to Web Audio; it is not whole-tab or system audio capture.`,i=`URL-backed media elements may be routed through the probe AudioContext while they are observed.`,a=window[t];return a&&a.state===`running`&&Date.now()-a.startedAt>=a.durationMs&&(D(a,n),v(a,`duration`)),e.action===`start`?A(e,a,t,`__agentDeviceAudioProbeContext`,n,r,i):e.action===`stop`?(a&&D(a,n),v(a,`manual`),k(a,e,r,i)):(a&&D(a,n),k(a,e,r,i))}function ce(e){return u(e)?u(e.result)?e.result:e:{}}function le(e,t={}){let n=ue(e),r=me(t.limit),i=t.include===`headers`||t.include===`all`,a=n.slice(-r).reverse().map(e=>fe(e,i)),o=t.include===`body`||t.include===`all`?[`agent-browser network requests does not expose request or response bodies.`]:void 0;return{entries:a,backend:`agent-browser`,redacted:!1,...o?{notes:o}:{}}}function ue(e){let t=u(e)&&Array.isArray(e.requests)?e.requests:e;return Array.isArray(t)?t.filter(de).map(e=>({headers:M(e.headers),method:f(e,`method`),mimeType:f(e,`mimeType`),requestId:f(e,`requestId`),resourceType:f(e,`resourceType`),responseHeaders:M(e.responseHeaders),status:p(e,`status`),timestamp:pe(e.timestamp),url:f(e,`url`)})):[]}function de(e){return u(e)}function fe(e,t){let n=e.timestamp===void 0?void 0:N(e.timestamp),i=r({requestId:e.requestId,resourceType:e.resourceType,mimeType:e.mimeType});return r({timestamp:n,method:e.method,url:e.url,status:e.status,requestHeaders:t?e.headers:void 0,responseHeaders:t?e.responseHeaders:void 0,metadata:Object.keys(i).length>0?i:void 0})}function M(e){if(!u(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return Object.keys(t).length>0?t:void 0}function pe(e){if(typeof e==`number`||typeof e==`string`)return e}function N(e){if(typeof e==`string`){let t=Number(e);return Number.isFinite(t)?N(t):e}let t=e>1e10?e:e*1e3,n=new Date(t);return Number.isNaN(n.getTime())?String(e):n.toISOString()}function me(e){return typeof e!=`number`||!Number.isInteger(e)?25:Math.max(1,Math.min(e,200))}async function he(e,t){let n=P(f(e,`snapshot`)??``,L(d(e,`refs`)));return t&&await ge(n,t),{nodes:n.map((e,t)=>({...e.node,index:t})),truncated:re(e,`truncated`)}}async function ge(e,t){for(let n=0;n<e.length;n+=8){let r=e.slice(n,n+8),i=await Promise.all(r.map(e=>t(e.ref)));for(let[e,t]of i.entries())t&&(r[e].node.rect=t)}}function P(e,t){let n=new Map(t.map(e=>[e.ref,e])),r=[],i=new Set,a=new Map;for(let t of e.split(/\r?\n/)){let e=ye(t);if(!e)continue;i.add(e);let o=n.get(e)?.data,s=_e(t),c=F(t,o,s),l=ve(a,s);l!==void 0&&(c.parentIndex=l),r.push({ref:e,node:{...c,index:r.length}}),a.set(s,r.length-1)}for(let e of t)i.has(e.ref)||r.push({ref:e.ref,node:{...I(e.data),index:r.length}});return r}function F(e,t,n){let r=be(e)??z(t,[`role`,`type`]);return{index:0,type:r,role:r,label:xe(e)??z(t,[`label`,`name`,`text`]),value:Se(e)??z(t,[`value`]),depth:n,enabled:B(t,[`enabled`]),focused:B(t,[`focused`])}}function I(e){let t=z(e,[`role`,`type`]);return{index:0,type:t,role:t,label:z(e,[`label`,`name`,`text`]),value:z(e,[`value`]),enabled:B(e,[`enabled`]),focused:B(e,[`focused`])}}function L(e){return Array.isArray(e)?e.flatMap(e=>{let t=u(e)?e:void 0,n=R(z(t,[`ref`,`id`])??String(e));return n?[{ref:n,data:t}]:[]}):u(e)?Object.entries(e).flatMap(([e,t])=>{let n=R(e);return n?[{ref:n,data:u(t)?t:void 0}]:[]}):[]}function _e(e){let t=e.match(/^\s*/)?.[0].length??0;return Math.floor(t/2)}function ve(e,t){for(let n=t-1;n>=0;--n){let t=e.get(n);if(t!==void 0)return t}}function ye(e){return R(e.match(/\bref=['"]?(@?e\d+)['"]?/i)?.[1]??e.match(/@?(e\d+)\b/i)?.[1])}function R(e){let t=e?.trim().replace(/^@/,``);return t&&/^e\d+$/i.test(t)?t.toLowerCase():null}function be(e){return e.replace(/\[[^\]]*ref[^\]]*\]/gi,``).replace(/@?e\d+\b/gi,``).replace(/^[\s|├└─>*-]+/g,``).trim().match(/^([A-Za-z][\w-]*)\b/)?.[1]}function xe(e){return e.match(/"([^"]+)"/)?.[1]??e.match(/'([^']+)'/)?.[1]}function Se(e){return Ce(e)??e.match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s\]]+))/i)?.slice(1).find(V)??e.match(/\bvalue:\s*(?:"([^"]*)"|'([^']*)'|([^\s\]]+))/i)?.slice(1).find(V)}function Ce(e){return e.match(/\]\s*:\s*(.+)$/)?.[1]?.trim()||void 0}function z(e,t){if(e)for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}}function B(e,t){if(e)for(let n of t){let t=e[n];if(typeof t==`boolean`)return t}}function V(e){return typeof e==`string`}const H=`agent-browser`,U="Run `agent-device web setup` to install the managed web backend.";function W(e={}){let t=e.session?.trim(),n=async(n,r)=>await Ne(n,{session:t,options:e,signal:r});return{async open(e){await n([`open`,e])},async close(){await n([`close`])},async startRecording(e){await n([`record`,`start`,e])},async stopRecording(){await n([`record`,`stop`])},async snapshot(e){return await ke(t=>n(t,e?.signal),e)},async screenshot(e,t){await n([`screenshot`,...t?.fullscreen?[`--full`]:[],e])},async setViewport(e,t){await n([`set`,`viewport`,String(e),String(t)])},async click(e,t){await G(n,e,t)},async clickRef(e){await n([`click`,q(e)])},async fill(e,t,r){await G(n,e,t),await n([`press`,Ve()]),await n([`keyboard`,`type`,r])},async fillRef(e,t){await n([`fill`,q(e),t])},async typeText(e){await n([`keyboard`,`type`,e])},async scroll(e,t){return await we(n,e,t),t?.durationMs===void 0?{}:{durationMs:t.durationMs}},async dumpNetwork(e){return le(await n([`network`,`requests`]),e)},async probeAudio(e){return oe(await n([`eval`,ae(e)]))}}}async function we(e,t,n){let r=Te(n);for(let n of r)await e(Oe(t,n.distance)),n.delayAfterMs>0&&await s(n.delayAfterMs)}function Te(e){let t=e?.pixels??e?.amount,n=e?.durationMs;if(n===void 0||n<=0)return[{distance:t,delayAfterMs:0}];let r=Math.max(1,Math.min(20,Math.ceil(n/50))),i=n/Math.max(1,r-1);return Ee(e,r).map((e,t)=>({distance:e,delayAfterMs:t<r-1?i:0}))}function Ee(e,t){let n=e?.pixels??e?.amount??300;return e?.amount!==void 0&&e.pixels===void 0?Array.from({length:t},()=>n/t):De(Math.round(n),t)}function De(e,t){let n=Math.floor(e/t),r=e-n*t;return Array.from({length:t},(e,t)=>t<r?n+1:n)}function Oe(e,t){return[`scroll`,e,...t===void 0?[]:[String(t)]]}async function G(e,t,n){await e([`mouse`,`move`,String(Math.round(t)),String(Math.round(n))]),await e([`mouse`,`down`]),await e([`mouse`,`up`])}async function ke(e,t){return await he(await e(Ae(t)),t?.includeRects?async t=>await je(e,t):void 0)}function Ae(e){return[`snapshot`,...e?.interactiveOnly?[`--interactive`]:[],...e?.raw?[]:[`--compact`],...typeof e?.depth==`number`?[`--depth`,String(e.depth)]:[],...e?.scope?[`--selector`,e.scope]:[]]}async function je(e,t){try{return He(await e([`get`,`box`,q(t)]))}catch(e){if(Me(e))return;throw e}}function Me(e){let t=e instanceof Error?e.message:String(e);return!/\bstale\b/i.test(t)&&/\bbox\b|not visible|not found|no element/i.test(t)}async function Ne(e,t){let{session:n,options:r,signal:i}=t,a=[...e,`--json`,...n?[`--session`,n]:[]],o=await Pe(a,r,i);return Ie(Le(o.stdout,o.stderr,a,o.exitCode),o,a)}async function Pe(e,t,n){let r=``,i=``,o=0;try{await Fe(t);let s=await l({stateDir:t.stateDir}),c=await a(s.command,e,{allowFailure:!0,env:s.env,timeoutMs:3e4,signal:n});r=c.stdout,i=c.stderr,o=c.exitCode}catch(t){throw Re(t,e)}return{stdout:r,stderr:i,exitCode:o}}async function Fe(e){if(!e.openWebSessionNames)return;let t=ee({stateDir:e.stateDir});if(t.installed)try{await te(t,{openWebSessionNames:e.openWebSessionNames()})}catch(e){i({level:`warn`,phase:`web_agent_browser_provider_orphan_cleanup_failed`,data:{error:e instanceof Error?e.message:String(e)}})}}function Ie(e,n,r){if(!u(e))return e;if((e.success??e.ok)===!1)throw new t(Be(e.code),ze(e),{cmd:H,args:r,hint:f(e,`hint`)??U,agentBrowserError:e.error});if(n.exitCode!==0)throw new t(`COMMAND_FAILED`,`agent-browser command failed`,o(n,{cmd:H,args:r,stdout:n.stdout.slice(0,500),stderr:n.stderr.slice(0,500),hint:f(e,`hint`)??U}));return Object.hasOwn(e,`data`)?e.data:e}function Le(e,n,r,i){try{return JSON.parse(e)}catch(a){let o=i!==0;throw new t(`COMMAND_FAILED`,o?`agent-browser command failed`:`agent-browser returned invalid JSON`,{cmd:H,args:r,...o?{exitCode:i}:{},stdout:e.slice(0,500),stderr:n.slice(0,500),hint:U},a instanceof Error?a:void 0)}}function Re(e,n){let r=ne(e);return r.code===`TOOL_MISSING`?new t(`TOOL_MISSING`,r.message,{...r.details??{},cmd:H,args:n,hint:K(r)},r):r.code===`COMMAND_FAILED`?new t(`COMMAND_FAILED`,r.message,{...r.details??{},cmd:H,args:n,hint:K(r)},r):r}function K(e){return typeof e.details?.hint==`string`?e.details.hint:U}function ze(e){let t=e.error;if(typeof t==`string`&&t.trim())return t.trim();if(u(t)){let e=f(t,`message`)??f(t,`error`);if(e)return e}return f(e,`message`)??`agent-browser command failed`}function Be(e){return typeof e==`string`&&e.length>0?e:`COMMAND_FAILED`}function q(e){return e.startsWith(`@`)?e:`@${e}`}function Ve(){return process.platform===`darwin`?`Meta+a`:`Control+a`}function He(e){let t=u(e)&&u(e.box)?e.box:e;if(u(t))return J(t)??Ue(t)}function J(e){return Y(p(e,`x`),p(e,`y`),p(e,`width`),p(e,`height`))}function Ue(e){let t=p(e,`left`),n=p(e,`top`),r=p(e,`right`),i=p(e,`bottom`);return Y(t,n,X(r,t),X(i,n))}function Y(e,t,n,r){if(!(e===void 0||t===void 0||n===void 0||r===void 0))return{x:e,y:t,width:n,height:r}}function X(e,t){return e===void 0||t===void 0?void 0:e-t}var We=e({hasScopedWebProvider:()=>Ge,resolveWebProvider:()=>Q,withWebProvider:()=>$});const Z=c(W());function Q(e){return Z.resolve(e)}function Ge(){return Z.hasScope()}async function $(e,t){return await Z.run(e,t)}export{W as i,Q as n,$ as r,We as t};
@@ -0,0 +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{_t as o,dt as s,ft as c,ht as l,pt as u,r as d,ut as ee}from"./screenshot-result.js";import{t as f}from"./timing-safe-equal.js";import{t as p}from"./shared.js";import{randomBytes as m,randomUUID as te}from"node:crypto";import{pipeline as h}from"node:stream/promises";import{Readable as g}from"node:stream";import _ from"node:http";const v=`${ee}/`,y=[`content-type`,`content-range`,`x-artifact-type`,`x-artifact-filename`,`x-artifact-hash`,`x-artifact-hash-algorithm`,s],b=[`content-type`,`content-disposition`,`x-request-id`];function x(e){let t=N(e);return _.createServer((e,n)=>{S(e,n,t).catch(e=>{X(n,e)})})}async function S(e,t,n){let r=I(e.url??`/`);if(e.method===`GET`&&r===`/health`){await C(t,n);return}if(!L(r,e.method)){t.statusCode=404,t.end(`Not found`);return}let i;if(r===`/rpc`&&(i=(await o(e,n.maxRpcBodyBytes,`Proxy request body is too large.`)).toString(`utf8`)),!U(e,n.clientToken,i)){Y(t,r,q(i));return}await T({req:e,res:t,route:r,options:n,rpcBody:i})}async function C(e,t){let n=await w(t);e.statusCode=200,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify(d(`agent-device-proxy`,{upstream:n})))}async function w(e){let t=new URL(l(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 T(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 E({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 E(e){let{req:t,res:n,route:r,response:i,clientToken:a}=e;if(n.statusCode=i.status,D(i,n),O(t,n),z(r)){await k({req:t,res:n,response:i,clientToken:a});return}await M(i,n)}function D(e,t){for(let n of b){let r=e.headers.get(n);r&&t.setHeader(n,r)}}function O(e,t){t.hasHeader(`x-request-id`)||t.setHeader(`x-request-id`,J(e))}async function k(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(A(a,t,i))}function A(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=j(i.upload.url,t);if(!a)return e;let o=i.upload.headers&&typeof i.upload.headers==`object`?{...i.upload.headers}:{};return Object.assign(o,c(n)),JSON.stringify({...r,upload:{...i.upload,url:a,headers:o}})}function j(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 M(e,t){if(!e.body){t.end();return}await h(g.fromWeb(e.body),t)}function N(e){return{upstreamBaseUrl:P(e.upstreamBaseUrl,`upstreamBaseUrl`),upstreamToken:F(e.upstreamToken,`upstreamToken`),clientToken:F(e.clientToken,`clientToken`),maxRpcBodyBytes:e.maxRpcBodyBytes??1048576,upstreamTimeoutMs:e.upstreamTimeoutMs??3e5,fetchImpl:e.fetchImpl??fetch}}function P(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 F(e,n){let r=e.trim();if(!r)throw new t(`INVALID_ARGS`,`Proxy ${n} is required.`);return r}function I(e){let t=new URL(e,`http://127.0.0.1`).pathname;return t===`/agent-device`?`/`:t.startsWith(v)?`/${t.slice(v.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(l(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 y){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(c(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&&f(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):te()}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 p(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),c=x({upstreamBaseUrl:o,upstreamToken:r.info.token,clientToken:s});await ie(c,e.proxyHost?.trim()||`127.0.0.1`,e.proxyPort??0);let l=c.address();if(!l||typeof l==`string`)throw new t(`COMMAND_FAILED`,`Proxy did not bind to a TCP address.`);let d=`http://${ae(l.address)}:${l.port}`;return{proxyBaseUrl:d,agentDeviceBaseUrl:u(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()||m(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
+ `)}function $(e,t,n){return n?r(e,t,{validateStream:!1}):e}function se(){return new Promise(()=>{})}export{Z as proxyCommand};
@@ -1 +1 @@
1
- import{S as e}from"./sdk-contracts.js";import{wn as t}from"./sdk-batch-runner.js";import{I as n,Kt as r,fn as i}from"./viewport-dimension.js";import{p as a}from"./runtime.js";import{c as o,l as s,n as c,s as l}from"./context.js";import{Kt 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:i,sessionName:c,sessionStore:l}=t;if(i.command!==r.reactNative)return null;let u=h(i.positionals??[]);if(!u.ok)return u.response;let f=l.get(c);if(!f)return o();let p=s(r.reactNative,f.device,{message:`react-native dismiss-overlay is not supported on this device`});if(p)return p;try{let e=await d(f,i.flags,l,t.contextFromFlags,{interactiveOnly:!0});if(n(e.snapshotQuality))return _(e.snapshotQuality);let r=a(e.nodes),o=r.primaryAction;return o?await v(t,f,e,o):g(r.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:l(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}}function g(e){return e?l(`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,...i(`No React Native overlay detected`)}}}function _(e){return l(`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,r,a){let{req:o,sessionStore:s}=e,l=Date.now();u(n);let d=await c(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(r.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,...i(b(h))});return f({session:n,sessionStore:s,command:o.command,positionals:o.positionals??[],flags:o.flags,result:g,responseData:g,actionStartedAt:l,actionFinishedAt:m})}async function y(e,t){let{req:r,sessionStore:i}=e,o=await d(t,r.flags,i,e.contextFromFlags,{interactiveOnly:!0});return n(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};
1
+ import{S as e}from"./sdk-contracts.js";import{tr 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,l as s,n as c,s as l}from"./context.js";import{Xt 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:c,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(c);if(!f)return o();let p=s(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:l(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}}function g(e){return e?l(`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 l(`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,l=Date.now();u(n);let d=await c(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:l,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};
@@ -1 +1 @@
1
- import{C as e}from"./screenshot-result.js";import{s as t}from"./context.js";import{c as n,m as r}from"./internal/daemon.js";import i from"node:path";import a from"node:fs";async function o(o){let{req:s,sessionName:c,sessionStore:l,logPath:u}=o,d=s.command;if(d===`record`)return n({req:s,sessionName:c,sessionStore:l,logPath:u});if(d===`trace`){let n=(s.positionals?.[0]??``).toLowerCase();if(![`start`,`stop`].includes(n))return t(`INVALID_ARGS`,`trace requires start|stop`);let o=l.get(c);if(!o)return t(`SESSION_NOT_FOUND`,`No active session`);if(n===`start`){if(o.trace)return t(`INVALID_ARGS`,`trace already in progress`);let n=s.positionals?.[1]??l.defaultTracePath(o),c=e.expandHome(n);return a.mkdirSync(i.dirname(c),{recursive:!0}),a.appendFileSync(c,``),o.trace={outPath:c,startedAt:Date.now()},r(l,o,s,d,{action:`start`,outPath:c}),{ok:!0,data:{trace:`started`,outPath:c}}}if(!o.trace)return t(`INVALID_ARGS`,`no active trace`);let u=o.trace.outPath;if(s.positionals?.[1]){let t=e.expandHome(s.positionals[1]);a.mkdirSync(i.dirname(t),{recursive:!0}),a.existsSync(u)?a.renameSync(u,t):a.appendFileSync(t,``),u=t}o.trace=void 0,r(l,o,s,d,{action:`stop`,outPath:u});let f=s.meta?.clientArtifactPaths?.outPath??u;return{ok:!0,data:{trace:`stopped`,outPath:u,artifacts:[{field:`outPath`,artifactType:`trace-log`,path:u,localPath:f,fileName:i.basename(f)}]}}}return null}export{o as handleRecordTraceCommands};
1
+ import{x as e}from"./screenshot-result.js";import{s as t}from"./context.js";import{D as n,y as r}from"./internal/daemon.js";import i from"node:path";import a from"node:fs";async function o(o){let{req:s,sessionName:c,sessionStore:l,logPath:u}=o,d=s.command;if(d===`record`)return r({req:s,sessionName:c,sessionStore:l,logPath:u});if(d===`trace`){let r=(s.positionals?.[0]??``).toLowerCase();if(![`start`,`stop`].includes(r))return t(`INVALID_ARGS`,`trace requires start|stop`);let o=l.get(c);if(!o)return t(`SESSION_NOT_FOUND`,`No active session`);if(r===`start`){if(o.trace)return t(`INVALID_ARGS`,`trace already in progress`);let r=s.positionals?.[1]??l.defaultTracePath(o),c=e.expandHome(r);return a.mkdirSync(i.dirname(c),{recursive:!0}),a.appendFileSync(c,``),o.trace={outPath:c,startedAt:Date.now()},n(l,o,s,d,{action:`start`,outPath:c}),{ok:!0,data:{trace:`started`,outPath:c}}}if(!o.trace)return t(`INVALID_ARGS`,`no active trace`);let u=o.trace.outPath;if(s.positionals?.[1]){let t=e.expandHome(s.positionals[1]);a.mkdirSync(i.dirname(t),{recursive:!0}),a.existsSync(u)?a.renameSync(u,t):a.appendFileSync(t,``),u=t}o.trace=void 0,n(l,o,s,d,{action:`stop`,outPath:u});let f=s.meta?.clientArtifactPaths?.outPath??u;return{ok:!0,data:{trace:`stopped`,outPath:u,artifacts:[{field:`outPath`,artifactType:`trace-log`,path:u,localPath:f,fileName:i.basename(f)}]}}}return null}export{o as handleRecordTraceCommands};