agent-device 0.21.34 → 0.21.35

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 (174) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.34.apk → agent-device-android-ime-helper-0.21.35.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.35.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.34.manifest.json → agent-device-android-ime-helper-0.21.35.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.34.apk → agent-device-android-snapshot-helper-0.21.35.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.35.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.34.manifest.json → agent-device-android-snapshot-helper-0.21.35.manifest.json} +7 -7
  7. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +27 -18
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +26 -7
  9. package/dist/src/agent-browser-provider.js +1 -1
  10. package/dist/src/agent-device-client.js +1 -1
  11. package/dist/src/ai-sdk.d.ts +1 -1
  12. package/dist/src/alert.js +1 -1
  13. package/dist/src/android-adb.d.ts +1 -1
  14. package/dist/src/app-backend.js +1 -1
  15. package/dist/src/app-launch.js +1 -1
  16. package/dist/src/app-lifecycle.js +1 -1
  17. package/dist/src/app-log-reconnect.js +1 -1
  18. package/dist/src/app-log-runtime2.js +2 -2
  19. package/dist/src/app-log-session-resource.js +1 -1
  20. package/dist/src/app-resolution.js +2 -2
  21. package/dist/src/app-state-runtime.d.ts +1 -1
  22. package/dist/src/apple-runner-platform.js +1 -1
  23. package/dist/src/application-lifecycle-interaction.js +1 -1
  24. package/dist/src/artifact-download.js +1 -1
  25. package/dist/src/back-mode.js +1 -1
  26. package/dist/src/cli-config.js +1 -1
  27. package/dist/src/cli-help.js +3 -2
  28. package/dist/src/cli.js +2 -2
  29. package/dist/src/client-types.d.ts +17 -4
  30. package/dist/src/cloud-artifacts.d.ts +2 -2
  31. package/dist/src/command-metadata.js +41 -41
  32. package/dist/src/command-schema.js +3 -1
  33. package/dist/src/command-tools.js +1 -1
  34. package/dist/src/composed-inventory-gateways.js +1 -1
  35. package/dist/src/composite-resource-admission.js +1 -1
  36. package/dist/src/connection-runtime.js +1 -1
  37. package/dist/src/connection.js +5 -5
  38. package/dist/src/contract.d.ts +2 -1
  39. package/dist/src/contracts.d.ts +1 -1
  40. package/dist/src/daemon-client-lease-beat.js +1 -1
  41. package/dist/src/daemon-client.js +2 -2
  42. package/dist/src/daemon-command-registry.js +1 -1
  43. package/dist/src/daemon-composition.js +1 -1
  44. package/dist/src/daemon-policy-file.js +1 -1
  45. package/dist/src/debug-symbols-facade.js +1 -1
  46. package/dist/src/destination-tunnel-dialer.js +27 -0
  47. package/dist/src/device-claim-recovery.js +1 -1
  48. package/dist/src/device-claims.js +1 -1
  49. package/dist/src/device-input-state.d.ts +1 -1
  50. package/dist/src/device-readiness-runtime.js +1 -1
  51. package/dist/src/device-selection-resolver.js +1 -1
  52. package/dist/src/device.js +1 -1
  53. package/dist/src/discovery.js +1 -1
  54. package/dist/src/doctor-facade.js +1 -1
  55. package/dist/src/durable-resource.js +1 -1
  56. package/dist/src/explicit-session-resolution.js +1 -1
  57. package/dist/src/find.js +1 -1
  58. package/dist/src/generic.js +1 -1
  59. package/dist/src/gesture-admission.js +1 -1
  60. package/dist/src/gesture-plan-types.d.ts +1 -1
  61. package/dist/src/gesture-runtime.js +1 -1
  62. package/dist/src/human-control.js +1 -1
  63. package/dist/src/index.d.ts +1 -1
  64. package/dist/src/instance-client.js +1 -1
  65. package/dist/src/interaction.js +1 -1
  66. package/dist/src/interaction2.js +1 -1
  67. package/dist/src/interactor.js +5 -5
  68. package/dist/src/interactor4.js +1 -1
  69. package/dist/src/interactors.js +1 -1
  70. package/dist/src/internal/bin.js +1 -1
  71. package/dist/src/inventory2.js +1 -1
  72. package/dist/src/ios-client.js +4 -4
  73. package/dist/src/launch-confirmation.js +1 -1
  74. package/dist/src/lease-context.js +1 -1
  75. package/dist/src/lease-registry-scope.js +1 -1
  76. package/dist/src/lease.js +1 -1
  77. package/dist/src/leased-recording-retention.js +1 -1
  78. package/dist/src/legacy.js +1 -1
  79. package/dist/src/limrun.d.ts +6 -1
  80. package/dist/src/local-interactor-operation-set.js +1 -1
  81. package/dist/src/log-stream.js +2 -28
  82. package/dist/src/mechanics.js +1 -1
  83. package/dist/src/metro.d.ts +1 -1
  84. package/dist/src/network-har.js +2 -0
  85. package/dist/src/open-target-resolution.js +1 -1
  86. package/dist/src/perf-facade.js +1 -1
  87. package/dist/src/perf-target.js +1 -1
  88. package/dist/src/platform-runtime-daemon-services.js +1 -1
  89. package/dist/src/platform-runtime-open-target.js +1 -1
  90. package/dist/src/platform-runtime-operation-host.js +3 -3
  91. package/dist/src/platform-runtime-runtime-hints.js +1 -1
  92. package/dist/src/platform-runtime-unavailable.js +1 -1
  93. package/dist/src/platform-runtime.js +1 -1
  94. package/dist/src/platform-runtime2.js +1 -1
  95. package/dist/src/plugin-inventory.js +1 -1
  96. package/dist/src/provider-device-runtime.d.ts +1 -1
  97. package/dist/src/provider-plugin.d.ts +1 -1
  98. package/dist/src/proxy.js +2 -2
  99. package/dist/src/react-native.js +1 -1
  100. package/dist/src/record-runtime-response.js +1 -1
  101. package/dist/src/record-runtime.js +1 -1
  102. package/dist/src/record-trace.js +1 -1
  103. package/dist/src/registry.js +1 -1
  104. package/dist/src/replay-maestro-backend.js +3 -3
  105. package/dist/src/replay-script-selection.js +1 -1
  106. package/dist/src/replay.d.ts +1 -1
  107. package/dist/src/request-runtime-binding.js +1 -1
  108. package/dist/src/result-serialization.js +2 -1
  109. package/dist/src/runner-client.js +1 -1
  110. package/dist/src/runner-dev-tools-security.js +1 -1
  111. package/dist/src/runner-device-readiness.js +1 -1
  112. package/dist/src/runner-retention.js +1 -1
  113. package/dist/src/runner-selector-query.js +1 -1
  114. package/dist/src/runner-startup-transport.js +1 -1
  115. package/dist/src/runner.js +1 -1
  116. package/dist/src/runtime-admission.js +1 -1
  117. package/dist/src/runtime-deployment.js +1 -1
  118. package/dist/src/runtime-session.js +1 -1
  119. package/dist/src/runtime.js +2 -2
  120. package/dist/src/runtime3.js +4 -4
  121. package/dist/src/runtime4.js +1 -1
  122. package/dist/src/runtime5.js +1 -1
  123. package/dist/src/runtime6.js +1 -1
  124. package/dist/src/runtime7.js +1 -1
  125. package/dist/src/runtime8.js +1 -1
  126. package/dist/src/runtime9.js +1 -1
  127. package/dist/src/screen-recording-resource-recovery.js +1 -1
  128. package/dist/src/screen-recording-session-resource.js +1 -1
  129. package/dist/src/screen-recording-transport.js +1 -1
  130. package/dist/src/screenshot-density.js +1 -1
  131. package/dist/src/screenshot-runtime.js +1 -1
  132. package/dist/src/sdk-batch-runner.js +2 -2
  133. package/dist/src/sdk-batch.js +2 -2
  134. package/dist/src/sdk-contracts.d.ts +4 -1
  135. package/dist/src/sdk-device.js +1 -1
  136. package/dist/src/sdk-finders.d.ts +1 -1
  137. package/dist/src/sdk-remote-config.d.ts +8 -1
  138. package/dist/src/sdk-remote-config.js +1 -1
  139. package/dist/src/sdk-selectors.d.ts +1 -1
  140. package/dist/src/selector-runtime.js +1 -1
  141. package/dist/src/server-startup.js +1 -1
  142. package/dist/src/server.js +1 -1
  143. package/dist/src/session-artifact-paths.js +1 -1
  144. package/dist/src/session-device-resolution.js +1 -1
  145. package/dist/src/session-open.js +1 -1
  146. package/dist/src/session-runtime.js +1 -1
  147. package/dist/src/session-selector.js +1 -1
  148. package/dist/src/session-store.js +1 -1
  149. package/dist/src/session2.js +4 -4
  150. package/dist/src/settle-observation-capture.js +1 -1
  151. package/dist/src/simctl.js +1 -1
  152. package/dist/src/simulator-boot.js +1 -1
  153. package/dist/src/snapshot-diagnostics.js +1 -1
  154. package/dist/src/snapshot-runtime-binding.js +1 -1
  155. package/dist/src/snapshot-runtime-capture-input.js +1 -1
  156. package/dist/src/snapshot-runtime.js +1 -1
  157. package/dist/src/snapshot.js +1 -1
  158. package/dist/src/src.js +1 -1
  159. package/dist/src/src3.js +4 -4
  160. package/dist/src/src4.js +1 -1
  161. package/dist/src/src9.js +1 -1
  162. package/dist/src/store.js +1 -1
  163. package/dist/src/telephony-runtime.js +1 -1
  164. package/dist/src/touch-runtime2.js +1 -1
  165. package/dist/src/transport.js +2 -2
  166. package/dist/src/tv-remote-runtime.js +1 -1
  167. package/dist/src/tv-remote.js +1 -1
  168. package/dist/src/type-text-runtime.js +1 -1
  169. package/package.json +1 -1
  170. package/server.json +2 -2
  171. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.34.apk.sha256 +0 -1
  172. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.34.apk.sha256 +0 -1
  173. package/dist/src/session-capture-binding.js +0 -1
  174. package/dist/src/session-teardown.js +0 -1
@@ -1,43 +1,43 @@
1
- import{L as e,M as t,R as n,h as r,j as i,k as a,n as o,v as s,w as c}from"./sdk-contracts.js";import{$ as l,At as ee,C as te,Ct as ne,D as re,E as ie,F as ae,K as oe,L as se,Mt as ce,O as le,Ot as ue,P as de,R as fe,S as pe,T as me,_ as he,a as ge,at as _e,bt as ve,g as ye,h as be,jt as xe,kt as Se,m as Ce,n as we,nt as Te,ot as Ee,p as De,r as Oe,rt as ke,st as Ae,t as je,u as Me,v as Ne,w as Pe,x as Fe,yt as Ie}from"./tv-remote.js";import{c as Le,d as Re,f as ze,h as Be,j as Ve,l as He,m as Ue,s as We,u as Ge,v as u}from"./sdk-batch-runner.js";import{E as d,M as Ke,Mt as qe,Q as Je,S as Ye,T as Xe,Z as Ze,_t as Qe,at as $e,bt as et,c as tt,g as nt,j as rt,jt as it,k as at,m as ot,n as st,ot as ct,p as lt,st as ut,t as dt,tt as ft,x as pt}from"./back-mode.js";import{ft as mt}from"./sdk-io.js";import{a as ht,i as gt,n as _t,t as vt}from"./sdk-device.js";import{$r as yt,Ar as bt,Dn as xt,Hr as St,Ir as Ct,Jn as wt,Pr as Tt,Tn as Et,Xn as Dt,_ as Ot,er as kt,i as At,ii as jt,jr as Mt,kr as Nt,m as Pt,p as Ft,s as It,tn as Lt,wi as Rt}from"./sdk-batch.js";import{n as zt}from"./recording-export-quality.js";import{t as Bt}from"./recording-scope.js";import{a as Vt,i as Ht,r as Ut}from"./vars.js";import{n as Wt}from"./session.js";import{a as Gt,c as Kt,d as qt,f as Jt,g as Yt,h as Xt,i as Zt,l as Qt,n as $t,o as en,p as tn,s as nn,t as rn,u as an}from"./observability.js";import{n as on,t as sn}from"./success-text.js";import{t as cn}from"./alert-contract.js";import{h as ln,l as un,n as dn,v as fn,x as pn,y as mn}from"./settings.js";import{t as hn}from"./location-coordinates.js";import{t as gn}from"./snapshot-quality-backend-capabilities.js";import{t as _n}from"./mobile-snapshot-semantics.js";import{t as vn}from"./absence-observation-errors.js";import{n as yn,t as bn}from"./interaction-positionals.js";import{t as xn}from"./app-inventory.js";import{s as Sn,u as Cn}from"./file.js";import wn from"node:fs";import f from"node:path";const Tn=[`path`,`start`,`stop`,`doctor`,`mark`,`clear`],En=new Set(pt().map(e=>e.key));function Dn(e){let t=Qe(e);return Ve({stateDir:e.stateDir,daemonBaseUrl:e.daemonBaseUrl,daemonTransport:e.daemonTransport,daemonServerMode:e.daemonServerMode,...et(t),provider:e.provider,providerSessionId:e.providerSessionId,providerApp:e.providerApp,providerOsVersion:e.providerOsVersion,providerDeviceType:e.providerDeviceType,providerProject:e.providerProject,providerBuild:e.providerBuild,providerSessionName:e.providerSessionName,providerDeviceOrientation:e.providerDeviceOrientation,providerGeoLocation:e.providerGeoLocation,providerTimezone:e.providerTimezone,providerAppiumVersion:e.providerAppiumVersion,providerLanguage:e.providerLanguage,providerLocale:e.providerLocale,providerNetworkProfile:e.providerNetworkProfile,providerCustomNetwork:e.providerCustomNetwork,providerNoResignApp:e.providerNoResignApp,awsProjectArn:e.awsProjectArn,awsDeviceArn:e.awsDeviceArn,awsAppArn:e.awsAppArn,awsRegion:e.awsRegion,awsInteractionMode:e.awsInteractionMode,sessionIsolation:e.sessionIsolation,platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,androidDeviceAllowlist:e.androidDeviceAllowlist,osVersion:e.osVersion,imageTag:e.imageTag,physical:e.physical,surface:e.surface,activity:e.activity,launchConsole:e.launchConsole,launchArgs:e.launchArgs,relaunch:e.relaunch,shutdown:e.shutdown,saveScript:e.saveScript,testIme:e.testIme,noRecord:e.noRecord,recordAs:e.recordAs,record:e.record,backMode:e.backMode,metroHost:e.metroHost,metroPort:e.metroPort,bundleUrl:e.bundleUrl,launchUrl:e.launchUrl,...i(e,s),...ue(e),appsFilter:e.appsFilter,kind:e.kind,out:e.out,count:e.count,fps:e.fps,quality:e.quality,hideTouches:e.hideTouches,recordingScope:e.recordingScope,intervalMs:e.intervalMs,delayMs:e.delayMs,durationMs:e.durationMs,holdMs:e.holdMs,jitterPx:e.jitterPx,pixels:e.pixels,until:e.until,maxPasses:e.maxPasses,doubleTap:e.doubleTap,verify:e.verify,settle:e.settle,settleQuietMs:e.settleQuietMs,clickButton:e.clickButton,pauseMs:e.pauseMs,pattern:e.pattern,headless:e.headless,restart:e.restart,replayUpdate:e.replayUpdate,replayBackend:e.replayBackend,replayEnv:e.replayEnv,replayShellEnv:e.replayShellEnv,replayScriptSource:e.replayScriptSource,replayScriptSources:e.replayScriptSources,replayFrom:e.replayFrom,replayPlanDigest:e.replayPlanDigest,replayKeepSession:e.replayKeepSession,failFast:e.failFast,timeoutMs:e.timeoutMs,retries:e.retries,recordVideo:e.recordVideo,artifactsDir:e.artifactsDir,shardAll:e.shardAll,shardSplit:e.shardSplit,findFirst:e.findFirst,findLast:e.findLast,networkInclude:e.networkInclude,batchOnError:e.batchOnError,batchMaxSteps:e.batchMaxSteps,batchSteps:e.batchSteps,verbose:e.debug})}function On(e,t){return{...Dn(e),...t}}function kn(e,t){let n=e.inputSchema.properties;if(!n)return{};let r={},i=t;for(let e of Object.keys(n)){if(!En.has(e))continue;let t=i[e];An(t)&&(r[e]=t)}return r}function An(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`}function jn(e,t,r){if(Object.hasOwn(e,t))throw new n(`INVALID_ARGS`,r)}function Mn(e){return{kind:`operator`,source:e}}function Nn(e,t){return`${e} is not accepted as a tool argument. ${Pn(e,t)}`}function Pn(e,t){if(`operatorPath`in t)return t.operatorPath;let n=`for the process serving these tools.`,r=(t.envFlagKeys??[e]).map(mt).join(` or `);return r===``?`Set ${e} in ~/.agent-device/config.json ${n}`:`Set the ${r} environment variable${t.operatorConfig?` (or ${e} in ~/.agent-device/config.json)`:``} ${n}`}function Fn(e){if(e==null)return{};if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected object arguments.`);return e}function In(e,t){let r=e[t];if(!r||typeof r!=`object`||Array.isArray(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be an object.`);return r}function Ln(e,t){let r=e[t];if(typeof r!=`string`||r.length===0)throw new n(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return r}function Rn(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`string`)throw new n(`INVALID_ARGS`,`Expected ${t} to be a string.`);return r}}function p(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`string`||r.length===0)throw new n(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return r}}function zn(e,t){let r=e[t];if(typeof r!=`number`||!Number.isFinite(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be a finite number.`);return r}function Bn(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`boolean`)throw new n(`INVALID_ARGS`,`Expected ${t} to be a boolean.`);return r}}function Vn(e,t,r){let i=e[t];if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected ${t} to be one of: ${r.join(`, `)}.`);return i}function Hn(e,t,r){let i=e[t];if(i!==void 0){if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected ${t} to be one of: ${r.join(`, `)}.`);return i}}function Un(e,t){let r=e[t];if(r!==void 0){if(!r||typeof r!=`object`||Array.isArray(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be an object.`);return r}}function Wn(e,t){let r=e[t];if(r!==void 0){if(!Array.isArray(r)||r.some(e=>typeof e!=`string`))throw new n(`INVALID_ARGS`,`Expected ${t} to be an array of strings.`);return r}}function Gn(e,t,r,i){let a=new Set(t),o=Object.keys(e).filter(e=>!a.has(e));if(o.length>0)throw new n(`INVALID_ARGS`,`${r} has unknown field(s): ${o.join(`, `)}.`,i===void 0?void 0:{hint:i})}function m(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}const Kn=Mn({operatorConfig:!0}),qn=`readinessTimeoutMs was removed; add an explicit wait for the target before the interaction.`,Jn={session:{schema:{type:`string`,description:`Agent-device session name.`},read:e=>p(e,`session`),flagKey:`session`,flagIn:[`input`]},platform:{schema:{type:`string`,enum:gt,description:`Platform selector used to resolve a device.`},read:e=>Hn(e,`platform`,gt),flagKey:`platform`,flagIn:[`input`,`selection`]},deviceTarget:{schema:{type:`string`,enum:_t,description:`Device target form. Maps to the CLI --target flag.`},read:tr,clientKey:`target`,flagKey:`target`,flagIn:[`input`,`selection`]},target:{schema:{type:`string`,enum:_t,description:`Alias for deviceTarget on commands without a UI target field. Interaction commands reserve target for the UI element.`}},device:{schema:{type:`string`,description:`Device name selector (a UDID belongs in udid, a serial in serial).`},read:e=>p(e,`device`),flagKey:`device`,flagIn:[`input`,`selection`]},udid:{schema:{type:`string`,description:`Apple device or simulator UDID; the selector that pins one device when several share a name.`},read:e=>p(e,`udid`),flagKey:`udid`,flagIn:[`input`,`selection`]},serial:{schema:{type:`string`,description:`Android, HarmonyOS, or Vega VVD serial selector.`},read:e=>p(e,`serial`),flagKey:`serial`,flagIn:[`input`,`selection`]},iosSimulatorDeviceSet:{schema:{type:`string`,description:`iOS simulator device-set path used for device resolution.`},read:e=>p(e,`iosSimulatorDeviceSet`),audience:Mn({envFlagKeys:[],operatorConfig:!0}),flagKey:`iosSimulatorDeviceSet`,flagIn:[`input`,`selection`]},iosXctestrunFile:{schema:{type:`string`,description:`Externally built iOS XCTest runner .xctestrun artifact path. Build it with the same agent-device version.`},read:e=>p(e,`iosXctestrunFile`),audience:Kn,flagKey:`iosXctestrunFile`,flagIn:[`input`]},iosXctestDerivedDataPath:{schema:{type:`string`,description:`Derived data path for external iOS XCTest runner execution.`},read:e=>p(e,`iosXctestDerivedDataPath`),audience:Kn,flagKey:`iosXctestDerivedDataPath`,flagIn:[`input`]},iosXctestEnvDir:{schema:{type:`string`,description:`Writable directory for iOS XCTest runner env overlays.`},read:e=>p(e,`iosXctestEnvDir`),audience:Kn,flagKey:`iosXctestEnvDir`,flagIn:[`input`]},androidDeviceAllowlist:{schema:{type:`string`,description:`Android serial allowlist used for device resolution.`},read:e=>p(e,`androidDeviceAllowlist`),flagKey:`androidDeviceAllowlist`,flagIn:[`input`,`selection`]},noRecord:{read:e=>Bn(e,`noRecord`),flagKey:`noRecord`,flagIn:[`input`,`selection`]},readinessTimeoutMs:{audience:{kind:`retired`,message:qn},read:e=>jn(e,`readinessTimeoutMs`,qn)},daemonBaseUrl:{schema:{type:`string`,description:`Remote daemon base URL.`},read:e=>p(e,`daemonBaseUrl`),audience:Kn},daemonAuthToken:{schema:{type:`string`,description:`Remote daemon auth token.`},read:e=>p(e,`daemonAuthToken`),audience:Kn},tenant:{schema:{type:`string`,description:`Remote tenant identifier.`},read:e=>p(e,`tenant`)},runId:{schema:{type:`string`,description:`Lease run identifier.`},read:e=>p(e,`runId`)},leaseId:{schema:{type:`string`,description:`Existing lease identifier.`},read:e=>p(e,`leaseId`)},cwd:{schema:{type:`string`,description:`Working directory for command execution.`},read:e=>p(e,`cwd`),audience:Mn({operatorPath:`Start the process serving these tools in the desired working directory, or pass absolute paths.`})},debug:{schema:{type:`boolean`,description:`Enable debug diagnostics.`},read:e=>Bn(e,`debug`)}},Yn=Object.entries(Jn),Xn=Object.fromEntries(Yn.flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]));function Zn(e){for(let[t,n]of Object.entries(Xn))n.kind===`retired`&&jn(e,t,n.message)}function Qn(){return Object.fromEntries(Yn.flatMap(([e,t])=>t.schema?[[e,t.schema]]:[]))}function $n(e,t={}){let n={};for(let[r,i]of Yn)i.read&&(n[r]=i.read(e,t));return n}function h(e){let t={};for(let[n,r]of Yn)r.read&&(t[r.clientKey??n]=e[n]);return m(t)}function er(e,t){let n={};for(let[r,i]of Yn){if(i.flagIn===void 0||!i.flagIn.includes(t))continue;let a=t===`selection`?i.clientKey??r:r;n[a]=e[i.flagKey]}return n}function tr(e,t){let r=Hn(e,`deviceTarget`,_t);if(t.readTargetAlias===!1||e.target===void 0)return r;let i=Hn(e,`target`,_t);if(r!==void 0&&i!==r)throw new n(`INVALID_ARGS`,`Expected target alias to match deviceTarget when both are set.`);return r??i}function g(e,t){return n=>_(e,t?t(n):[],n)}function _(e,t,n,r){return{command:e,positionals:t,...r?{input:r}:{},options:nr(n)}}function nr(e){let t=rr(e.deviceTarget??e.target);if(t===void 0&&e.target===void 0)return e;let{target:n,...r}=e;return t===void 0?r:{...r,target:t}}function rr(e){return e===`mobile`||e===`tv`||e===`desktop`?e:void 0}function v(e){return m(er(e,`input`))}function ir(e){return m({record:e.record})}function ar(e){return er(e,`selection`)}function or(e){return m({depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw})}function sr(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function cr(e){return m({settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs})}function lr(e){return m({count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap})}function ur(e){return it(e).spec}function dr(e){if(`ref`in e&&e.ref!==void 0)return m({kind:`ref`,ref:e.ref,label:e.label});if(`selector`in e&&e.selector!==void 0)return{kind:`selector`,selector:e.selector};let t=e;return{kind:`point`,x:t.x,y:t.y}}function fr(e){let t=mr(e);if(typeof t.ref==`string`)return[t.ref,...gr(t.label)];if(typeof t.selector==`string`)return[t.selector];if(t.kind===`point`||t.x!==void 0||t.y!==void 0)return[String(hr(t.x,`x`)),String(hr(t.y,`y`))];throw new n(`INVALID_ARGS`,`interaction requires @ref, selector, or point target`)}function pr(e){let t=mr(e);if(typeof t.ref==`string`)return[t.ref,...gr(t.label)];if(typeof t.selector==`string`)return[t.selector];throw new n(`INVALID_ARGS`,`element command requires @ref or selector target`)}function mr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected target object.`);let t=e,r=t.target;return r&&typeof r==`object`&&!Array.isArray(r)?r:t}function hr(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw new n(`INVALID_ARGS`,`point target requires numeric ${t}.`);return e}function gr(e){return typeof e==`string`&&e.length>0?[e]:[]}function _r(e){let t=bt(e);if(!t.ok)throw new n(t.code,t.message);return`ref`in t?{ref:t.ref,label:xr(e.slice(1))}:{selector:t.selector}}function vr(e){let t=Mt(e);if(!t.ok)throw new n(t.code,t.message);return t.format}function yr(e,t={}){let r=St(e,t);if(!r)throw new n(`INVALID_ARGS`,Nt);return r}function br(e,t){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}throw new n(`INVALID_ARGS`,`${t} must be a JSON object`)}function xr(e){return e.join(` `).trim()||void 0}function Sr(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function Cr(e,t){if(e===void 0)return;let r=Number(e);if(Number.isFinite(r))return r;throw new n(`INVALID_ARGS`,`${t} must be a finite number.`)}function wr(e){return e===void 0?void 0:Number(e)}function y(e){return e===void 0?[]:[e]}function b(e){return e===void 0?[]:[String(e)]}function x(e,t){if(e===void 0||e===``)throw new n(`INVALID_ARGS`,t);return e}function S(e,t){if(typeof e!=`string`||e.length===0)throw new n(`INVALID_ARGS`,t);return e}function Tr(e){return Or(e.description,e.cliDetail)}function Er(e){return Or(e.description,e.mcpDetail)}function Dr(e,t){return{...e,description:t}}function Or(e,t){return t?`${e} ${t}`:e}function kr(e){return e}const Ar=[`ref`,`selector`,`point`];function jr(e,t=[]){return{type:`object`,properties:{...Qn(),...e},...t.length>0?{required:t}:{},additionalProperties:!1}}function C(e,t=[],n){return{type:`object`,...n?{description:n}:{},properties:e,...t.length>0?{required:t}:{}}}function Mr(e){return{type:`object`,description:e,properties:{x:{type:`number`},y:{type:`number`}},required:[`x`,`y`],additionalProperties:!1}}function w(e,t){return{type:`string`,enum:e,...t?{description:t}:{}}}function T(e){return{type:`string`,const:e}}function E(e){return{type:`string`,...e?{description:e}:{}}}function Nr(e){return{type:[`string`,`null`],...e?{description:e}:{}}}function D(e,t={}){return{type:`number`,...e?{description:e}:{},...t.min===void 0?{}:{minimum:t.min},...t.max===void 0?{}:{maximum:t.max}}}function Pr(e){return{type:`integer`,...e?{description:e}:{}}}function O(e){return{type:`boolean`,...e?{description:e}:{}}}function Fr(e){return{type:`array`,items:{type:`string`},...e?{description:e}:{}}}function k(e){return{type:`object`,additionalProperties:!0,...e?{description:e}:{}}}function A(e){return{...e,required:!0}}function j(e,t={}){return L(E(e),t.allowEmpty===!0?Rn:p)}function Ir(e){return{schema:{type:`null`},required:!1,audience:{kind:`retired`,message:e},read:(t,n)=>jn(t,n,e)}}function Lr(e,t){return{...e,audience:{kind:`operator`,source:t}}}function M(e,t={}){return L(D(e,t),(e,n)=>Be(e,n,t))}function N(e,t={}){return L(li(e,t),(e,n)=>Ue(e,n,t))}function P(e){return L(O(e),Bn)}function Rr(e){return Br(zr(e))}function zr(e){let[t,...n]=Ye(e).filter(e=>e.inputDescription!==void 0);if(!t)throw Error(`Flag ${e} declares no inputDescription; optionField cannot derive a field`);if(n.length>0)throw Error(`Flag ${e} declares inputDescription more than once`);return t}function Br(e){let t=e.inputDescription,n={min:e.min,max:e.max};switch(e.type){case`boolean`:return P(t);case`int`:return N(t,n);case`number`:return M(t,n);case`string`:return j(t);case`enum`:return F(Vr(e),t);case`booleanOrString`:throw Error(`Flag ${e.key} is booleanOrString; declare its field shape explicitly with jsonSchemaField`)}}function Vr(e){let t=e.enumValues;if(!t)throw Error(`Flag ${e.key} is an enum with no enumValues`);return t}function F(e,t){return L(w(e,t),(t,n)=>Hn(t,n,e))}function Hr(e){return L(k(e),Un)}function Ur(e){return L(Fr(e),Wn)}function I(e){return L(e,(e,t)=>e[t])}function Wr(e,t){return L(e,t)}function Gr(){return L(pi(),(e,t)=>e[t]===void 0?void 0:ni(e,t))}function Kr(){return L(mi(),(e,t)=>e[t]===void 0?void 0:ri(e,t))}function qr(e){return L(Mr(e),(e,t)=>e[t]===void 0?void 0:ii(e,t))}function Jr(e,t){return L({type:`array`,description:e,items:Mr(`One contact point.`),minItems:t.min,maxItems:t.max},(e,t)=>e[t]===void 0?void 0:Yr(e,t))}function Yr(e,t){let r=e[t];if(!Array.isArray(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be an array of points.`);return r.map((e,n)=>{let r=`${t}[${n}]`;return ii({[r]:e},r)})}function Xr(){return{depth:N(`Snapshot traversal depth.`,{min:0}),scope:j(`Snapshot scope selector used before resolution.`),raw:P(`Use raw snapshot data during selector resolution.`)}}function Zr(){return{count:N(`Number of press/click repetitions.`,{min:1}),intervalMs:N(`Delay between repeated press/click actions.`,{min:0}),holdMs:N(`Hold duration for each action.`,{min:0}),jitterPx:N(`Deterministic per-axis coordinate jitter in pixels (each press offsets x and y by up to this amount).`,{min:0}),doubleTap:P(`Request a double-tap action.`)}}function Qr(){return{osVersion:$r(`osVersion`),imageTag:$r(`imageTag`),physical:$r(`physical`)}}function $r(e){return Wr(Rr(e).schema,t=>it({[e]:t[e]}).spec[e])}function ei(e){return jr(ui(e),di(e))}function ti(e,t){let r=Fn(e),i=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{let i=t.read(r,e);if(t.required&&i===void 0)throw new n(`INVALID_ARGS`,`Expected ${e} to be set.`);return i===void 0?[]:[[e,i]]})),a=$n(r,{readTargetAlias:!Object.hasOwn(t,`target`)});return m({...a,...h(a),...i})}function ni(e,t){let n=In(e,t),r=Vn(n,`kind`,Ar);switch(r){case`ref`:return{kind:r,ref:Ln(n,`ref`),label:p(n,`label`)};case`selector`:return{kind:r,selector:Ln(n,`selector`)};case`point`:return{kind:r,x:zn(n,`x`),y:zn(n,`y`)}}}function ri(e,t){let n=In(e,t),r=Vn(n,`kind`,[`ref`,`selector`]);return r===`ref`?{kind:r,ref:Ln(n,`ref`),label:p(n,`label`)}:{kind:r,selector:Ln(n,`selector`)}}function ii(e,t){let n=In(e,t);return{x:zn(n,`x`),y:zn(n,`y`)}}function ai(e){switch(e.kind){case`ref`:return{ref:e.ref,label:e.label};case`selector`:return{selector:e.selector};case`point`:return{x:e.x,y:e.y}}}function oi(e){switch(e.kind){case`ref`:return{ref:e.ref,label:e.label};case`selector`:return{selector:e.selector}}}function si(e){return{count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap}}function ci(e){return{depth:e.depth,scope:e.scope,raw:e.raw}}function L(e,t){return{schema:e,required:!1,read:t}}function li(e,t){return{...Pr(e),...t.min===void 0?{}:{minimum:t.min},...t.max===void 0?{}:{maximum:t.max}}}function ui(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.audience?.kind!==`retired`).map(([e,t])=>[e,t.schema]))}function di(e){return Object.entries(e).flatMap(([e,t])=>t.required?[e]:[])}function fi(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]))}function pi(){return{oneOf:[...hi(),{type:`object`,properties:{kind:{type:`string`,const:`point`},x:{type:`number`},y:{type:`number`}},required:[`kind`,`x`,`y`],additionalProperties:!1}],description:`UI target. This is separate from deviceTarget, which selects the device form.`}}function mi(){return{oneOf:hi(),description:`UI element target by snapshot ref or selector expression.`}}function hi(){return[{type:`object`,properties:{kind:{type:`string`,const:`ref`},ref:{type:`string`,description:`Snapshot element ref such as @e12.`},label:{type:`string`,description:`Optional human label for the ref.`}},required:[`kind`,`ref`],additionalProperties:!1},{type:`object`,properties:{kind:{type:`string`,const:`selector`},selector:{type:`string`,description:`Agent-device selector expression.`}},required:[`kind`,`selector`],additionalProperties:!1}]}function R(e,t,n,r){return kr({name:e,description:t,inputSchema:ei(n),readInput:r?.readInput??(e=>ti(e,n)),inputAudience:fi(n),...r?.parseableOutput?{parseableOutput:!0}:{}})}function z(e){let t=Dr(e.text,e.metadata.description),n=t.mcpDetail?{mcpDetail:t.mcpDetail}:{},r={...e.metadata,...n},i={name:r.name,description:r.description,inputSchema:r.inputSchema,...n,invoke:async(t,n)=>await e.run(t,r.readInput(n))};return{name:e.name,metadata:r,definition:i,cliSchema:{...e.cliSchema,text:t},cliReader:e.cliReader,daemonWriter:e.daemonWriter,cliOutputFormatter:e.cliOutputFormatter,text:t}}function gi(e){return z({name:e.name,text:e.text,metadata:R(e.name,e.description,{}),run:e.run,cliSchema:{},cliReader:(e,t)=>v(t),daemonWriter:g(e.name),cliOutputFormatter:e.cliOutputFormatter})}function B(e){let t={},n={},r={},i={};for(let a of e.commands)_i(t,`CLI schema`,a.name,a.cliSchema),_i(n,`CLI reader`,a.name,a.cliReader),a.daemonWriter&&_i(r,`daemon writer`,a.name,a.daemonWriter),a.cliOutputFormatter&&_i(i,`CLI output formatter`,a.name,a.cliOutputFormatter);return{name:e.name,clientSurface:e.clientSurface,metadata:e.commands.map(e=>e.metadata),definitions:e.commands.map(e=>e.definition),cliSchemas:t,cliReaders:n,daemonWriters:r,cliOutputFormatters:i}}function _i(e,t,n,r){if(Object.hasOwn(e,n))throw Error(`Duplicate command family ${t}: ${n}`);e[n]=r}function V(e){return({result:t})=>e(t)}const H=V(vi);function vi(e){return{data:e,text:sn(e)}}function yi(e){return[...typeof e.warning==`string`&&e.warning.trim()!==``?[e.warning]:[],...on(e)].map(e=>Si(e)).filter(e=>e.length>0)}function bi(e,t){let n=e??``,r=yi(t).filter(e=>!n.includes(e)).map(e=>`Warning: ${e}`);return r.length===0?e??null:[...n===``?[]:[n],...r].join(`
2
- `)}function xi(e,t,n){let r=t??{};if(n===`text`)return{...e,text:bi(e.text,r)};let i=`${e.text??``}\n${e.stderr??``}`,a=yi(r).filter(e=>!i.includes(e)).map(e=>`Warning: ${e}`);if(a.length===0)return e;let o=e.stderr??``;return{...e,stderr:`${o}${o===``||o.endsWith(`
1
+ import{L as e,M as t,R as n,h as r,j as i,k as a,n as o,v as s,w as c}from"./sdk-contracts.js";import{$ as l,At as ee,C as te,Ct as ne,D as re,E as ie,F as ae,K as oe,L as se,Mt as ce,O as le,Ot as ue,P as de,R as fe,S as pe,T as me,_ as he,a as ge,at as _e,bt as ve,g as ye,h as be,jt as xe,kt as Se,m as Ce,n as we,nt as Te,ot as Ee,p as De,r as Oe,rt as ke,st as Ae,t as je,u as Me,v as Ne,w as Pe,x as Fe,yt as Ie}from"./tv-remote.js";import{M as Le,c as Re,d as ze,f as Be,g as Ve,h as He,l as Ue,p as We,u as Ge,y as u}from"./sdk-batch-runner.js";import{E as d,M as Ke,Mt as qe,Q as Je,S as Ye,T as Xe,Z as Ze,_t as Qe,at as $e,bt as et,c as tt,g as nt,j as rt,jt as it,k as at,m as ot,n as st,ot as ct,p as lt,st as ut,t as dt,tt as ft,x as pt}from"./back-mode.js";import{ft as mt}from"./sdk-io.js";import{a as ht,n as gt,o as _t,r as vt,t as yt}from"./sdk-device.js";import{$r as bt,Ar as xt,Dn as St,Hr as Ct,Ir as wt,Jn as Tt,M as Et,Pr as Dt,Xn as Ot,_ as kt,er as At,i as jt,ii as Mt,jr as Nt,kr as Pt,m as Ft,p as It,rn as Lt,s as Rt,wi as zt}from"./sdk-batch.js";import{n as Bt}from"./recording-export-quality.js";import{t as Vt}from"./recording-scope.js";import{a as Ht,i as Ut,r as Wt}from"./vars.js";import{n as Gt}from"./session.js";import{a as Kt,c as qt,d as Jt,f as Yt,g as Xt,h as Zt,i as Qt,l as $t,n as en,o as tn,p as nn,s as rn,t as an,u as on}from"./observability.js";import{n as sn,t as cn}from"./success-text.js";import{t as ln}from"./alert-contract.js";import{h as un,l as dn,n as fn,v as pn,x as mn,y as hn}from"./settings.js";import{t as gn}from"./location-coordinates.js";import{t as _n}from"./snapshot-quality-backend-capabilities.js";import{t as vn}from"./mobile-snapshot-semantics.js";import{t as yn}from"./absence-observation-errors.js";import{n as bn,t as xn}from"./interaction-positionals.js";import{t as Sn}from"./app-inventory.js";import{s as Cn,u as wn}from"./file.js";import Tn from"node:fs";import f from"node:path";const En=[`path`,`start`,`stop`,`doctor`,`mark`,`clear`],Dn=new Set(pt().map(e=>e.key));function On(e){let t=Qe(e);return Le({stateDir:e.stateDir,daemonBaseUrl:e.daemonBaseUrl,daemonTransport:e.daemonTransport,daemonServerMode:e.daemonServerMode,...et(t),provider:e.provider,providerSessionId:e.providerSessionId,providerApp:e.providerApp,providerOsVersion:e.providerOsVersion,providerDeviceType:e.providerDeviceType,providerProject:e.providerProject,providerBuild:e.providerBuild,providerSessionName:e.providerSessionName,providerDeviceOrientation:e.providerDeviceOrientation,providerGeoLocation:e.providerGeoLocation,providerTimezone:e.providerTimezone,providerAppiumVersion:e.providerAppiumVersion,providerLanguage:e.providerLanguage,providerLocale:e.providerLocale,providerNetworkProfile:e.providerNetworkProfile,providerCustomNetwork:e.providerCustomNetwork,providerNoResignApp:e.providerNoResignApp,providerNetworkLogs:e.providerNetworkLogs,providerNetworkHosts:e.providerNetworkHosts,awsProjectArn:e.awsProjectArn,awsDeviceArn:e.awsDeviceArn,awsAppArn:e.awsAppArn,awsRegion:e.awsRegion,awsInteractionMode:e.awsInteractionMode,sessionIsolation:e.sessionIsolation,platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,androidDeviceAllowlist:e.androidDeviceAllowlist,osVersion:e.osVersion,imageTag:e.imageTag,physical:e.physical,surface:e.surface,activity:e.activity,launchConsole:e.launchConsole,launchArgs:e.launchArgs,relaunch:e.relaunch,shutdown:e.shutdown,saveScript:e.saveScript,testIme:e.testIme,noRecord:e.noRecord,recordAs:e.recordAs,record:e.record,backMode:e.backMode,metroHost:e.metroHost,metroPort:e.metroPort,bundleUrl:e.bundleUrl,launchUrl:e.launchUrl,...i(e,s),...ue(e),appsFilter:e.appsFilter,kind:e.kind,out:e.out,count:e.count,fps:e.fps,quality:e.quality,hideTouches:e.hideTouches,recordingScope:e.recordingScope,intervalMs:e.intervalMs,delayMs:e.delayMs,durationMs:e.durationMs,holdMs:e.holdMs,jitterPx:e.jitterPx,pixels:e.pixels,until:e.until,maxPasses:e.maxPasses,doubleTap:e.doubleTap,verify:e.verify,settle:e.settle,settleQuietMs:e.settleQuietMs,clickButton:e.clickButton,pauseMs:e.pauseMs,pattern:e.pattern,headless:e.headless,pick:e.pick,restart:e.restart,replayUpdate:e.replayUpdate,replayBackend:e.replayBackend,replayEnv:e.replayEnv,replayShellEnv:e.replayShellEnv,replayScriptSource:e.replayScriptSource,replayScriptSources:e.replayScriptSources,replayFrom:e.replayFrom,replayPlanDigest:e.replayPlanDigest,replayKeepSession:e.replayKeepSession,failFast:e.failFast,timeoutMs:e.timeoutMs,retries:e.retries,recordVideo:e.recordVideo,artifactsDir:e.artifactsDir,shardAll:e.shardAll,shardSplit:e.shardSplit,findFirst:e.findFirst,findLast:e.findLast,networkInclude:e.networkInclude,batchOnError:e.batchOnError,batchMaxSteps:e.batchMaxSteps,batchSteps:e.batchSteps,verbose:e.debug})}function kn(e,t){return{...On(e),...t}}function An(e,t){let n=e.inputSchema.properties;if(!n)return{};let r={},i=t;for(let e of Object.keys(n)){if(!Dn.has(e))continue;let t=i[e];jn(t)&&(r[e]=t)}return r}function jn(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`}function Mn(e,t,r){if(Object.hasOwn(e,t))throw new n(`INVALID_ARGS`,r)}function Nn(e){return{kind:`operator`,source:e}}function Pn(e,t){return`${e} is not accepted as a tool argument. ${Fn(e,t)}`}function Fn(e,t){if(`operatorPath`in t)return t.operatorPath;let n=`for the process serving these tools.`,r=(t.envFlagKeys??[e]).map(mt).join(` or `);return r===``?`Set ${e} in ~/.agent-device/config.json ${n}`:`Set the ${r} environment variable${t.operatorConfig?` (or ${e} in ~/.agent-device/config.json)`:``} ${n}`}function In(e){if(e==null)return{};if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected object arguments.`);return e}function Ln(e,t){let r=e[t];if(!r||typeof r!=`object`||Array.isArray(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be an object.`);return r}function Rn(e,t){let r=e[t];if(typeof r!=`string`||r.length===0)throw new n(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return r}function zn(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`string`)throw new n(`INVALID_ARGS`,`Expected ${t} to be a string.`);return r}}function p(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`string`||r.length===0)throw new n(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return r}}function Bn(e,t){let r=e[t];if(typeof r!=`number`||!Number.isFinite(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be a finite number.`);return r}function Vn(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`boolean`)throw new n(`INVALID_ARGS`,`Expected ${t} to be a boolean.`);return r}}function Hn(e,t,r){let i=e[t];if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected ${t} to be one of: ${r.join(`, `)}.`);return i}function Un(e,t,r){let i=e[t];if(i!==void 0){if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected ${t} to be one of: ${r.join(`, `)}.`);return i}}function Wn(e,t){let r=e[t];if(r!==void 0){if(!r||typeof r!=`object`||Array.isArray(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be an object.`);return r}}function Gn(e,t){let r=e[t];if(r!==void 0){if(!Array.isArray(r)||r.some(e=>typeof e!=`string`))throw new n(`INVALID_ARGS`,`Expected ${t} to be an array of strings.`);return r}}function Kn(e,t,r,i){let a=new Set(t),o=Object.keys(e).filter(e=>!a.has(e));if(o.length>0)throw new n(`INVALID_ARGS`,`${r} has unknown field(s): ${o.join(`, `)}.`,i===void 0?void 0:{hint:i})}function m(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}const qn=Nn({operatorConfig:!0}),Jn=`readinessTimeoutMs was removed; add an explicit wait for the target before the interaction.`,Yn={session:{schema:{type:`string`,description:`Agent-device session name.`},read:e=>p(e,`session`),flagKey:`session`,flagIn:[`input`]},platform:{schema:{type:`string`,enum:ht,description:`Platform selector used to resolve a device.`},read:e=>Un(e,`platform`,ht),flagKey:`platform`,flagIn:[`input`,`selection`]},deviceTarget:{schema:{type:`string`,enum:vt,description:`Device target form. Maps to the CLI --target flag.`},read:rr,clientKey:`target`,flagKey:`target`,flagIn:[`input`,`selection`]},target:{schema:{type:`string`,enum:vt,description:`Alias for deviceTarget on commands without a UI target field. Interaction commands reserve target for the UI element.`}},device:{schema:{type:`string`,description:`Device name selector (a UDID belongs in udid, a serial in serial).`},read:e=>p(e,`device`),flagKey:`device`,flagIn:[`input`,`selection`]},udid:{schema:{type:`string`,description:`Apple device or simulator UDID; the selector that pins one device when several share a name.`},read:e=>p(e,`udid`),flagKey:`udid`,flagIn:[`input`,`selection`]},serial:{schema:{type:`string`,description:`Android, HarmonyOS, or Vega VVD serial selector.`},read:e=>p(e,`serial`),flagKey:`serial`,flagIn:[`input`,`selection`]},iosSimulatorDeviceSet:{schema:{type:`string`,description:`iOS simulator device-set path used for device resolution.`},read:e=>p(e,`iosSimulatorDeviceSet`),audience:Nn({envFlagKeys:[],operatorConfig:!0}),flagKey:`iosSimulatorDeviceSet`,flagIn:[`input`,`selection`]},iosXctestrunFile:{schema:{type:`string`,description:`Externally built iOS XCTest runner .xctestrun artifact path. Build it with the same agent-device version.`},read:e=>p(e,`iosXctestrunFile`),audience:qn,flagKey:`iosXctestrunFile`,flagIn:[`input`]},iosXctestDerivedDataPath:{schema:{type:`string`,description:`Derived data path for external iOS XCTest runner execution.`},read:e=>p(e,`iosXctestDerivedDataPath`),audience:qn,flagKey:`iosXctestDerivedDataPath`,flagIn:[`input`]},iosXctestEnvDir:{schema:{type:`string`,description:`Writable directory for iOS XCTest runner env overlays.`},read:e=>p(e,`iosXctestEnvDir`),audience:qn,flagKey:`iosXctestEnvDir`,flagIn:[`input`]},androidDeviceAllowlist:{schema:{type:`string`,description:`Android serial allowlist used for device resolution.`},read:e=>p(e,`androidDeviceAllowlist`),flagKey:`androidDeviceAllowlist`,flagIn:[`input`,`selection`]},noRecord:{read:e=>Vn(e,`noRecord`),flagKey:`noRecord`,flagIn:[`input`,`selection`]},readinessTimeoutMs:{audience:{kind:`retired`,message:Jn},read:e=>Mn(e,`readinessTimeoutMs`,Jn)},daemonBaseUrl:{schema:{type:`string`,description:`Remote daemon base URL.`},read:e=>p(e,`daemonBaseUrl`),audience:qn},daemonAuthToken:{schema:{type:`string`,description:`Remote daemon auth token.`},read:e=>p(e,`daemonAuthToken`),audience:qn},tenant:{schema:{type:`string`,description:`Remote tenant identifier.`},read:e=>p(e,`tenant`)},runId:{schema:{type:`string`,description:`Lease run identifier.`},read:e=>p(e,`runId`)},leaseId:{schema:{type:`string`,description:`Existing lease identifier.`},read:e=>p(e,`leaseId`)},cwd:{schema:{type:`string`,description:`Working directory for command execution.`},read:e=>p(e,`cwd`),audience:Nn({operatorPath:`Start the process serving these tools in the desired working directory, or pass absolute paths.`})},debug:{schema:{type:`boolean`,description:`Enable debug diagnostics.`},read:e=>Vn(e,`debug`)}},Xn=Object.entries(Yn),Zn=Object.fromEntries(Xn.flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]));function Qn(e){for(let[t,n]of Object.entries(Zn))n.kind===`retired`&&Mn(e,t,n.message)}function $n(){return Object.fromEntries(Xn.flatMap(([e,t])=>t.schema?[[e,t.schema]]:[]))}function er(e,t={}){let n={};for(let[r,i]of Xn)i.read&&(n[r]=i.read(e,t));return n}function tr(e){let t={};for(let[n,r]of Xn)r.read&&(t[r.clientKey??n]=e[n]);return m(t)}function nr(e,t){let n={};for(let[r,i]of Xn){if(i.flagIn===void 0||!i.flagIn.includes(t))continue;let a=t===`selection`?i.clientKey??r:r;n[a]=e[i.flagKey]}return n}function rr(e,t){let r=Un(e,`deviceTarget`,vt);if(t.readTargetAlias===!1||e.target===void 0)return r;let i=Un(e,`target`,vt);if(r!==void 0&&i!==r)throw new n(`INVALID_ARGS`,`Expected target alias to match deviceTarget when both are set.`);return r??i}function h(e,t){return n=>g(e,t?t(n):[],n)}function g(e,t,n,r){return{command:e,positionals:t,...r?{input:r}:{},options:ir(n)}}function ir(e){let t=ar(e.deviceTarget??e.target);if(t===void 0&&e.target===void 0)return e;let{target:n,...r}=e;return t===void 0?r:{...r,target:t}}function ar(e){return e===`mobile`||e===`tv`||e===`desktop`?e:void 0}function _(e){return m(nr(e,`input`))}function or(e){return m({record:e.record})}function sr(e){return nr(e,`selection`)}function cr(e){return m({depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw})}function lr(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function ur(e){return m({settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs})}function dr(e){return m({count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap})}function fr(e){return it(e).spec}function pr(e){if(`ref`in e&&e.ref!==void 0)return m({kind:`ref`,ref:e.ref,label:e.label});if(`selector`in e&&e.selector!==void 0)return{kind:`selector`,selector:e.selector};let t=e;return{kind:`point`,x:t.x,y:t.y}}function mr(e){let t=gr(e);if(typeof t.ref==`string`)return[t.ref,...vr(t.label)];if(typeof t.selector==`string`)return[t.selector];if(t.kind===`point`||t.x!==void 0||t.y!==void 0)return[String(_r(t.x,`x`)),String(_r(t.y,`y`))];throw new n(`INVALID_ARGS`,`interaction requires @ref, selector, or point target`)}function hr(e){let t=gr(e);if(typeof t.ref==`string`)return[t.ref,...vr(t.label)];if(typeof t.selector==`string`)return[t.selector];throw new n(`INVALID_ARGS`,`element command requires @ref or selector target`)}function gr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected target object.`);let t=e,r=t.target;return r&&typeof r==`object`&&!Array.isArray(r)?r:t}function _r(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw new n(`INVALID_ARGS`,`point target requires numeric ${t}.`);return e}function vr(e){return typeof e==`string`&&e.length>0?[e]:[]}function yr(e){let t=xt(e);if(!t.ok)throw new n(t.code,t.message);return`ref`in t?{ref:t.ref,label:Cr(e.slice(1))}:{selector:t.selector}}function br(e){let t=Nt(e);if(!t.ok)throw new n(t.code,t.message);return t.format}function xr(e,t={}){let r=Ct(e,t);if(!r)throw new n(`INVALID_ARGS`,Pt);return r}function Sr(e,t){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}throw new n(`INVALID_ARGS`,`${t} must be a JSON object`)}function Cr(e){return e.join(` `).trim()||void 0}function wr(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function Tr(e,t){if(e===void 0)return;let r=Number(e);if(Number.isFinite(r))return r;throw new n(`INVALID_ARGS`,`${t} must be a finite number.`)}function Er(e){return e===void 0?void 0:Number(e)}function v(e){return e===void 0?[]:[e]}function y(e){return e===void 0?[]:[String(e)]}function b(e,t){if(e===void 0||e===``)throw new n(`INVALID_ARGS`,t);return e}function x(e,t){if(typeof e!=`string`||e.length===0)throw new n(`INVALID_ARGS`,t);return e}function Dr(e){return Ar(e.description,e.cliDetail)}function Or(e){return Ar(e.description,e.mcpDetail)}function kr(e,t){return{...e,description:t}}function Ar(e,t){return t?`${e} ${t}`:e}function jr(e){return e}const Mr=[`ref`,`selector`,`point`];function Nr(e,t=[]){return{type:`object`,properties:{...$n(),...e},...t.length>0?{required:t}:{},additionalProperties:!1}}function S(e,t=[],n){return{type:`object`,...n?{description:n}:{},properties:e,...t.length>0?{required:t}:{}}}function Pr(e){return{type:`object`,description:e,properties:{x:{type:`number`},y:{type:`number`}},required:[`x`,`y`],additionalProperties:!1}}function C(e,t){return{type:`string`,enum:e,...t?{description:t}:{}}}function w(e){return{type:`string`,const:e}}function T(e){return{type:`string`,...e?{description:e}:{}}}function Fr(e){return{type:[`string`,`null`],...e?{description:e}:{}}}function E(e,t={}){return{type:`number`,...e?{description:e}:{},...t.min===void 0?{}:{minimum:t.min},...t.max===void 0?{}:{maximum:t.max}}}function Ir(e){return{type:`integer`,...e?{description:e}:{}}}function D(e){return{type:`boolean`,...e?{description:e}:{}}}function Lr(e){return{type:`array`,items:{type:`string`},...e?{description:e}:{}}}function O(e){return{type:`object`,additionalProperties:!0,...e?{description:e}:{}}}function k(e){return{...e,required:!0}}function A(e,t={}){return I(T(e),t.allowEmpty===!0?zn:p)}function Rr(e){return{schema:{type:`null`},required:!1,audience:{kind:`retired`,message:e},read:(t,n)=>Mn(t,n,e)}}function zr(e,t){return{...e,audience:{kind:`operator`,source:t}}}function j(e,t={}){return I(E(e,t),(e,n)=>Ve(e,n,t))}function M(e,t={}){return I(di(e,t),(e,n)=>He(e,n,t))}function N(e){return I(D(e),Vn)}function Br(e){return Hr(Vr(e))}function Vr(e){let[t,...n]=Ye(e).filter(e=>e.inputDescription!==void 0);if(!t)throw Error(`Flag ${e} declares no inputDescription; optionField cannot derive a field`);if(n.length>0)throw Error(`Flag ${e} declares inputDescription more than once`);return t}function Hr(e){let t=e.inputDescription,n={min:e.min,max:e.max};switch(e.type){case`boolean`:return N(t);case`int`:return M(t,n);case`number`:return j(t,n);case`string`:return A(t);case`enum`:return P(Ur(e),t);case`booleanOrString`:throw Error(`Flag ${e.key} is booleanOrString; declare its field shape explicitly with jsonSchemaField`)}}function Ur(e){let t=e.enumValues;if(!t)throw Error(`Flag ${e.key} is an enum with no enumValues`);return t}function P(e,t){return I(C(e,t),(t,n)=>Un(t,n,e))}function Wr(e){return I(O(e),Wn)}function Gr(e){return I(Lr(e),Gn)}function F(e){return I(e,(e,t)=>e[t])}function Kr(e,t){return I(e,t)}function qr(){return I(hi(),(e,t)=>e[t]===void 0?void 0:ii(e,t))}function Jr(){return I(gi(),(e,t)=>e[t]===void 0?void 0:ai(e,t))}function Yr(e){return I(Pr(e),(e,t)=>e[t]===void 0?void 0:oi(e,t))}function Xr(e,t){return I({type:`array`,description:e,items:Pr(`One contact point.`),minItems:t.min,maxItems:t.max},(e,t)=>e[t]===void 0?void 0:Zr(e,t))}function Zr(e,t){let r=e[t];if(!Array.isArray(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be an array of points.`);return r.map((e,n)=>{let r=`${t}[${n}]`;return oi({[r]:e},r)})}function Qr(){return{depth:M(`Snapshot traversal depth.`,{min:0}),scope:A(`Snapshot scope selector used before resolution.`),raw:N(`Use raw snapshot data during selector resolution.`)}}function $r(){return{count:M(`Number of press/click repetitions.`,{min:1}),intervalMs:M(`Delay between repeated press/click actions.`,{min:0}),holdMs:M(`Hold duration for each action.`,{min:0}),jitterPx:M(`Deterministic per-axis coordinate jitter in pixels (each press offsets x and y by up to this amount).`,{min:0}),doubleTap:N(`Request a double-tap action.`)}}function ei(){return{osVersion:ti(`osVersion`),imageTag:ti(`imageTag`),physical:ti(`physical`)}}function ti(e){return Kr(Br(e).schema,t=>it({[e]:t[e]}).spec[e])}function ni(e){return Nr(fi(e),pi(e))}function ri(e,t){let r=In(e),i=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{let i=t.read(r,e);if(t.required&&i===void 0)throw new n(`INVALID_ARGS`,`Expected ${e} to be set.`);return i===void 0?[]:[[e,i]]})),a=er(r,{readTargetAlias:!Object.hasOwn(t,`target`)});return m({...a,...tr(a),...i})}function ii(e,t){let n=Ln(e,t),r=Hn(n,`kind`,Mr);switch(r){case`ref`:return{kind:r,ref:Rn(n,`ref`),label:p(n,`label`)};case`selector`:return{kind:r,selector:Rn(n,`selector`)};case`point`:return{kind:r,x:Bn(n,`x`),y:Bn(n,`y`)}}}function ai(e,t){let n=Ln(e,t),r=Hn(n,`kind`,[`ref`,`selector`]);return r===`ref`?{kind:r,ref:Rn(n,`ref`),label:p(n,`label`)}:{kind:r,selector:Rn(n,`selector`)}}function oi(e,t){let n=Ln(e,t);return{x:Bn(n,`x`),y:Bn(n,`y`)}}function si(e){switch(e.kind){case`ref`:return{ref:e.ref,label:e.label};case`selector`:return{selector:e.selector};case`point`:return{x:e.x,y:e.y}}}function ci(e){switch(e.kind){case`ref`:return{ref:e.ref,label:e.label};case`selector`:return{selector:e.selector}}}function li(e){return{count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap}}function ui(e){return{depth:e.depth,scope:e.scope,raw:e.raw}}function I(e,t){return{schema:e,required:!1,read:t}}function di(e,t){return{...Ir(e),...t.min===void 0?{}:{minimum:t.min},...t.max===void 0?{}:{maximum:t.max}}}function fi(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.audience?.kind!==`retired`).map(([e,t])=>[e,t.schema]))}function pi(e){return Object.entries(e).flatMap(([e,t])=>t.required?[e]:[])}function mi(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]))}function hi(){return{oneOf:[..._i(),{type:`object`,properties:{kind:{type:`string`,const:`point`},x:{type:`number`},y:{type:`number`}},required:[`kind`,`x`,`y`],additionalProperties:!1}],description:`UI target. This is separate from deviceTarget, which selects the device form.`}}function gi(){return{oneOf:_i(),description:`UI element target by snapshot ref or selector expression.`}}function _i(){return[{type:`object`,properties:{kind:{type:`string`,const:`ref`},ref:{type:`string`,description:`Snapshot element ref such as @e12.`},label:{type:`string`,description:`Optional human label for the ref.`}},required:[`kind`,`ref`],additionalProperties:!1},{type:`object`,properties:{kind:{type:`string`,const:`selector`},selector:{type:`string`,description:`Agent-device selector expression.`}},required:[`kind`,`selector`],additionalProperties:!1}]}function L(e,t,n,r){return jr({name:e,description:t,inputSchema:ni(n),readInput:r?.readInput??(e=>ri(e,n)),inputAudience:mi(n),...r?.parseableOutput?{parseableOutput:!0}:{}})}function R(e){let t=kr(e.text,e.metadata.description),n=t.mcpDetail?{mcpDetail:t.mcpDetail}:{},r={...e.metadata,...n},i={name:r.name,description:r.description,inputSchema:r.inputSchema,...n,invoke:async(t,n)=>await e.run(t,r.readInput(n))};return{name:e.name,metadata:r,definition:i,cliSchema:{...e.cliSchema,text:t},cliReader:e.cliReader,daemonWriter:e.daemonWriter,cliOutputFormatter:e.cliOutputFormatter,text:t}}function vi(e){return R({name:e.name,text:e.text,metadata:L(e.name,e.description,{}),run:e.run,cliSchema:{},cliReader:(e,t)=>_(t),daemonWriter:h(e.name),cliOutputFormatter:e.cliOutputFormatter})}function z(e){let t={},n={},r={},i={};for(let a of e.commands)yi(t,`CLI schema`,a.name,a.cliSchema),yi(n,`CLI reader`,a.name,a.cliReader),a.daemonWriter&&yi(r,`daemon writer`,a.name,a.daemonWriter),a.cliOutputFormatter&&yi(i,`CLI output formatter`,a.name,a.cliOutputFormatter);return{name:e.name,clientSurface:e.clientSurface,metadata:e.commands.map(e=>e.metadata),definitions:e.commands.map(e=>e.definition),cliSchemas:t,cliReaders:n,daemonWriters:r,cliOutputFormatters:i}}function yi(e,t,n,r){if(Object.hasOwn(e,n))throw Error(`Duplicate command family ${t}: ${n}`);e[n]=r}function B(e){return({result:t})=>e(t)}const V=B(bi);function bi(e){return{data:e,text:cn(e)}}function xi(e){return[...typeof e.warning==`string`&&e.warning.trim()!==``?[e.warning]:[],...sn(e)].map(e=>wi(e)).filter(e=>e.length>0)}function Si(e,t){let n=e??``,r=xi(t).filter(e=>!n.includes(e)).map(e=>`Warning: ${e}`);return r.length===0?e??null:[...n===``?[]:[n],...r].join(`
2
+ `)}function Ci(e,t,n){let r=t??{};if(n===`text`)return{...e,text:Si(e.text,r)};let i=`${e.text??``}\n${e.stderr??``}`,a=xi(r).filter(e=>!i.includes(e)).map(e=>`Warning: ${e}`);if(a.length===0)return e;let o=e.stderr??``;return{...e,stderr:`${o}${o===``||o.endsWith(`
3
3
  `)?``:`
4
4
  `}${a.join(`
5
- `)}\n`}}function Si(e){return e.replaceAll(/\s*\n\s*/g,` `)}function Ci(e,t){if(typeof e==`string`&&e.length!==0&&typeof t==`number`)return`@${e.startsWith(`@`)?e.slice(1):e}~s${t}`}function wi(e){let t=[`Batch completed: ${e.executed}/${e.total} steps in ${e.totalDurationMs}ms`];for(let n of e.results)t.push(Ei(n));return{data:e,text:t.join(`
6
- `)}}const Ti={batch:V(wi)};function Ei(e){let t=sn(e.data)??e.command;return`${e.step}. OK ${t} (${e.durationMs}ms)`}function Di(e=At){let t=Oi(e);return R(`batch`,`Execute multiple commands in one daemon request.`,t,{readInput:e=>Ai(e,t)})}function Oi(e){return{steps:A(Wr({type:`array`,description:`Structured batch steps. Each step uses a command name and the same input object as that command tool.`,items:ki(e)},(t,n)=>ji(t[n],e))),onError:F([`stop`],`Batch failure policy.`),maxSteps:N(`Maximum number of steps accepted for this batch.`,{min:1,max:1e3}),out:j(`Optional output path for command artifacts.`)}}function ki(e){return{type:`object`,properties:{command:{type:`string`,enum:e,description:`Command name to run with structured input.`},input:{type:`object`,additionalProperties:!0,commandInputFor:`command`,description:`Structured command input for the nested command. Use the matching MCP tool schema for this object.`},runtime:{type:`object`,additionalProperties:!0,description:`Optional per-step runtime payload.`}},required:[`command`,`input`],additionalProperties:!1}}function Ai(e,t){let r=ti(e,t),i=r.maxSteps??100;if(!He(i))throw new n(`INVALID_ARGS`,`Invalid batch maxSteps: ${String(r.maxSteps)}`);return Le(r.steps.length,i),{...r}}function ji(e,t){if(!Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected steps to be an array.`);return e.map((e,n)=>Mi(e,n+1,t))}function Mi(e,t,n){let r=ze(e,t);return Gn(r,[`command`,`input`,`runtime`],`Batch step ${t}`,We),{command:Ni(r,t,n),input:Re(r,t),...Pi(r,t)}}function Ni(e,t,r){if(r===At)return It(e.command,t);let i=e.command;if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected command to be one of: ${r.join(`, `)}.`);return i}function Pi(e,t){let n=Ge(e.runtime,t);return n===void 0?{}:{runtime:n}}function Fi(e){return async(t,n)=>_(d.batch,[],{...t,batchSteps:await Ii(t.steps,(t,r,i)=>e(t,r,i,n)),batchOnError:t.onError,batchMaxSteps:t.maxSteps})}async function Ii(e,t){if(!Array.isArray(e)||e.length===0)throw new n(`INVALID_ARGS`,`batch requires a non-empty steps array.`);let r=[];for(let[n,i]of e.entries())r.push(await Li(i,n+1,t));return r}async function Li(e,t,n){let r=ze(e,t),i=zi(r,t),a=Re(r,t);Ri(i,a,t);let o=Ge(r.runtime,t),s=await n(i,a,t);return{command:s.command,positionals:s.positionals,...s.input?{input:s.input}:{},flags:On(s.options,s.metadataFlags),runtime:o??s.options.runtime}}function Ri(e,t,r){if(e===d.fill&&t.textStdin===!0)throw new n(`INVALID_ARGS`,`Batch step ${r}: fill textStdin is not supported because batch steps have no stdin of their own. Run that fill on its own with --text-stdin.`,{reason:`fill_text_stdin_in_batch`})}function zi(e,t){return It(e.command,t)}const Bi=Di(),Vi={usageOverride:`batch [--steps <json> | --steps-file <path>]`,usageFlags:[],listUsageOverride:`batch --steps <json> | --steps-file <path>`,allowedFlags:[`steps`,`stepsFile`,`batchOnError`,`batchMaxSteps`,`out`]},Hi=(e,t)=>({...v(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out}),Ui=[{command:`snapshot`,input:{interactiveOnly:!0}},{command:`press`,input:{target:{kind:`ref`,ref:`@e12`},settle:!0}},{command:`fill`,input:{target:{kind:`selector`,selector:`id="field-email"`},text:`qa@example.com`}}];function Wi(){return`${[`Each step is {"command":"<name>","input":{...}}, and input is that command's structured input object rather than its terminal spelling: a CLI positional becomes a named field (target, text, direction) and a CLI flag becomes a camelCase key (--settle -> "settle":true, -i -> "interactiveOnly":true). There is no positional step form; args, argv, positionals, and flags are not step fields. agent-device help <command> lists arguments in CLI spelling only. The examples below carry the structured spelling; over MCP, the command tool schema states it in full.`,`Steps run serially in one daemon request against the same session, in order. Mutating UI verbs are included (press, click, fill, longpress, scroll, back), which is where the round-trip saving is; --on-error stop halts at the first failing step.`,`The whole batch has a 60-second work budget inside a 90-second client timeout. The running step receives ordinary request cancellation at the budget. When it settles, failure returns COMMAND_FAILED with details.reason daemon_request_timeout and preserves executed, partialResults, and dispatch status. The daemon and other sessions stay available if it responds; a close step may already have ended its session. A completed batch returns success even if it settles just after the deadline. Cancellation does not prove native device work stopped. A step that ignores cancellation beyond the 30-second margin may cause a transport timeout; an unresponsive daemon retains the client liveness-based reset. Split longer sequences into separate requests.`,`Available through batch: ${[...At].sort().join(`, `)}.`,`Every other command is excluded: batch and replay never nest, and session, daemon, connection, and host tooling commands own lifecycle a batch request cannot carry. Run those on their own.`].join(` `)}\n\nExamples:\n${[` agent-device batch --steps '${JSON.stringify(Ui)}'`,` agent-device batch --steps-file ./steps.json --json`].join(`
7
- `)}`}const Gi=B({name:`batch`,clientSurface:!1,commands:[z({name:`batch`,text:{summary:`Run multiple commands`,cliDetail:Wi()},metadata:Bi,run:(e,t)=>e.batch.run(Ki(t)),cliSchema:Vi,cliReader:Hi,cliOutputFormatter:Ti.batch})]});function Ki(e){return{...h(e),steps:e.steps,onError:e.onError,maxSteps:e.maxSteps,out:e.out}}const qi=`alert`,Ji=z({name:qi,text:{summary:`Inspect, accept, or dismiss a platform alert`},metadata:R(qi,`Inspect, wait for, accept, or dismiss a platform alert. Use get before acting when the alert content matters; accept and dismiss change the active alert state. Each iOS XCTest execution activates once, then only observes. Local Apple XCTest and Limrun iOS choose recognized English labels by preference (Allow While Using App before Allow Once); on iOS simulators, local XCTest also recognizes the device's preferred languages' wording of those labels from the OS permission-prompt strings, on any alert, while Limrun iOS stays English; equal-ranked choices and unknown labels refuse, including a lone unknown button. Open, Done, and Confirm… accept; Keep Browsing, Deny, and Skip dismiss. On the Apple XCUITest runner, dismiss taps only a recognized decline label (Cancel, Don't Allow, Ask App Not to Track, and similar) or the close element of a popover whose accessibility marker reads exactly "dismiss popup"; when no button fits the action, accept and dismiss answer ALERT_BUTTON_NOT_FOUND having tapped nothing — read labels with alert get, then press the button by label. Inspect again after an unconfirmed action; never assume a timeout means nothing happened.`,{action:F(cn),timeoutMs:N()}),run:(e,t)=>e.command.alert(t),cliSchema:{usageOverride:`alert [get|accept|dismiss|wait] [timeout]`,positionalArgs:[`action?`,`timeout?`]},cliReader:(e,t)=>({...v(t),...Xi(e)}),daemonWriter:g(d.alert,e=>Yi(e)),cliOutputFormatter:H});function Yi(e){return[e.action??`get`,...b(e.timeoutMs)]}function Xi(e){if(e.length>2)throw new n(`INVALID_ARGS`,`alert accepts at most action and timeout arguments.`);return m({action:Zi(e[0]),timeoutMs:Cr(e[1],`alert timeout`)})}function Zi(e){let t=e?.toLowerCase();if(t===void 0||t===`get`||t===`accept`||t===`dismiss`||t===`wait`)return t;throw new n(`INVALID_ARGS`,`alert action must be get, accept, dismiss, or wait.`)}function U(...e){return e}const Qi=U(`keyframes`),$i=U(`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`),ea=U(`snapshotDepth`,`snapshotScope`,`snapshotRaw`),ta=U(`metroProjectRoot`,`kind`,`metroKind`,`metroPublicBaseUrl`,`metroProxyBaseUrl`,`metroBearerToken`,`metroPreparePort`,`metroListenHost`,`metroStatusHost`,`metroStartupTimeoutMs`,`metroProbeTimeoutMs`,`metroRuntimeFile`,`metroNoReuseExisting`,`metroNoInstallDeps`),na=U(`metroHost`,`metroPort`,`bundleUrl`),ra=U(`osVersion`,`imageTag`,`physical`),ia=U(`count`,`intervalMs`,`holdMs`,`jitterPx`,`doubleTap`),aa=U(`settle`,`settleQuietMs`,`timeoutMs`),oa=U(`replayUpdate`,`replayEnv`),sa=U(`remoteConfig`,`stateDir`,`daemonBaseUrl`,`daemonAuthToken`,`daemonTransport`,`daemonServerMode`,`tenant`,`sessionIsolation`,`runId`,`leaseId`,`leaseBackend`,`sessionLock`,`platform`,`target`,`device`,`providerApp`,`providerOsVersion`,`providerDeviceType`,`providerProject`,`providerBuild`,`providerSessionName`,`providerDeviceOrientation`,`providerGeoLocation`,`providerTimezone`,`providerAppiumVersion`,`providerLanguage`,`providerLocale`,`providerNetworkProfile`,`providerCustomNetwork`,`providerNoResignApp`,`awsProjectArn`,`awsDeviceArn`,`awsAppArn`,`awsRegion`,`awsInteractionMode`,`udid`,`serial`,`iosSimulatorDeviceSet`,`iosXctestrunFile`,`iosXctestDerivedDataPath`,`iosXctestEnvDir`,`androidDeviceAllowlist`,`session`,`noRecord`),ca=new Set([`platform`,`device`,`udid`,`serial`,`session`]),la=new Set([`json`,`config`,`help`,`version`,`verbose`,`cost`,`responseLevel`]),ua=`diff`,da={diff:C({mode:T(`snapshot`),baselineInitialized:O(),summary:C({additions:D(),removals:D(),unchanged:D()},[`additions`,`removals`,`unchanged`]),lines:{type:`array`,items:C({kind:w([`added`,`removed`,`unchanged`]),text:E(),ref:E()},[`kind`,`text`])},warnings:Fr()},[`mode`,`baselineInitialized`,`summary`,`lines`])},fa=z({name:ua,text:{summary:`Diff snapshot or screenshot`,cliDetail:`Screenshot --threshold is a per-pixel RGB tolerance: 0 requires exact colors and 1 ignores color differences; the current image scales proportionally to the baseline width and aligns top-left. Scaled height rounds to the nearest pixel (minimum 1). Extra or missing bottom rows always count as differences, even at threshold 1. The originals remain unchanged. When dimensions differ, normalization metadata reports original, scaled and compared sizes; region coordinates use comparison pixels. Both screenshot inputs are decoded from their bytes, so a baseline or current image may be PNG or JPEG, and the diff image is always PNG. JPEG is lossy, so keep --threshold above 0 whenever either input is JPEG. Live iOS simulator screenshot diffs normalize status-bar chrome by default; use screenshot --normalize-status-bar when capturing reusable baselines.`},metadata:R(ua,`Compare accessibility snapshots or screenshots to identify UI changes. Use snapshot comparisons for semantic tree changes and screenshot comparisons for pixel differences.`,{kind:A(I({type:`string`,const:`snapshot`})),out:j(),interactiveOnly:P(),depth:N(),scope:j(),raw:P()}),run:(e,t)=>e.capture.diff(t),cliSchema:{usageOverride:`diff snapshot | diff screenshot --baseline <path> [current.png] [--out <diff.png>] [--threshold <0-1>] [--overlay-refs]`,usageFlags:[],positionalArgs:[`kind`,`current?`],allowedFlags:[...$i,`baseline`,`threshold`,`out`,`overlayRefs`]},cliReader:(e,t)=>{if(e[0]!==`snapshot`)throw new n(`INVALID_ARGS`,`Only diff snapshot is available through this parser.`);return{...v(t),kind:`snapshot`,out:t.out,interactiveOnly:t.snapshotInteractiveOnly,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw}},daemonWriter:g(d.diff,e=>[S(e.kind,`diff requires kind`)])}),pa=`screenshot`,ma=z({name:pa,text:{summary:`Capture a screenshot`,cliDetail:`Web defaults to the viewport; use --fullscreen, --full, or -f for the entire page. iOS simulators default to 1x logical-point output; use --pixel-density to request a different screenshot density. macOS app sessions default to the app window; use --fullscreen for full desktop, --scale to downscale, --crop-on <selector> to crop the capture to the frame the selector resolves on the same screen (currently iOS simulators, Android emulators, and CoreDevice physical iPhones), --overlay-refs to annotate current refs, --normalize-status-bar for deterministic iOS simulator or Android chrome. Physical iPhone crop verification covers portrait CoreDevice/devicectl captures only. XCTest, runner fallback, and physical iPad crops are refused; landscape iPhone crop is unverified. Android captures immediately by default; --normalize-status-bar also waits for transient UI to fade, and --no-stabilize keeps capture immediate. With the native macOS backend, the front window is the app's frontmost visible, nonempty normal-level (layer-0) window on the current Space: floating palettes and app-modal alerts at window level 8 are skipped, and a sheet is captured as its own window. On macOS, any --surface other than app (desktop, menubar, frontmost-app) always captures the main display and refuses an explicit --fullscreen. On single-display iOS simulators and Android devices, the result reports displayRotation, the rotation the display rendered the capture in, when the device returns a reading in time; otherwise the field is absent.`},metadata:R(pa,`Capture a screenshot of the active app or web session. Choose the capture scope, density, size, or annotations through the corresponding input fields when needed.`,{path:j(`Output path.`),cropOn:j(`Selector expression; the capture is cropped to the frame the selector resolves on the same screen.`),overlayRefs:P(),pixelDensity:N(`Output screenshot pixel density in pixels per logical point.`,{min:1}),fullscreen:P(),scale:M(`Screenshot scale factor.`,ne),maxSize:Ir(Ie.migration.screenshot),stabilize:P(),normalizeStatusBar:P(),surface:F(Wt)}),run:(e,t)=>e.capture.screenshot(t),cliSchema:{positionalArgs:[`path?`],allowedFlags:ve},cliReader:(e,t)=>({...v(t),path:e[0]??t.out,...ee(t)}),daemonWriter:e=>(xe(`screenshot`,e),ce(e),_(d.screenshot,y(e.path),{...e,...Se(e)}))}),ha=`settings`,ga=R(ha,`Read or change supported operating-system settings, animation scales, appearance, or app permissions on the selected target. Platform support varies by setting and action.`,{setting:A(F(mn)),state:j(),app:j("App the change targets, by bundle id, package name, or app name: the app `clear-app-state` clears, or the app a `permission` change (or an iOS-simulator `location on|off` privacy change) lands on. A name resolves to the installed app as `open` resolves it: an iOS simulator matches display names and accepts only an installed bundle id, Android accepts only an installed package and refuses a name that resolves to an intent with `setting_app_not_package`, and a Limrun iOS session resolves only the `settings` alias. One that resolves to nothing is refused with `app_not_installed` before anything changes. The app need not be running. Without it the session app is used; a device-wide change (`location set` on any target, the Android `location on|off` toggle, `mobile-data`, macOS permissions) refuses one with `setting_app_not_consumed`. The CLI reads it only from this invocation, never from `AGENT_DEVICE_TARGET_APP` or config `targetApp`."),latitude:M(),longitude:M(),permission:j(),mode:F([...fn])}),_a={usageOverride:dn,listUsageOverride:`settings [area] [options]`,positionalArgs:[`setting`,`state?`,`target?`,`mode?`],allowedFlags:[`targetApp`],explicitOnlyFlags:[`targetApp`]},va=(e,t)=>{let n=ar(t),r=Lt(e);if(r.kind===`read`)return{...n,setting:r.setting};let i=un(e),a=pn(i.setting)?.app===`positional`?Sa(i.setting,i.app,t):t.targetApp;return{...n,setting:i.setting,state:i.state,...i.permission===void 0?{}:{permission:i.permission},...i.mode===void 0?{}:{mode:i.mode},...i.latitude===void 0?{}:{latitude:hn(i.latitude,`latitude`),longitude:hn(i.longitude,`longitude`)},...a===void 0?{}:{app:a}}},ya=e=>{let t=e,n=m({app:ba(t)});return _(d.settings,Ca(t),e,Object.keys(n).length===0?void 0:n)};function ba(e){return pn(e.setting)?.app===`input`&&`app`in e?e.app:void 0}const xa=z({name:ha,text:{summary:`Change OS settings and app permissions`,cliDetail:[`A bare readable setting reads the value the target holds. A target that does not serve a setting refuses it with UNSUPPORTED_OPERATION before anything changes.`,``,`Settings:`,...ln().map(e=>` ${e}`)].join(`
8
- `)},metadata:ga,run:(e,t)=>e.settings.update(t),cliSchema:_a,cliReader:va,daemonWriter:ya,cliOutputFormatter:H});function Sa(e,t,r){let i=r.targetApp;if(t!==void 0&&i!==void 0&&t!==i)throw new n(`INVALID_ARGS`,`settings ${e} names two apps: ${t} and ${i}. Name one.`);return t??i}function Ca(e){return pn(e.setting)?.app===`positional`?[e.setting,...y(`app`in e?e.app:void 0)]:e.state===void 0?[e.setting]:`latitude`in e?[e.setting,e.state,String(e.latitude),String(e.longitude)]:`permission`in e?[e.setting,e.state,e.permission,...y(e.mode)]:[e.setting,e.state]}function wa(e){if(!Array.isArray(e)||e.length===0)return e;let t=jt(e);return e.map(e=>{let n=Ta(e,t,e=>e.label),r=Ta(e,t,e=>e.identifier),i=typeof e.label==`string`&&e.label.length>=24&&e.label===n,a=typeof e.identifier==`string`&&e.identifier.length>=24&&e.identifier===r;if(!i&&!a)return e;let o={...e};return i&&(delete o.label,o.inheritsLabel=!0),a&&(delete o.identifier,o.inheritsIdentifier=!0),o})}function Ta(e,t,n){let r=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0;for(;r;){let e=n(r);if(typeof e==`string`&&e.length>0)return e;r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}}function Ea(e){return e.width>0&&e.height>0}function Da(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 Oa(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 ka(e){return typeof e.parentIndex!=`number`}function Aa(e){let t=(e.type??``).toLowerCase(),n=(e.identifier??``).trim().toLowerCase();return t.includes(`edittext`)||t.includes(`textfield`)||n===`composer`}function ja(e){let t=(e.type??``).toLowerCase();return t.includes(`scroll`)||t.includes(`list`)||t.includes(`recyclerview`)}function W(e){let t=yt(e);if(!t||t!==e.identifier?.trim()||!Na(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 Ma(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||/^(true|false|\d+)$/.test(t)?null:t}function Na(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function Pa(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 Fa(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 Ia(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 La=[`button`,`switch`,`checkbox`,`radio`],Ra=[`button`,`image`,`textview`,`view`];function za(e,t,n){for(let r of e){if(t.has(r.index)||!Ha(r))continue;let i=Ua(Fa(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)Ia(e,n,t)}}}function Ba(e,t,n){let r=new Map;for(let i of e){if(t.has(i.index)||!Za(i))continue;let a=Ma(W(i));if(!a)continue;let o=r.get(a);if(o&&Ja(o,i,t)){let s=Ya(e,o,i,t,n);r.set(a,s);continue}r.set(a,i)}}function Va(e,t){for(let n of e){if(t.has(n.index)||!Ka(n))continue;let r=Ma(W(n));if(!r)continue;let i=Fa(e,n.index).filter(e=>!t.has(e.index)&&qa(n,e,r));for(let n of i.filter(Ga))Ia(e,n.index,t);let a=i.filter(e=>!Ga(e)),o=new Set(a.map(e=>Ma(W(e))).filter(e=>!!e));if(!(a.length<2||o.size<2))for(let n of a)Ia(e,n.index,t)}}function Ha(e){return e.hittable===!0&&!Aa(e)&&!!(e.rect&&Ea(e.rect))&&W(e).trim().length===0}function Ua(e,t,n){let r=[],i=[],a=new Set;for(let o of e){if(n.has(o.index)||!Wa(o,e)||!Da(o.rect,t.rect))continue;let s=W(o).trim().replaceAll(/\s+/g,` `),c=Ma(s);i.push(o.index),!(!s||!c||a.has(c))&&(a.add(c),r.push(s))}return{label:r.join(`, `),removableIndexes:i}}function Wa(e,t){if(Ga(e))return!0;let n=(e.type??``).toLowerCase();return e.hittable!==!0&&!Aa(e)&&n.includes(`view`)&&W(e).trim().length>0&&!t.some(t=>t.parentIndex===e.index)}function Ga(e){if(e.hittable===!0||Aa(e))return!1;let t=(e.type??``).toLowerCase();return t.includes(`text`)||t.includes(`image`)||t.includes(`icon`)}function Ka(e){return e.hittable===!0&&!Aa(e)&&!!(e.rect&&Ea(e.rect))&&!!Ma(W(e))}function qa(e,t,n){if(!Za(t)||!Da(t.rect,e.rect))return!1;let r=Ma(W(t));return!!(r&&n!==r&&n.includes(r))}function Ja(e,t,n){return!n.has(e.index)&&Oa(e.rect,t.rect)&&(no(e,t)||to(e,t))}function Ya(e,t,n,r,i){let a=Qa(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:Xa(c.presentationHints,l,s)}),Ia(e,o.index,r),i.get(a.index)??a}function Xa(e,t,n){return[...new Set([...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...n?[n]:[]])]}function Za(e){if(!e.rect||!Ea(e.rect)||ka(e)||Aa(e))return!1;let t=(e.type??``).toLowerCase();return t===`text`||eo(t,Ra)}function Qa(e,t){let n=$a(e);return $a(t)>n?t:e}function $a(e){let t=(e.type??``).toLowerCase(),n=0;return eo(t,La)?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 eo(e,t){return t.some(t=>e.includes(t))}function to(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:Qa(n,r).index===n.index}function no(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 ro(e,t,n){if(n.raw||!io(e))return{nodes:t,filteredCount:0};let r=ao(t);return{nodes:r,filteredCount:t.length-r.length}}function io(e){let t=e.androidSnapshot;return!t||typeof t!=`object`?!1:t.backend===`android-helper`}function ao(e){if(e.length===0)return e;let t=new Set,n=new Map,r=new Map(e.map(e=>[e.index,e]));return oo(e,t),so(e,r,t,n),za(e,t,n),Va(e,t),Ba(e,t,n),e.filter(e=>!t.has(e.index)).map(e=>n.get(e.index)??e)}function oo(e,t){for(let n of e)!n.rect||Ea(n.rect)||ka(n)||Ia(e,n.index,t)}function so(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||ka(i))continue;let a=Pa(i,t,ja);a&&lo(r,a,co(i,e)),Ia(e,i.index,n)}}function co(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&Ea(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 lo(e,t,n){if(!n)return;let r=e.get(t.index)??t;e.set(t.index,{...r,hiddenContentAbove:r.hiddenContentAbove===!0||n===`above`||void 0,hiddenContentBelow:r.hiddenContentBelow===!0||n===`below`||void 0})}function uo(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??``).toLowerCase(),r=fo(yt(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||!ho(e)||(n+=e.length);return n>=8}function fo(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||po(t)?null:t}function po(e){return e.split(` `).some(mo)}function mo(e){let t=e.indexOf(`@`,1);return t!==-1&&e.lastIndexOf(`.`,e.length-2)>t+1}function ho(e){for(let t=0;t<e.length;t+=1)for(let n=t+1;n<e.length;n+=1)if(go(e[t]?.rect,e[n]?.rect))return!0;return!1}function go(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)}function _o(t,n={}){let r=t.nodes,i=Array.isArray(r)?r:[],o=a(t.backend)?t.backend:void 0,s=e(o),c=ro(t,i,n),l=xo(t),ee=Ao(t,i,n,c),te=ee.length>0?`${ee.join(`
9
- `)}\n`:``,ne=n.raw?null:vo(t);if(ne)return`${l}${te}${yo(ne)}\n`;let re=n.raw||!s?null:_n(c.nodes),ie=!!t.truncated,ae=re?.nodes??i,oe=n.raw||!s?null:Do(t,re,ae.length,i.length,c.filteredCount),se=So(i.length,oe,ie);return i.length===0?`${l}${se}\n${te}`:n.raw?`${l}${se}\n${te}${Co(i)}\n`:n.flatten?`${l}${se}\n${te}${wo(ae)}${Eo(re)}\n`:`${l}${se}\n${te}${To(ae)}${Eo(re)}\n`}function vo(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||void 0,scope:typeof n.scope==`string`?n.scope:void 0}}function yo(e){let t=bo(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
+ `)}\n`}}function wi(e){return e.replaceAll(/\s*\n\s*/g,` `)}function Ti(e,t){if(typeof e==`string`&&e.length!==0&&typeof t==`number`)return`@${e.startsWith(`@`)?e.slice(1):e}~s${t}`}function Ei(e){let t=[`Batch completed: ${e.executed}/${e.total} steps in ${e.totalDurationMs}ms`];for(let n of e.results)t.push(Oi(n));return{data:e,text:t.join(`
6
+ `)}}const Di={batch:B(Ei)};function Oi(e){let t=cn(e.data)??e.command;return`${e.step}. OK ${t} (${e.durationMs}ms)`}function ki(e=jt){let t=Ai(e);return L(`batch`,`Execute multiple commands in one daemon request.`,t,{readInput:e=>Mi(e,t)})}function Ai(e){return{steps:k(Kr({type:`array`,description:`Structured batch steps. Each step uses a command name and the same input object as that command tool.`,items:ji(e)},(t,n)=>Ni(t[n],e))),onError:P([`stop`],`Batch failure policy.`),maxSteps:M(`Maximum number of steps accepted for this batch.`,{min:1,max:1e3}),out:A(`Optional output path for command artifacts.`)}}function ji(e){return{type:`object`,properties:{command:{type:`string`,enum:e,description:`Command name to run with structured input.`},input:{type:`object`,additionalProperties:!0,commandInputFor:`command`,description:`Structured command input for the nested command. Use the matching MCP tool schema for this object.`},runtime:{type:`object`,additionalProperties:!0,description:`Optional per-step runtime payload.`}},required:[`command`,`input`],additionalProperties:!1}}function Mi(e,t){let r=ri(e,t),i=r.maxSteps??100;if(!Ge(i))throw new n(`INVALID_ARGS`,`Invalid batch maxSteps: ${String(r.maxSteps)}`);return Ue(r.steps.length,i),{...r}}function Ni(e,t){if(!Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected steps to be an array.`);return e.map((e,n)=>Pi(e,n+1,t))}function Pi(e,t,n){let r=We(e,t);return Kn(r,[`command`,`input`,`runtime`],`Batch step ${t}`,Re),{command:Fi(r,t,n),input:Be(r,t),...Ii(r,t)}}function Fi(e,t,r){if(r===jt)return Rt(e.command,t);let i=e.command;if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected command to be one of: ${r.join(`, `)}.`);return i}function Ii(e,t){let n=ze(e.runtime,t);return n===void 0?{}:{runtime:n}}function Li(e){return async(t,n)=>g(d.batch,[],{...t,batchSteps:await Ri(t.steps,(t,r,i)=>e(t,r,i,n)),batchOnError:t.onError,batchMaxSteps:t.maxSteps})}async function Ri(e,t){if(!Array.isArray(e)||e.length===0)throw new n(`INVALID_ARGS`,`batch requires a non-empty steps array.`);let r=[];for(let[n,i]of e.entries())r.push(await zi(i,n+1,t));return r}async function zi(e,t,n){let r=We(e,t),i=Vi(r,t),a=Be(r,t);Bi(i,a,t);let o=ze(r.runtime,t),s=await n(i,a,t);return{command:s.command,positionals:s.positionals,...s.input?{input:s.input}:{},flags:kn(s.options,s.metadataFlags),runtime:o??s.options.runtime}}function Bi(e,t,r){if(e===d.fill&&t.textStdin===!0)throw new n(`INVALID_ARGS`,`Batch step ${r}: fill textStdin is not supported because batch steps have no stdin of their own. Run that fill on its own with --text-stdin.`,{reason:`fill_text_stdin_in_batch`})}function Vi(e,t){return Rt(e.command,t)}const Hi=ki(),Ui={usageOverride:`batch [--steps <json> | --steps-file <path>]`,usageFlags:[],listUsageOverride:`batch --steps <json> | --steps-file <path>`,allowedFlags:[`steps`,`stepsFile`,`batchOnError`,`batchMaxSteps`,`out`]},Wi=(e,t)=>({..._(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out}),Gi=[{command:`snapshot`,input:{interactiveOnly:!0}},{command:`press`,input:{target:{kind:`ref`,ref:`@e12`},settle:!0}},{command:`fill`,input:{target:{kind:`selector`,selector:`id="field-email"`},text:`qa@example.com`}}];function Ki(){return`${[`Each step is {"command":"<name>","input":{...}}, and input is that command's structured input object rather than its terminal spelling: a CLI positional becomes a named field (target, text, direction) and a CLI flag becomes a camelCase key (--settle -> "settle":true, -i -> "interactiveOnly":true). There is no positional step form; args, argv, positionals, and flags are not step fields. agent-device help <command> lists arguments in CLI spelling only. The examples below carry the structured spelling; over MCP, the command tool schema states it in full.`,`Steps run serially in one daemon request against the same session, in order. Mutating UI verbs are included (press, click, fill, longpress, scroll, back), which is where the round-trip saving is; --on-error stop halts at the first failing step.`,`The whole batch has a 60-second work budget inside a 90-second client timeout. The running step receives ordinary request cancellation at the budget. When it settles, failure returns COMMAND_FAILED with details.reason daemon_request_timeout and preserves executed, partialResults, and dispatch status. The daemon and other sessions stay available if it responds; a close step may already have ended its session. A completed batch returns success even if it settles just after the deadline. Cancellation does not prove native device work stopped. A step that ignores cancellation beyond the 30-second margin may cause a transport timeout; an unresponsive daemon retains the client liveness-based reset. Split longer sequences into separate requests.`,`Available through batch: ${[...jt].sort().join(`, `)}.`,`Every other command is excluded: batch and replay never nest, and session, daemon, connection, and host tooling commands own lifecycle a batch request cannot carry. Run those on their own.`].join(` `)}\n\nExamples:\n${[` agent-device batch --steps '${JSON.stringify(Gi)}'`,` agent-device batch --steps-file ./steps.json --json`].join(`
7
+ `)}`}const qi=z({name:`batch`,clientSurface:!1,commands:[R({name:`batch`,text:{summary:`Run multiple commands`,cliDetail:Ki()},metadata:Hi,run:(e,t)=>e.batch.run(Ji(t)),cliSchema:Ui,cliReader:Wi,cliOutputFormatter:Di.batch})]});function Ji(e){return{...tr(e),steps:e.steps,onError:e.onError,maxSteps:e.maxSteps,out:e.out}}const Yi=`alert`,Xi=R({name:Yi,text:{summary:`Inspect, accept, or dismiss a platform alert`},metadata:L(Yi,`Inspect, wait for, accept, or dismiss a platform alert. Use get before acting when the alert content matters; accept and dismiss change the active alert state. Each iOS XCTest execution activates once, then only observes. Local Apple XCTest and Limrun iOS choose recognized English labels by preference (Allow While Using App before Allow Once); on iOS simulators, local XCTest also recognizes the device's preferred languages' wording of those labels from the OS permission-prompt strings, on any alert, while Limrun iOS stays English; equal-ranked choices and unknown labels refuse, including a lone unknown button. Open, Done, and Confirm… accept; Keep Browsing, Deny, and Skip dismiss. On the Apple XCUITest runner, dismiss taps only a recognized decline label (Cancel, Don't Allow, Ask App Not to Track, and similar) or the close element of a popover whose accessibility marker reads exactly "dismiss popup"; when no button fits the action, accept and dismiss answer ALERT_BUTTON_NOT_FOUND having tapped nothing — read labels with alert get, then press the button by label. Inspect again after an unconfirmed action; never assume a timeout means nothing happened.`,{action:P(ln),timeoutMs:M()}),run:(e,t)=>e.command.alert(t),cliSchema:{usageOverride:`alert [get|accept|dismiss|wait] [timeout]`,positionalArgs:[`action?`,`timeout?`]},cliReader:(e,t)=>({..._(t),...Qi(e)}),daemonWriter:h(d.alert,e=>Zi(e)),cliOutputFormatter:V});function Zi(e){return[e.action??`get`,...y(e.timeoutMs)]}function Qi(e){if(e.length>2)throw new n(`INVALID_ARGS`,`alert accepts at most action and timeout arguments.`);return m({action:$i(e[0]),timeoutMs:Tr(e[1],`alert timeout`)})}function $i(e){let t=e?.toLowerCase();if(t===void 0||t===`get`||t===`accept`||t===`dismiss`||t===`wait`)return t;throw new n(`INVALID_ARGS`,`alert action must be get, accept, dismiss, or wait.`)}function H(...e){return e}const ea=H(`keyframes`),ta=H(`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`),U=H(`snapshotDepth`,`snapshotScope`,`snapshotRaw`),na=H(`metroProjectRoot`,`kind`,`metroKind`,`metroPublicBaseUrl`,`metroProxyBaseUrl`,`metroBearerToken`,`metroPreparePort`,`metroListenHost`,`metroStatusHost`,`metroStartupTimeoutMs`,`metroProbeTimeoutMs`,`metroRuntimeFile`,`metroNoReuseExisting`,`metroNoInstallDeps`),ra=H(`metroHost`,`metroPort`,`bundleUrl`),ia=H(`osVersion`,`imageTag`,`physical`),aa=H(`count`,`intervalMs`,`holdMs`,`jitterPx`,`doubleTap`),oa=H(`settle`,`settleQuietMs`,`timeoutMs`),sa=H(`replayUpdate`,`replayEnv`),ca=H(`remoteConfig`,`stateDir`,`daemonBaseUrl`,`daemonAuthToken`,`daemonTransport`,`daemonServerMode`,`tenant`,`sessionIsolation`,`runId`,`leaseId`,`leaseBackend`,`sessionLock`,`platform`,`target`,`device`,`providerApp`,`providerOsVersion`,`providerDeviceType`,`providerProject`,`providerBuild`,`providerSessionName`,`providerDeviceOrientation`,`providerGeoLocation`,`providerTimezone`,`providerAppiumVersion`,`providerLanguage`,`providerLocale`,`providerNetworkProfile`,`providerCustomNetwork`,`providerNoResignApp`,`providerNetworkLogs`,`providerNetworkHosts`,`awsProjectArn`,`awsDeviceArn`,`awsAppArn`,`awsRegion`,`awsInteractionMode`,`udid`,`serial`,`iosSimulatorDeviceSet`,`iosXctestrunFile`,`iosXctestDerivedDataPath`,`iosXctestEnvDir`,`androidDeviceAllowlist`,`session`,`noRecord`),la=new Set([`platform`,`device`,`udid`,`serial`,`session`]),ua=new Set([`json`,`config`,`help`,`version`,`verbose`,`cost`,`responseLevel`]),da=`diff`,fa={diff:S({mode:w(`snapshot`),baselineInitialized:D(),summary:S({additions:E(),removals:E(),unchanged:E()},[`additions`,`removals`,`unchanged`]),lines:{type:`array`,items:S({kind:C([`added`,`removed`,`unchanged`]),text:T(),ref:T()},[`kind`,`text`])},warnings:Lr()},[`mode`,`baselineInitialized`,`summary`,`lines`])},pa=R({name:da,text:{summary:`Diff snapshot or screenshot`,cliDetail:`Screenshot --threshold is a per-pixel RGB tolerance: 0 requires exact colors and 1 ignores color differences; the current image scales proportionally to the baseline width and aligns top-left. Scaled height rounds to the nearest pixel (minimum 1). Extra or missing bottom rows always count as differences, even at threshold 1. The originals remain unchanged. When dimensions differ, normalization metadata reports original, scaled and compared sizes; region coordinates use comparison pixels. Both screenshot inputs are decoded from their bytes, so a baseline or current image may be PNG or JPEG, and the diff image is always PNG. JPEG is lossy, so keep --threshold above 0 whenever either input is JPEG. Live iOS simulator screenshot diffs normalize status-bar chrome by default; use screenshot --normalize-status-bar when capturing reusable baselines.`},metadata:L(da,`Compare accessibility snapshots or screenshots to identify UI changes. Use snapshot comparisons for semantic tree changes and screenshot comparisons for pixel differences.`,{kind:k(F({type:`string`,const:`snapshot`})),out:A(),interactiveOnly:N(),depth:M(),scope:A(),raw:N()}),run:(e,t)=>e.capture.diff(t),cliSchema:{usageOverride:`diff snapshot | diff screenshot --baseline <path> [current.png] [--out <diff.png>] [--threshold <0-1>] [--overlay-refs]`,usageFlags:[],positionalArgs:[`kind`,`current?`],allowedFlags:[...ta,`baseline`,`threshold`,`out`,`overlayRefs`]},cliReader:(e,t)=>{if(e[0]!==`snapshot`)throw new n(`INVALID_ARGS`,`Only diff snapshot is available through this parser.`);return{..._(t),kind:`snapshot`,out:t.out,interactiveOnly:t.snapshotInteractiveOnly,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw}},daemonWriter:h(d.diff,e=>[x(e.kind,`diff requires kind`)])}),ma=`screenshot`,ha=R({name:ma,text:{summary:`Capture a screenshot`,cliDetail:`Web defaults to the viewport; use --fullscreen, --full, or -f for the entire page. iOS simulators default to 1x logical-point output; use --pixel-density to request a different screenshot density. macOS app sessions default to the app window; use --fullscreen for full desktop, --scale to downscale, --crop-on <selector> to crop the capture to the frame the selector resolves on the same screen (currently iOS simulators, Android emulators, and CoreDevice physical iPhones), --overlay-refs to annotate current refs, --normalize-status-bar for deterministic iOS simulator or Android chrome. Physical iPhone crop verification covers portrait CoreDevice/devicectl captures only. XCTest, runner fallback, and physical iPad crops are refused; landscape iPhone crop is unverified. Android captures immediately by default; --normalize-status-bar also waits for transient UI to fade, and --no-stabilize keeps capture immediate. With the native macOS backend, the front window is the app's frontmost visible, nonempty normal-level (layer-0) window on the current Space: floating palettes and app-modal alerts at window level 8 are skipped, and a sheet is captured as its own window. On macOS, any --surface other than app (desktop, menubar, frontmost-app) always captures the main display and refuses an explicit --fullscreen. On single-display iOS simulators and Android devices, the result reports displayRotation, the rotation the display rendered the capture in, when the device returns a reading in time; otherwise the field is absent.`},metadata:L(ma,`Capture a screenshot of the active app or web session. Choose the capture scope, density, size, or annotations through the corresponding input fields when needed.`,{path:A(`Output path.`),cropOn:A(`Selector expression; the capture is cropped to the frame the selector resolves on the same screen.`),overlayRefs:N(),pixelDensity:M(`Output screenshot pixel density in pixels per logical point.`,{min:1}),fullscreen:N(),scale:j(`Screenshot scale factor.`,ne),maxSize:Rr(Ie.migration.screenshot),stabilize:N(),normalizeStatusBar:N(),surface:P(Gt)}),run:(e,t)=>e.capture.screenshot(t),cliSchema:{positionalArgs:[`path?`],allowedFlags:ve},cliReader:(e,t)=>({..._(t),path:e[0]??t.out,...ee(t)}),daemonWriter:e=>(xe(`screenshot`,e),ce(e),g(d.screenshot,v(e.path),{...e,...Se(e)}))}),ga=`settings`,_a=L(ga,`Read or change supported operating-system settings, animation scales, appearance, or app permissions on the selected target. Platform support varies by setting and action.`,{setting:k(P(hn)),state:A(),app:A("App the change targets, by bundle id, package name, or app name: the app `clear-app-state` clears, or the app a `permission` change (or an iOS-simulator `location on|off` privacy change) lands on. A name resolves to the installed app as `open` resolves it: an iOS simulator matches display names and accepts only an installed bundle id, Android accepts only an installed package and refuses a name that resolves to an intent with `setting_app_not_package`, and a Limrun iOS session resolves only the `settings` alias. One that resolves to nothing is refused with `app_not_installed` before anything changes. The app need not be running. Without it the session app is used; a device-wide change (`location set` on any target, the Android `location on|off` toggle, `mobile-data`, macOS permissions) refuses one with `setting_app_not_consumed`. The CLI reads it only from this invocation, never from `AGENT_DEVICE_TARGET_APP` or config `targetApp`."),latitude:j(),longitude:j(),permission:A(),mode:P([...pn])}),va={usageOverride:fn,listUsageOverride:`settings [area] [options]`,positionalArgs:[`setting`,`state?`,`target?`,`mode?`],allowedFlags:[`targetApp`],explicitOnlyFlags:[`targetApp`]},ya=(e,t)=>{let n=sr(t),r=Lt(e);if(r.kind===`read`)return{...n,setting:r.setting};let i=dn(e),a=mn(i.setting)?.app===`positional`?Ca(i.setting,i.app,t):t.targetApp;return{...n,setting:i.setting,state:i.state,...i.permission===void 0?{}:{permission:i.permission},...i.mode===void 0?{}:{mode:i.mode},...i.latitude===void 0?{}:{latitude:gn(i.latitude,`latitude`),longitude:gn(i.longitude,`longitude`)},...a===void 0?{}:{app:a}}},ba=e=>{let t=e,n=m({app:xa(t)});return g(d.settings,wa(t),e,Object.keys(n).length===0?void 0:n)};function xa(e){return mn(e.setting)?.app===`input`&&`app`in e?e.app:void 0}const Sa=R({name:ga,text:{summary:`Change OS settings and app permissions`,cliDetail:[`A bare readable setting reads the value the target holds. A target that does not serve a setting refuses it with UNSUPPORTED_OPERATION before anything changes.`,``,`Settings:`,...un().map(e=>` ${e}`)].join(`
8
+ `)},metadata:_a,run:(e,t)=>e.settings.update(t),cliSchema:va,cliReader:ya,daemonWriter:ba,cliOutputFormatter:V});function Ca(e,t,r){let i=r.targetApp;if(t!==void 0&&i!==void 0&&t!==i)throw new n(`INVALID_ARGS`,`settings ${e} names two apps: ${t} and ${i}. Name one.`);return t??i}function wa(e){return mn(e.setting)?.app===`positional`?[e.setting,...v(`app`in e?e.app:void 0)]:e.state===void 0?[e.setting]:`latitude`in e?[e.setting,e.state,String(e.latitude),String(e.longitude)]:`permission`in e?[e.setting,e.state,e.permission,...v(e.mode)]:[e.setting,e.state]}function Ta(e){if(!Array.isArray(e)||e.length===0)return e;let t=Mt(e);return e.map(e=>{let n=Ea(e,t,e=>e.label),r=Ea(e,t,e=>e.identifier),i=typeof e.label==`string`&&e.label.length>=24&&e.label===n,a=typeof e.identifier==`string`&&e.identifier.length>=24&&e.identifier===r;if(!i&&!a)return e;let o={...e};return i&&(delete o.label,o.inheritsLabel=!0),a&&(delete o.identifier,o.inheritsIdentifier=!0),o})}function Ea(e,t,n){let r=typeof e.parentIndex==`number`?t.get(e.parentIndex):void 0;for(;r;){let e=n(r);if(typeof e==`string`&&e.length>0)return e;r=typeof r.parentIndex==`number`?t.get(r.parentIndex):void 0}}function Da(e){return e.width>0&&e.height>0}function Oa(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 ka(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 Aa(e){return typeof e.parentIndex!=`number`}function ja(e){let t=(e.type??``).toLowerCase(),n=(e.identifier??``).trim().toLowerCase();return t.includes(`edittext`)||t.includes(`textfield`)||n===`composer`}function Ma(e){let t=(e.type??``).toLowerCase();return t.includes(`scroll`)||t.includes(`list`)||t.includes(`recyclerview`)}function W(e){let t=bt(e);if(!t||t!==e.identifier?.trim()||!Pa(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 Na(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||/^(true|false|\d+)$/.test(t)?null:t}function Pa(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function Fa(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 Ia(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 La(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 Ra=[`button`,`switch`,`checkbox`,`radio`],za=[`button`,`image`,`textview`,`view`];function Ba(e,t,n){for(let r of e){if(t.has(r.index)||!Ua(r))continue;let i=Wa(Ia(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)La(e,n,t)}}}function Va(e,t,n){let r=new Map;for(let i of e){if(t.has(i.index)||!Qa(i))continue;let a=Na(W(i));if(!a)continue;let o=r.get(a);if(o&&Ya(o,i,t)){let s=Xa(e,o,i,t,n);r.set(a,s);continue}r.set(a,i)}}function Ha(e,t){for(let n of e){if(t.has(n.index)||!qa(n))continue;let r=Na(W(n));if(!r)continue;let i=Ia(e,n.index).filter(e=>!t.has(e.index)&&Ja(n,e,r));for(let n of i.filter(Ka))La(e,n.index,t);let a=i.filter(e=>!Ka(e)),o=new Set(a.map(e=>Na(W(e))).filter(e=>!!e));if(!(a.length<2||o.size<2))for(let n of a)La(e,n.index,t)}}function Ua(e){return e.hittable===!0&&!ja(e)&&!!(e.rect&&Da(e.rect))&&W(e).trim().length===0}function Wa(e,t,n){let r=[],i=[],a=new Set;for(let o of e){if(n.has(o.index)||!Ga(o,e)||!Oa(o.rect,t.rect))continue;let s=W(o).trim().replaceAll(/\s+/g,` `),c=Na(s);i.push(o.index),!(!s||!c||a.has(c))&&(a.add(c),r.push(s))}return{label:r.join(`, `),removableIndexes:i}}function Ga(e,t){if(Ka(e))return!0;let n=(e.type??``).toLowerCase();return e.hittable!==!0&&!ja(e)&&n.includes(`view`)&&W(e).trim().length>0&&!t.some(t=>t.parentIndex===e.index)}function Ka(e){if(e.hittable===!0||ja(e))return!1;let t=(e.type??``).toLowerCase();return t.includes(`text`)||t.includes(`image`)||t.includes(`icon`)}function qa(e){return e.hittable===!0&&!ja(e)&&!!(e.rect&&Da(e.rect))&&!!Na(W(e))}function Ja(e,t,n){if(!Qa(t)||!Oa(t.rect,e.rect))return!1;let r=Na(W(t));return!!(r&&n!==r&&n.includes(r))}function Ya(e,t,n){return!n.has(e.index)&&ka(e.rect,t.rect)&&(ro(e,t)||no(e,t))}function Xa(e,t,n,r,i){let a=$a(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:Za(c.presentationHints,l,s)}),La(e,o.index,r),i.get(a.index)??a}function Za(e,t,n){return[...new Set([...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...n?[n]:[]])]}function Qa(e){if(!e.rect||!Da(e.rect)||Aa(e)||ja(e))return!1;let t=(e.type??``).toLowerCase();return t===`text`||to(t,za)}function $a(e,t){let n=eo(e);return eo(t)>n?t:e}function eo(e){let t=(e.type??``).toLowerCase(),n=0;return to(t,Ra)?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 to(e,t){return t.some(t=>e.includes(t))}function no(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:$a(n,r).index===n.index}function ro(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 io(e,t,n){if(n.raw||!ao(e))return{nodes:t,filteredCount:0};let r=oo(t);return{nodes:r,filteredCount:t.length-r.length}}function ao(e){let t=e.androidSnapshot;return!t||typeof t!=`object`?!1:t.backend===`android-helper`}function oo(e){if(e.length===0)return e;let t=new Set,n=new Map,r=new Map(e.map(e=>[e.index,e]));return so(e,t),co(e,r,t,n),Ba(e,t,n),Ha(e,t),Va(e,t,n),e.filter(e=>!t.has(e.index)).map(e=>n.get(e.index)??e)}function so(e,t){for(let n of e)!n.rect||Da(n.rect)||Aa(n)||La(e,n.index,t)}function co(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||Aa(i))continue;let a=Fa(i,t,Ma);a&&uo(r,a,lo(i,e)),La(e,i.index,n)}}function lo(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&Da(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 uo(e,t,n){if(!n)return;let r=e.get(t.index)??t;e.set(t.index,{...r,hiddenContentAbove:r.hiddenContentAbove===!0||n===`above`||void 0,hiddenContentBelow:r.hiddenContentBelow===!0||n===`below`||void 0})}function fo(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??``).toLowerCase(),r=po(bt(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||!go(e)||(n+=e.length);return n>=8}function po(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||mo(t)?null:t}function mo(e){return e.split(` `).some(ho)}function ho(e){let t=e.indexOf(`@`,1);return t!==-1&&e.lastIndexOf(`.`,e.length-2)>t+1}function go(e){for(let t=0;t<e.length;t+=1)for(let n=t+1;n<e.length;n+=1)if(_o(e[t]?.rect,e[n]?.rect))return!0;return!1}function _o(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)}function vo(t,n={}){let r=t.nodes,i=Array.isArray(r)?r:[],o=a(t.backend)?t.backend:void 0,s=e(o),c=io(t,i,n),l=So(t),ee=jo(t,i,n,c),te=ee.length>0?`${ee.join(`
9
+ `)}\n`:``,ne=n.raw?null:yo(t);if(ne)return`${l}${te}${bo(ne)}\n`;let re=n.raw||!s?null:vn(c.nodes),ie=!!t.truncated,ae=re?.nodes??i,oe=n.raw||!s?null:Oo(t,re,ae.length,i.length,c.filteredCount),se=Co(i.length,oe,ie);return i.length===0?`${l}${se}\n${te}`:n.raw?`${l}${se}\n${te}${wo(i)}\n`:n.flatten?`${l}${se}\n${te}${To(ae)}${Do(re)}\n`:`${l}${se}\n${te}${Eo(ae)}${Do(re)}\n`}function yo(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||void 0,scope:typeof n.scope==`string`?n.scope:void 0}}function bo(e){let t=xo(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(`
10
10
  `):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(`
11
11
  `):[`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(`
12
- `)}function bo(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 xo(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(`
13
- `)}\n`:``}function So(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 Co(e){return e.map(e=>JSON.stringify(e)).join(`
14
- `)}function wo(e){return zo(e).join(`
15
- `)}function To(e){return Io(lt(e,{summarizeTextSurfaces:!0})).join(`
16
- `)}function Eo(e){return e&&e.summaryLines.length>0?`\n${e.summaryLines.join(`
17
- `)}`:``}function Do(e,t,n,r,i=0){let a=Oo(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:ko([...a?.reasons??[],`offscreen-nodes`])}:a||(s?{partial:!0,visibleNodeCount:n,totalNodeCount:n,reasons:[]}:null)}function Oo(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 ko(e){return[...new Set(e)]}function Ao(e,t,n,r={nodes:t,filteredCount:0}){let i=[...Fo(e),...jo(e)];if(Mo(e)){let e=Po(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&&uo(a)&&i.push(`Warning: possible repeated nav subtree detected.`),i}function jo(e){let t=e.fallbackScreenshotPath;return typeof t==`string`&&t.length>0?[`Captured a screenshot of this screen automatically as visual truth: ${t}`]:[]}function Mo(e){return!e.snapshotQuality&&!No(e)}function No(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 Po(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 Fo(e){return on(e).filter(e=>e.length>0)}function Io(e){let t=[],n=[],r=new Map(e.map(e=>[e.node.index,e.node])),i=e=>{for(;n.length>0&&(!e||Lo(e,n.at(-1),r));)t.push(...Bo(n.pop(),`below`))};for(let r of e)i(r),t.push(r.text),t.push(...Bo(r,`above`)),r.node.hiddenContentBelow&&n.push(r);return i(),t}function Lo(e,t,n){return!Ro(e.node,t.node,n)&&e.depth<=t.depth}function Ro(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 zo(e){return lt(e,{summarizeTextSurfaces:!0}).flatMap(e=>[nt(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...Bo({...e,depth:0})])}function Bo(e,t){let n=Vo(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 Vo(e){return e===`scroll-area`||e===`list`||e===`collection`||e===`table`?e:null}async function Ho(e){let{serializeSnapshotResult:t}=await import(`./result-serialization.js`).then(e=>e.t),n=t(e.raw||!Array.isArray(e.result.nodes)?e.result:{...e.result,nodes:wa(e.result.nodes)});return{data:n,jsonData:Wo(n),stderr:e.result.snapshotDiagnostics?.warning?`${e.result.snapshotDiagnostics.warning}\n`:void 0,text:_o(n,{raw:e.raw,flatten:e.interactiveOnly,scoped:typeof e.scope==`string`&&e.scope.trim().length>0,depthLimited:typeof e.depth==`number`})}}const Uo={snapshot:async({input:e,result:t})=>await Ho({result:t,raw:e.raw,interactiveOnly:e.interactiveOnly,scope:e.scope,depth:e.depth}),wait:H,alert:H};function Wo(e){let{unchanged:t,...n}=e;return n}const Go=`snapshot`,Ko=Object.entries(gn).map(([e,t])=>{let n=t.knownGaps.map(e=>`known gap ${e}`);return`${e}: hittable=${t.hittable}, regular-depth=${t.regularDepth}, deep-extension=${t.deepExtension}, depth-ladder=${t.depthLadder}${n.length>0?`, ${n.join(`, `)}`:``}`}).join(`; `),qo=R(Go,`Capture the accessibility tree or compare it with the previous session baseline. Use the returned refs for subsequent semantic interactions and the diff option to verify UI changes.`,{interactiveOnly:P(),depth:N(),scope:j(),raw:P(),customActions:Rr(`snapshotCustomActions`),observeOnly:Rr(`snapshotObserveOnly`),forceFull:P(),timeoutMs:N(`Maximum wall-clock time for the snapshot command.`),noRecord:P(`Do not record this action.`),record:P(`Force-record this out-of-band observation into a repair-armed heal (mutually exclusive with noRecord). Authored replay steps are recorded automatically and never need this.`)}),Jo={allowedFlags:[`snapshotDiff`,...$i,`snapshotCustomActions`,`snapshotObserveOnly`,`snapshotForceFull`,`timeoutMs`,`record`]},Yo=(e,n)=>({...v(n),...ir(n),...t(n,s),timeoutMs:n.timeoutMs}),Xo=g(d.snapshot),Zo=z({name:Go,text:{summary:`Capture or diff the accessibility tree`,cliDetail:`Regular iOS snapshots clip overflowing elements to their visible area and omit fully outside elements. --json reports clipping counts in snapshotQualityNotes with code regular-geometry-clipped; --raw retains reported frames. --observe-only is local iOS snapshot-only: an already-ready compatible runner reads the session app without activation or foreground repair, refuses unavailable observation, and reports XCUIApplication state rather than verified foreground ownership (#2696). Regular targetActivation disclosure stays unchanged (#2682, #2694). Repeated equivalent unfiltered Android snapshots return a compact unchanged acknowledgement. Use --force-full to re-emit the tree; --json and --raw retain full output. Android Appium JSON snapshots publish a display viewport only when measurements before and after the tree agree, independent of tree extent or keyboard content resizing. On Android, JSON value carries field content rather than static labels; saved selectors and replay scripts using value= for static labels must use label= instead; a reported showing hint means value is empty, and text equal to the placeholder is preserved when hint state is unknown. For iOS raw-coordinate fallback after a no-op ref press, inspect rects with snapshot -i --json, press the rect center, then verify with diff snapshot -i or snapshot --diff. iOS backend capability contract: ${Ko}.`},metadata:qo,run:(e,t)=>e.capture.snapshot(t),cliSchema:Jo,cliReader:Yo,daemonWriter:Xo,cliOutputFormatter:Uo.snapshot}),Qo=[`duration`,`text`,`ref`,`selector`,`absent`,`stable`],$o=`wait`,es={wait:C({waitedMs:D(),kind:T(`selector`),text:E(),selector:E(),captures:D(),nodeCount:D(),hint:E(),warning:E()},[`waitedMs`])},ts=z({name:$o,text:{summary:`Wait for a duration, text, selector, strict absence, or stable UI`},metadata:R($o,`Wait for a duration, text, snapshot ref, selector to appear, selector to be strictly absent, or stable UI. Use the strict absence target when zero selector matches are required; stable waits until the UI stays quiet for the requested window.`,{kind:F(Qo),durationMs:N(),text:j(),ref:j(),selector:j(),absent:j(),stable:P(),quietMs:N(),timeoutMs:N(),depth:N(),scope:j(),raw:P()}),run:(e,t)=>e.command.wait(ns(t)),cliSchema:{usageOverride:`wait <ms>|text <text>|@ref|<selector>|absent <selector> [timeoutMs]|stable [quietMs] [timeoutMs]`,usageFlags:[],positionalArgs:[`durationOrSelector`,`timeoutMs?`],allowsExtraPositionals:!0,allowedFlags:[...ea]},cliReader:(e,t)=>rs(e,t),daemonWriter:g(d.wait,e=>os(e)),cliOutputFormatter:H});function ns(e){Hn(e,`kind`,Qo);let t={...e};return delete t.kind,t}function rs(e,t){let r=Et(e);if(!r)throw new n(`INVALID_ARGS`,`wait requires <ms>, text <text>, @ref, <selector> [timeoutMs], absent <selector> [timeoutMs], or stable [quietMs] [timeoutMs].`);let i={...ar(t),...sr(t)};switch(r.kind){case`absent`:return is(i,r);case`sleep`:return{...i,durationMs:r.durationMs};case`text`:return as(i,r);case`ref`:return{...i,ref:r.rawRef,...ss(r.timeoutMs)};case`stable`:return{...i,stable:!0,...cs(r.quietMs),...ss(r.timeoutMs)};case`invalid`:throw new n(`INVALID_ARGS`,r.message);case`selector`:return{...i,selector:r.selectorExpression,...ss(r.timeoutMs)};default:return ls(r)}}function is(e,t){let n=tt(e);if(n)throw vn(n,`wait`);return{...e,absent:t.selectorExpression,...ss(t.timeoutMs)}}function as(e,t){if(!t.text)throw new n(`INVALID_ARGS`,`wait requires text.`);return{...e,text:t.text,...ss(t.timeoutMs)}}function os(e){if([e.durationMs===void 0?void 0:`durationMs`,e.text===void 0?void 0:`text`,e.ref===void 0?void 0:`ref`,e.selector===void 0?void 0:`selector`,e.absent===void 0?void 0:`absent`,e.stable===void 0?void 0:`stable`].filter(Boolean).length!==1)throw new n(`INVALID_ARGS`,`wait command requires exactly one of durationMs, text, ref, selector, absent, or stable.`);if(e.durationMs!==void 0)return[String(e.durationMs)];let t=b(e.timeoutMs);if(e.text!==void 0)return[`text`,e.text,...t];if(e.ref!==void 0)return[e.ref,...t];if(e.absent!==void 0){let r=tt(e);if(r)throw vn(r,`wait`);if(!xt(e.absent))throw new n(`INVALID_ARGS`,`Invalid wait absent selector: ${e.absent}`);return[`absent`,e.absent,...t]}if(e.stable!==void 0){let r=b(e.quietMs);if(r.length===0&&t.length>0)throw new n(`INVALID_ARGS`,`wait stable requires quietMs before timeoutMs.`);return[`stable`,...r,...t]}let r=e.selector;if(!xt(r))throw new n(`INVALID_ARGS`,`Invalid wait selector: ${r}`);return[r,...t]}function ss(e){return e===null?{}:{timeoutMs:e}}function cs(e){return e===null?{}:{quietMs:e}}function ls(e){throw Error(`Unsupported wait positional target: ${String(e)}`)}const us=B({name:`capture`,commands:[Zo,ma,fa,ts,Ji,xa]});function ds(e){let t=[e.outPath,e.message];t.push(...ps(e));for(let n of e.matchedImages)t.push(`Matched: ${n.name} ${n.uuid}${n.arch?` ${n.arch}`:``}`);for(let n of e.warnings??[])t.push(`Warning: ${n}`);return{data:e,text:t.join(`
18
- `)}}const fs={debug:V(ds)};function ps(e){let t=e.crash,n=[`Crash: ${t.appName??`unknown app`}${t.crashedThread===void 0?``:` thread ${t.crashedThread}`}`];t.bundleId&&n.push(`Bundle: ${t.bundleId}`),t.exceptionType&&n.push(`Exception: ${t.exceptionType}`),t.terminationReason&&n.push(`Termination: ${t.terminationReason}`);for(let e of t.topFrames)n.push(`Frame ${e.index}: ${e.image} ${e.symbol??e.address}`);for(let e of t.findings)n.push(`Finding: ${e}`);return n}const ms=`debug`,hs=B({name:`debugging`,commands:[z({name:ms,text:{summary:`Symbolicate Apple crash artifacts`},metadata:R(ms,`Symbolicate Apple crash artifacts with matching dSYM UUIDs. This debug namespace is intentionally narrow: use logs for app logs, network for HTTP evidence, perf for performance samples, record/trace for media and traces, and react-devtools for React Native components and render profiles.`,{action:A(F([`symbols`])),artifact:A(j(`Apple crash artifact path (.ips, .crash, or .log).`)),dsym:j(`Path to a matching .dSYM bundle.`),searchPath:j(`Directory to scan for matching .dSYM bundles.`),out:j(`Output path for the symbolicated artifact.`)}),run:(e,t)=>e.debug.symbols(t),cliSchema:{usageOverride:`debug symbols --artifact <crash.ips|crash.log> (--dsym <App.dSYM> | --search-path <dir>) [--out <symbolicated>]`,usageFlags:[],listUsageOverride:`debug`,positionalArgs:[`symbols`],allowedFlags:[`artifact`,`dsym`,`searchPath`,`out`]},cliReader:(e,t)=>({...v(t),action:gs(e[0]),artifact:t.artifact,dsym:t.dsym,searchPath:t.searchPath,out:t.out}),cliOutputFormatter:fs.debug})]});function gs(e){if(e===`symbols`)return e;throw new n(`INVALID_ARGS`,`debug supports only symbols; use logs, network, perf, record, trace, or react-devtools for other diagnostics`)}const _s=()=>P(`Capture cheap post-action evidence (AX digest, node counts, changedFromBefore) instead of a follow-up snapshot.`),vs=()=>({settle:P(`After the action, wait for the UI to go quiet and return the settled diff vs the pre-action tree in the same response. Best-effort; never fails the action.`),settleQuietMs:N(`Settle: quiet window in milliseconds (default 500; 300 when the settled tree comes from the iOS simulator snapshot bridge). On iOS, a broad screen replacement such as a modal dismissal is confirmed for at least 1500ms whatever window is asked for, within the timeoutMs settle deadline; a replacement from a screen the pre-action capture read as presenting nothing, such as a tab switch, gets no 1500ms confirmation and keeps the asked window.`,{min:0}),timeoutMs:N(`Settle: wait deadline in milliseconds (default 10000).`,{min:1})});function ys(e){return{...Pt(e)?{verify:_s()}:{},...Ft(e)?vs():{}}}function bs(e){let t=[];return Pt(e)&&t.push(`verify`),Ft(e)&&t.push(...aa),t}function xs(e,t){return Ft(e)?cr(t):{}}const Ss=[`click`,`focus`,`exists`,`list`,`getText`,`getAttrs`,`wait`,`fill`,`type`],Cs={click:`Activate a UI target by snapshot ref, selector, or coordinates. Prefer a ref or selector after a snapshot; use coordinates only when semantic targeting is unavailable. This can change app state. Success means the click was dispatched, not that it landed: use settle or verify to confirm the result without a follow-up snapshot, or wait for the expected screen. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was.`,press:`Short-press a UI target by snapshot ref, selector, or coordinates. Use longpress instead when the target requires a context-menu or hold gesture. Success means the press was dispatched, not that it landed: use settle or verify to confirm the result, or wait for the expected screen. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was.`,fill:`Replace text in a UI input selected by snapshot ref, selector, or coordinates. Pass an empty text to clear the field. Inspect unconfirmed evidence and assert the expected value or resulting screen before continuing. Prefer refs or selectors after snapshot; use recordAs to keep sensitive text out of a recorded replay while sending it to the live app.`,longpress:`Hold a UI target by snapshot ref, selector, or coordinates to open a context menu or perform another hold gesture. Set durationMs when the default hold duration is unsuitable.`,hover:`Move the pointer over a UI target by snapshot ref, selector, or coordinates without pressing, to reveal hover-gated UI such as row toolbars or menus. Web only; touch platforms have no hover state. Use settle to observe what the hover revealed without a follow-up snapshot.`,swipe:`Quick coordinate fling with optional repeat pattern.`,focus:`Move input focus to explicit screen coordinates without entering text. Prefer semantic interactions when a snapshot ref or selector is available; use type or fill after focus.`,type:`Append text to the currently focused input. Use fill when the existing field value should be replaced, and focus first when no input is active.`,scroll:`Scroll in a direction, or toward the top/bottom edge of scrollable content. Set until to a selector to reach an off-screen target in one command rather than a scroll-and-check loop. The optional amount is the finger-path fraction of the viewport axis, honored up to 0.8 of it; directional scrolls reduce release momentum, while app scroll physics determine the final content offset. A visible keyboard shortens the swiped band instead of being dismissed; when too little is left, the command refuses with scroll_keyboard_occludes_surface. A directional scroll also reports the movement it observed as movement: moved, at-edge, unchanged, or unobserved when the two reads could not back a claim either way; an unchanged surface inside a container that still hides content in that direction refuses with scroll_no_progress rather than repeating the requested distance. The movement field is absent where a tier verifies per pass (top/bottom, until), where the runtime cannot read a screen, or where a settle observation or a replay already owns that observation.`,get:`Read text or accessibility attributes from a snapshot ref or selector without changing the app. Use format text for visible content or attrs for the element attribute map.`,is:"Check whether a selector satisfies a UI predicate such as visible, hidden, exists, absent, editable, selected, focused, or text. `absent` passes only when one readable, complete, settled, unscoped, full-depth accessibility capture has zero matches. Use wait when the condition may appear asynchronously.",find:`Find by text/label/value/role/id and run action. The role locator matches snapshot kind vocabulary (button, text, text-field, switch, ...); pre-reconciliation leaf spellings (statictext, edittext, textview) stay accepted on the nodes that carried them during a deprecation window.`,gesture:`Perform a structured pan, fling, swipe, pinch, rotate, transform, tap, or drag gesture. Select the gesture kind, then provide only the inputs that apply to that kind. A tap touches 2 to 5 points at once; repeat it with count and pauseMs.`},ws={target:A(Gr()),button:F(st,`Pointer button for platforms that support mouse buttons.`),...Xr(),...Zr(),...ys(`click`)},Ts={target:A(Gr()),...Xr(),...Zr(),...ys(`press`)},Es={target:A(Gr()),text:A(j(`Text to enter into the target. Pass "" to clear it.`,{allowEmpty:!0})),delayMs:N(`Delay between typed characters.`,{min:0}),recordAs:j("When script recording is armed, send text to the live app but publish it as ${VAR}. Use an uppercase replay variable name such as PASSWORD."),textStdin:Lr(P(`Operator-only: text was read from the CLI's stdin, so it is kept out of diagnostics and recorded actions.`),{operatorPath:`Pass --text-stdin on the CLI and pipe the text in; it is not exposed to model-facing tools.`}),...Xr(),...ys(`fill`)},Ds={target:A(Gr()),durationMs:N(`Long press duration in milliseconds.`,{min:0}),...Xr(),...ys(`longpress`)},Os={target:A(Gr()),...Xr(),...ys(`hover`)},ks={from:A(qr(`Swipe start point.`)),to:A(qr(`Swipe end point.`)),count:N(`Number of swipe repetitions.`,{min:1,max:200}),pauseMs:N(`Pause between repeated swipes.`,{min:0,max:Ee}),pattern:F(_e)},As={x:A(M(`X coordinate.`)),y:A(M(`Y coordinate.`))},js={text:A(j(`Text to type.`)),delayMs:N(`Delay between typed characters.`,{min:0})},Ms={direction:A(F(ke)),amount:M(`Platform scroll amount.`),pixels:N(`Pixel scroll amount.`,{min:0}),until:j(`Repeat scroll passes until this selector is visible on screen, then stop. Not valid with the top/bottom edge directions, which carry their own stop condition.`),maxPasses:N(`Maximum scroll gestures for an until search (default 12). Requires until.`,{min:1,max:200}),durationMs:N(`Scroll duration in milliseconds when the backend supports pacing.`,{min:0,max:oe}),...ys(`scroll`)},Ns=()=>({noRecord:P(`Do not record this action.`),record:P(`Force-record this out-of-band observation into a repair-armed heal (mutually exclusive with noRecord). Authored replay steps are recorded automatically and never need this. On find, valid only for a read-only action.`)}),Ps={format:A(F([`text`,`attrs`])),target:A(Kr()),...Xr(),...Ns()},Fs={predicate:A(F(Rt)),selector:A(j()),value:j(),...Xr(),...Ns()},Is={locator:F(wt),query:A(j()),action:F(Ss),value:j(void 0,{allowEmpty:!0}),timeoutMs:N(),first:P(),last:P(),depth:N(),raw:P(),...Ns()},Ls={kind:A(F(ct,`Gesture variant.`)),direction:F(Te,`Fling direction.`),preset:F(Ae,`Swipe preset.`),origin:qr(`Gesture origin point.`),delta:qr(`Movement delta for pan or transform gestures.`),distance:N(`Fling distance.`,{min:0}),scale:M(`Pinch or transform scale.`),degrees:M(`Rotation in degrees.`),durationMs:N(`Pan/transform duration.`,{min:16,max:1e4}),pointerCount:N(`Pan touch pointer count (1 or 2).`,{min:1,max:2}),points:Jr(`Tap contact points, held together for holdMs.`,{min:2,max:5}),holdMs:N(`Tap contact hold duration.`,{min:16,max:l}),count:N(`Tap repetitions; the same contacts run this many times.`,{min:1,max:200}),pauseMs:N(`Delay between tap repetitions, added to each repetition’s own time.`,{min:0,max:Ee}),source:j(`Drag source @ref or selector.`),destination:j(`Drag destination @ref or selector.`),sourceHoldMs:N(`Drag activation hold duration.`,{min:1,max:1e4}),moveMs:N(`Drag movement duration.`,{min:16,max:1e4}),destinationHoldMs:N(`Hold before releasing at the destination.`,{min:0,max:1e4})},Rs=[G(`click`,ws),G(`press`,Ts),G(`fill`,Es),G(`longpress`,Ds),G(`hover`,Os),G(`swipe`,ks),G(`focus`,As),G(`type`,js),G(`scroll`,Ms),G(`get`,Ps,{parseableOutput:!0}),G(`is`,Fs),G(`find`,Is,{parseableOutput:!0}),R(`gesture`,Cs.gesture,Ls,{readInput:zs})];function zs(e){let t=Fn(e);return{...$n(t),...ut(t)}}function G(e,t,n){return R(e,Cs[e],t,n)}const Bs={gesture:Hs},Vs={gesture:e=>{let t=zs(e);return _(d.gesture,[],e,m(t))}};function Hs(e,t){return{...v(t),...ft(e,{pointerCount:t.pointerCount,holdMs:t.holdMs,count:t.count,pauseMs:t.pauseMs})}}const K={click:(e,t)=>({...v(t),...or(t),...lr(t),target:dr(yn(e)),button:t.clickButton,verify:t.verify}),press:(e,t)=>({...v(t),...or(t),...lr(t),target:dr(yn(e)),verify:t.verify}),longpress:(e,t)=>{let n=Ws(e);return{...v(t),...or(t),target:dr(n),durationMs:n.durationMs}},hover:(e,t)=>({...v(t),...or(t),target:dr(yn(e))}),swipe:(e,t)=>({...v(t),...$e(e,{count:t.count,pauseMs:t.pauseMs,pattern:t.pattern})}),focus:(e,t)=>({...v(t),x:Number(e[0]),y:Number(e[1])}),type:(e,t)=>({...v(t),text:e.join(` `),delayMs:t.delayMs}),fill:(e,t)=>{let n=t.textStdin?Us(e):bn(e);return{...v(t),...or(t),target:dr(n.target),text:n.text,delayMs:t.delayMs,recordAs:t.recordAs,textStdin:t.textStdin,verify:t.verify}},scroll:(e,t)=>({...v(t),direction:Js(e[0]),amount:wr(e[1]),pixels:t.pixels,durationMs:t.durationMs,until:t.until,maxPasses:t.maxPasses}),get:(e,t)=>({...v(t),...ir(t),...or(t),format:vr(e[0]),target:dr(_r(e.slice(1)))})},q={click:e=>_(d.click,fr(e),{...e,clickButton:e.button}),press:g(d.press,e=>fr(e)),longpress:g(d.longPress,e=>Gs(e)),hover:g(d.hover,e=>fr(e)),swipe:e=>(Je(e),_(d.swipe,[],e,{from:e.from,to:e.to,count:e.count,pauseMs:e.pauseMs,pattern:e.pattern})),focus:g(d.focus,e=>[String(e.x),String(e.y)]),type:g(d.type,e=>Ks(e)),fill:g(d.fill,e=>qs(e)),scroll:g(d.scroll,e=>[S(e.direction,`scroll requires direction`),...b(e.amount)]),get:g(d.get,e=>[S(e.format,`get requires format`),...pr(e)])};function Us(e){let t;try{t=bn(e)}catch(e){throw e instanceof n?new n(`INVALID_ARGS`,`fill --text-stdin could not read the target.`,{reason:`fill_text_stdin_target_invalid`,hint:`Pass only the target: an @ref, a quoted selector, or x y coordinates. The text itself goes to stdin.`}):e}if(t.text!==void 0)throw new n(`INVALID_ARGS`,`fill --text-stdin reads the text from stdin, so it cannot also take a text argument.`,{reason:`fill_text_source_conflict`,hint:`Pass only the target, for example: printf %s "$PASSWORD" | agent-device fill @e3 --text-stdin. Quote a multi-word selector so no part of it is read as text.`});return t}function Ws(e){let t=Ys(e);return{...yn(t.target),...t.durationMs===void 0?{}:{durationMs:t.durationMs}}}function Gs(e){return[...fr(e),...b(e.durationMs)]}function Ks(e){return[e.text]}function qs(e){return[...fr(e),e.text]}function Js(e){if(e===`up`||e===`down`||e===`left`||e===`right`||e===`top`||e===`bottom`)return e;throw new n(`INVALID_ARGS`,`Unknown direction: ${String(e)}`,{hint:`scroll takes a direction first, then an optional amount: scroll <up|down|left|right|top|bottom> [amount]. It takes no @ref or selector — scroll the whole viewport, then retry the target with a selector.`})}function Ys(e){if(Sr(e[0])&&Sr(e[1]))return{target:e.slice(0,2),...e[2]===void 0?{}:{durationMs:Number(e[2])}};let t=e.at(-1);return e.length>1&&Sr(t)?{target:e.slice(0,-1),durationMs:Number(t)}:{target:e}}function Xs(e){return t=>{let n=e(t);return n instanceof Promise?n.then(Zs):Zs(n)}}function Zs(e){return{data:e.data,text:$s(e.text,e.data)}}function Qs(e){let t={...e};for(let[n,r]of Object.entries(e))Ft(n)&&(t[n]=Xs(r));return t}function $s(e,t){return`${e??``}${ec(t.settle)}`}function ec(e){if(!e||typeof e!=`object`)return``;let t=e,n=[ic(t),...tc(t),...rc(t)];return t.hint&&n.push(`hint: ${t.hint}`),`\n${n.join(`
19
- `)}`}function tc(e){let t=e.diff,n=(t?.lines??[]).map(t=>`${t.kind===`removed`?`-`:`+`} ${nc(t,e.refsGeneration)}`);return t?.truncated&&n.push(`… changed lines truncated`),n}function nc(e,t){let n=e.text??``,r=Ci(e.ref,t);if(!r||!e.ref)return n;let i=`@${e.ref}`;return n.startsWith(`${i} `)?`${r}${n.slice(i.length)}`:`${r} ${n}`}function rc(e){let t=e.tail??[];if(t.length===0)return[];let n=[`unchanged interactive (${t.length}):`];for(let r of t){let t=r.label?` "${r.label}"`:``,i=Ci(r.ref,e.refsGeneration)??`@${r.ref??``}`;n.push(`= ${i} [${r.role??``}]${t}`)}return e.tailTruncated&&n.push(`… more interactive elements not shown, use snapshot -i`),n}function ic(e){let t=e.settled===!0?`settled`:`not settled`,n=e.diff?.summary;return n?`${t} after ${e.waitedMs??0}ms: +${n.additions??0} -${n.removals??0} (~${n.unchanged??0} unchanged)`:`${t} after ${e.waitedMs??0}ms`}function ac(e){let t=e.result;return e.format===`attrs`?{data:t,text:JSON.stringify(t.node??{},null,2)}:{data:t,text:typeof t.text==`string`?t.text:``}}function oc(e){let t=e,n=sn(t);if(n)return{data:t,text:n};if(typeof t.text==`string`)return{data:t,text:t.text};if(Array.isArray(t.matches))return{data:t,text:sc(t.matches,t.refsGeneration)};let r=Ci(t.ref,t.refsGeneration);return r?{data:t,text:`Found: ${r}`}:typeof t.found==`boolean`?{data:t,text:`Found: ${t.found}`}:t.node?{data:t,text:JSON.stringify(t.node,null,2)}:vi(t)}function sc(e,t){return[`${e.length} match${e.length===1?``:`es`}:`,...e.map(e=>cc(e,t))].join(`
20
- `)}function cc(e,t){let n=e.ref===void 0?`(no ref)`:Ci(e.ref,t)??e.ref,r=c(e.node?.type??`Element`),i=e.node?ot(e.node,r):``;return`= ${n} [${r}]${i?` "${i}"`:``}`}function lc(e){let t=e;return{data:t,text:`Passed: is ${t.predicate??`assertion`}`}}function uc(e){let t=e,n=t.ref??``,r=t.x,i=t.y;return!n||typeof r!=`number`||typeof i!=`number`?vi(t):{data:t,text:`Tapped @${n} (${r}, ${i})`}}const J=Qs({click:V(uc),press:V(uc),fill:H,longpress:H,hover:H,scroll:H,get:({input:e,result:t})=>ac({result:t,format:e.format===`attrs`?`attrs`:`text`}),is:V(lc),find:V(oc)}),dc={find:(e,t)=>hc(e,t),is:(e,t)=>gc(e,t)},fc={is:g(d.is,e=>pc(e)),find:e=>_(d.find,mc(e),{...e,findFirst:e.first,findLast:e.last})};function pc(e){return[e.predicate,e.selector,...e.predicate===`text`?[e.value]:[]]}function mc(e){let t=e.locator&&e.locator!==`any`?[e.locator,e.query]:[e.query];switch(e.action){case void 0:case`click`:case`focus`:case`exists`:case`list`:return e.action?[...t,e.action]:t;case`getText`:return[...t,`get`,`text`];case`getAttrs`:return[...t,`get`,`attrs`];case`wait`:return[...t,`wait`,...b(e.timeoutMs)];case`fill`:case`type`:return[...t,e.action,e.value]}}function hc(e,t){let r={...bc(t),...ar(t),...ir(t),first:t.findFirst,last:t.findLast},i=yc(e[0]),a=i!==void 0,o=a?e[1]:e[0],s=a?2:1,c=kt(e[s]);if(c===void 0)return{...r,locator:i,query:xc(o)};if(c===`get`){let t=e[s+1];if(t===`text`)return{...r,locator:i,query:xc(o),action:`getText`};if(t===`attrs`)return{...r,locator:i,query:xc(o),action:`getAttrs`};throw new n(`INVALID_ARGS`,`find get only supports text or attrs`)}if(c===`wait`)return{...r,locator:i,query:xc(o),action:`wait`,timeoutMs:wr(e[s+1])};if(c===`fill`||c===`type`){let t=e.slice(s+1);if(t.length===0)throw new n(`INVALID_ARGS`,c===`fill`?`find fill requires text (use "" to clear the field)`:`find type requires text`);return{...r,locator:i,query:xc(o),action:c,value:t.join(` `)}}if(c===`click`||c===`focus`||c===`exists`||c===`list`)return{...r,locator:i,query:xc(o),action:c};throw new n(`INVALID_ARGS`,`Unsupported find action: ${e[s]}`,{hint:Dt})}function gc(e,t){let r={...sr(t),...ar(t),...ir(t)},i=Ct(e),a=Tt(i[0]??``);if(!a.ok)throw new n(a.code,a.message,{hint:a.hint});let o=a.predicate;if(o===`absent`){let e=_c(r);if(e)throw vc(e)}let s=yr(i.slice(1),{preferTrailingValue:o===`text`});return o===`text`?{...r,predicate:o,selector:s.selectorExpression,value:s.rest.join(` `)}:{...r,predicate:o,selector:s.selectorExpression}}function _c(e){if(e.scope!==void 0)return`scope`;if(e.depth!==void 0)return`depth`}function vc(e){return new n(`INVALID_ARGS`,e===`scope`?`is absent does not support --scope; it requires an unscoped capture`:`is absent does not support --depth; it requires a full-depth capture`,{command:`is`,predicate:`absent`,rejectedOption:e})}function yc(e){if(e===`text`||e===`label`||e===`value`||e===`role`||e===`id`)return e}function bc(e){return{depth:e.snapshotDepth,raw:e.snapshotRaw}}function xc(e){if(e===void 0||e===``)throw new n(`INVALID_ARGS`,`find requires query`);return e}const Sc=C({from:E(`Surface the pre-action baseline described: a host bundle id, or app.`),to:E(`Surface the post-action capture describes: a host bundle id, or app.`),disclosure:E(`Agent-facing sentence explaining the surface transition.`)},[`from`,`to`,`disclosure`],`Present when an in-place system surface (web sign-in or Apple Pay sheet) was presented over the app, or left it.`),Cc=C({foregroundApp:E(`Foreground app bundle id or name, when the capture carries it.`),nodeCount:D(`Node count in the post-action interactive-only capture.`),interactiveNodeCount:D(`Subset of nodeCount the platform reports as hittable.`),digest:E(`Order-independent digest of the post-action node multiset.`),changedFromBefore:O(`Whether the post-action digest differs from the pre-action capture digest. false is evidence, not failure. With surfaceChange present, no digest comparison is made: it reports that surface transition.`),surfaceChange:Sc},[`nodeCount`,`interactiveNodeCount`,`digest`,`changedFromBefore`]),wc=C({wallClockMs:D(`Total wall-clock time for the request in milliseconds.`),runnerRoundTrips:D(`Number of real runner round-trips made while serving the request.`),nodeCount:D(`Number of nodes in the original node tree when the response carries one.`)},[`wallClockMs`,`runnerRoundTrips`]),Tc=C({diagnosticRef:E(`Opaque non-@ diagnostic token. Never a snapshot ref: not issued via refsGeneration and cannot be pinned or reused as an @ref target. UTF-8 truncated to 256 bytes.`),role:E(`UTF-8 truncated to 256 bytes.`),label:E(`UTF-8 truncated to 256 bytes.`)},[`diagnosticRef`]),Ec={type:`object`,description:`Pre-action disclosure of how the acting path resolved its target. Absent when resolutionDisclosure is inapplicable for the path.`,oneOf:[C({source:T(`runtime`),phase:T(`pre-action`),kind:T(`unique`)},[`source`,`phase`,`kind`]),C({source:T(`runtime`),phase:T(`pre-action`),kind:T(`disambiguated`),matchCount:D(`Total matches resolveSelectorChain found before disambiguation.`),winnerDiagnostic:Tc,tiebreak:w([`visible`,`deepest`,`smallest-area`,`structural-equivalence`],`The comparison that decided the winner.`),alternatives:{type:`array`,description:`At most 5 losing candidates, document order. Present at default/full response levels and omitted in digest. The winner is never included.`,items:Tc}},[`source`,`phase`,`kind`,`matchCount`,`winnerDiagnostic`,`tiebreak`]),C({source:T(`ref`),phase:T(`pre-action`),kind:T(`exact`)},[`source`,`phase`,`kind`]),C({source:T(`ref`),phase:T(`pre-action`),kind:T(`label-fallback`)},[`source`,`phase`,`kind`]),C({source:T(`direct-ios`),kind:T(`not-observed`)},[`source`,`kind`])]};function Dc(e={}){let t=e.properties??{},n=e.required??[];return C({targetKind:w([`point`,`ref`,`selector`],`Resolved interaction target kind.`),x:D(`Resolved interaction x coordinate when available.`),y:D(`Resolved interaction y coordinate when available.`),referenceWidth:D(`Reference frame width for visualizing the interaction point.`),referenceHeight:D(`Reference frame height for visualizing the interaction point.`),ref:E(`Snapshot ref without the @ prefix when the target was an @ref.`),selector:E(`Selector expression when the target was a selector.`),selectorChain:Fr(),refLabel:E(),targetHittable:O(),hint:E(),warning:E(),message:E(),evidence:Cc,resolution:Ec,cost:wc,maestroNonHittableCoordinateFallbackAllowed:O(`Whether the direct iOS Maestro coordinate fallback was allowed for this selector.`),maestroNonHittableCoordinateFallbackUsed:O(`Whether the direct iOS Maestro coordinate fallback was actually used.`),maestroFallbackReason:T(`non-hittable-coordinate`),...t},[`targetKind`,...n])}const Oc=Dc({properties:{evidence:Cc,button:w([`secondary`,`middle`]),count:D(`Number of press/click repetitions.`),intervalMs:D(`Delay between repeated press/click actions.`),holdMs:D(`Hold duration for each action.`),jitterPx:D(`Deterministic per-axis coordinate jitter in pixels (each press offsets x and y by up to this amount).`),doubleTap:O(`Whether the command requested a double-tap action.`)}}),kc={text:E(`Text submitted to the field.`),delayMs:D(`Delay between typed characters in milliseconds.`),evidence:Cc},Ac=C({resourceId:Nr(`Identifier of the exact field that changed: Android resource id or Apple accessibility identifier.`),className:Nr(`Type of the exact field that changed: Android class name or Apple element type.`),packageName:Nr(`App that owns the exact field: Android package name or Apple bundle id.`),rect:C({x:D(),y:D(),width:D(),height:D()},[`x`,`y`,`width`,`height`],`Screen-space rectangle of the exact field that changed.`)},[`resourceId`,`className`,`packageName`,`rect`],`Target identity captured before fill and matched after fill.`),jc={press:Oc,click:Oc,fill:{type:`object`,description:`Fill response. Target-bound unconfirmed evidence reports an observed value different from the requested text. It does not establish that formatting preserved the input; assert the expected value or resulting screen before continuing.`,oneOf:[{...Dc({properties:kc,required:[`text`]}),not:C({},[`verification`])},Dc({properties:{...kc,verification:T(`unconfirmed`),requested:E(`Literal text requested by the fill command.`),before:Nr(`Raw target text captured before the fill.`),after:Nr(`Raw target text captured after the fill.`),target:Ac},required:[`text`,`verification`,`requested`,`before`,`after`,`target`]})]},longpress:Dc({properties:{durationMs:D(),gesture:T(`longpress`)}}),hover:Dc({properties:{gesture:T(`hover`)}}),find:C({ref:E(`Snapshot ref without the @ prefix when the find action returns one.`),refsGeneration:D(`ADR 0014 ref frame epoch for read-only find actions.`),found:O(`Whether a wait/exists/read-only find satisfied its condition.`),waitedMs:D(`Milliseconds waited for a read-only find condition.`),text:E(`Text value returned by find get_text.`),node:k(`Snapshot node for find get_attrs/get_text.`),matches:{type:`array`,description:`Every match for the read-only find list action (#1625): { ref, node } each.`,items:k(`One listed match with its snapshot ref and node.`)},locator:E(`Locator kind used for the find action.`),query:E(`Query argument used for the find action.`),x:D(`Resolved x coordinate for mutating find actions.`),y:D(`Resolved y coordinate for mutating find actions.`),message:E(`Diagnostic message for mutating find actions.`),cost:wc},[],`Daemon response data for the find command.`)},Mc=Ze,Nc=[...new Set(Object.values(Mc).flat())],Y={get:{usageOverride:`get text|attrs <@ref|selector>`,usageFlags:[],positionalArgs:[`subcommand`,`target`],allowsExtraPositionals:!0,allowedFlags:[...ea,`record`]},find:{usageOverride:`find <locator|text> <action> [value] [--first|--last]`,usageFlags:[],positionalArgs:[`query`,`action`,`value?`],allowsExtraPositionals:!0,allowedFlags:[`snapshotDepth`,`snapshotRaw`,`findFirst`,`findLast`,`record`]},is:{positionalArgs:[`predicate`,`selector`,`value?`],allowsExtraPositionals:!0,allowedFlags:[...ea,`record`]},click:{usageOverride:`click <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`target`],allowsExtraPositionals:!0,allowedFlags:[...ia,`clickButton`,...bs(`click`),...ea]},press:{usageOverride:`press <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...ia,...bs(`press`),...ea]},longpress:{usageOverride:`longpress <x y|@ref|selector> [durationMs]`,usageFlags:[],positionalArgs:[`targetOrX`,`yOrDurationMs?`,`durationMs?`],allowsExtraPositionals:!0,allowedFlags:[...bs(`longpress`),...ea]},hover:{usageOverride:`hover <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...bs(`hover`),...ea]},swipe:{positionalArgs:[`x1`,`y1`,`x2`,`y2`],allowsExtraPositionals:!0,allowedFlags:[`count`,`pauseMs`,`pattern`]},gesture:{usageOverride:`gesture <pan|fling|swipe|pinch|rotate|transform|tap|drag> ...`,usageFlags:[],listUsageOverride:`gesture <pan|fling|swipe|pinch|rotate|transform|tap|drag> ...`,positionalArgs:[`pan|fling|swipe|pinch|rotate|transform|tap|drag`,`args?`],allowsExtraPositionals:!0,allowedFlags:Nc,flagsByAction:Mc},focus:{positionalArgs:[`x`,`y`]},type:{positionalArgs:[`text`],allowsExtraPositionals:!0,allowedFlags:[`delayMs`]},fill:{usageOverride:`fill <x> <y> <text> | fill <@ref|selector> <text> | fill <x y|@ref|selector> --text-stdin`,usageFlags:[],positionalArgs:[`targetOrX`,`yOrText`,`text?`],allowsExtraPositionals:!0,allowedFlags:[...ea,`delayMs`,`recordAs`,`textStdin`,...bs(`fill`)]},scroll:{usageOverride:`scroll <direction|top|bottom> [amount]`,usageFlags:[`until`,`maxPasses`,`pixels`,`durationMs`,`settle`],positionalArgs:[`directionOrEdge`,`amount?`],allowedFlags:[`pixels`,`durationMs`,`until`,`maxPasses`,...bs(`scroll`)]}},Pc=B({name:`interaction`,clientSurface:!1,commands:[z({name:`click`,text:{summary:`Click or tap a UI target`},metadata:X(`click`),run:(e,t)=>e.interactions.click(Fc(t)),cliSchema:Y.click,cliReader:K.click,daemonWriter:q.click,cliOutputFormatter:J.click}),z({name:`press`,text:{summary:`Short-press a UI target`,cliDetail:`The hold duration is positional on longpress, not press --hold-ms.`},metadata:X(`press`),run:(e,t)=>e.interactions.press(Ic(t)),cliSchema:Y.press,cliReader:K.press,daemonWriter:q.press,cliOutputFormatter:J.press}),z({name:`fill`,text:{summary:`Replace text in a UI input`,cliDetail:`Every positional after an @ref is the replacement text, so fill @e57 good morning enters "good morning"; quote the text when the shell must preserve exact whitespace. Clear a field with an empty text argument: fill @e57 "" (the argument must be present — fill @e57 alone is a missing argument, not a clear). When visible label text also matches a non-input element, constrain the target with editable=true, for example fill 'label="Email" editable=true' "qa@example.com". To keep a secret out of argv, omit the text and pipe it in: printf %s "$PASSWORD" | fill @e57 --text-stdin (max 64 KiB, one trailing newline removed). On web, a coordinate fill selects the clicked field in the page and refuses with COMMAND_FAILED and details.reason text_entry_focus_not_observed, before it sends any text or key, when the click did not reach an editable text field it can reach: a read-only, disabled, date, checkbox, or select control, a field in a cross-origin frame, a sandboxed frame without allow-same-origin, or a closed shadow root, or a click that missed. The click has already landed, so run snapshot -i again and fill the field it reports by ref (fill @e2 text); a selector fill reaches the same coordinate path and hits the same limits.`},metadata:X(`fill`),run:(e,t)=>e.interactions.fill(Lc(t)),cliSchema:Y.fill,cliReader:K.fill,daemonWriter:q.fill,cliOutputFormatter:J.fill}),z({name:`longpress`,text:{summary:`Hold a UI target to open a context menu`,cliDetail:`Duration is positional, for example longpress @e12 800 or longpress 300 500 800.`},metadata:X(`longpress`),run:(e,t)=>e.interactions.longPress(Rc(t)),cliSchema:Y.longpress,cliReader:K.longpress,daemonWriter:q.longpress,cliOutputFormatter:J.longpress}),z({name:`hover`,text:{summary:`Hover the pointer over a UI target (web only)`,cliDetail:`The pointer stays where hover left it: read the revealed UI (--settle or snapshot -i) and act on it before another click or hover moves the pointer away.`},metadata:X(`hover`),run:(e,t)=>e.interactions.hover(zc(t)),cliSchema:Y.hover,cliReader:K.hover,daemonWriter:q.hover,cliOutputFormatter:J.hover}),z({name:`swipe`,text:{summary:`Fling between coordinates`},metadata:X(`swipe`),run:(e,t)=>e.interactions.swipe(t),cliSchema:Y.swipe,cliReader:K.swipe,daemonWriter:q.swipe}),z({name:`focus`,text:{summary:`Focus input at screen coordinates`},metadata:X(`focus`),run:(e,t)=>e.interactions.focus(t),cliSchema:Y.focus,cliReader:K.focus,daemonWriter:q.focus}),z({name:`type`,text:{summary:`Append text to the focused input`},metadata:X(`type`),run:(e,t)=>e.interactions.type(t),cliSchema:Y.type,cliReader:K.type,daemonWriter:q.type}),z({name:`scroll`,text:{summary:`Scroll in a direction or to an edge`},metadata:X(`scroll`),run:(e,t)=>e.interactions.scroll(t),cliSchema:Y.scroll,cliReader:K.scroll,daemonWriter:q.scroll,cliOutputFormatter:J.scroll}),z({name:`get`,text:{summary:`Read element text or attributes`},metadata:X(`get`),run:(e,t)=>e.interactions.get(Vc(t)),cliSchema:Y.get,cliReader:K.get,daemonWriter:q.get,cliOutputFormatter:J.get}),z({name:`is`,text:{summary:`Check a UI predicate on a selector`},metadata:X(`is`),run:(e,t)=>e.interactions.is(t),cliSchema:Y.is,cliReader:dc.is,daemonWriter:fc.is,cliOutputFormatter:J.is}),z({name:`find`,text:{summary:`Find an element and act`},metadata:X(`find`),run:(e,t)=>e.interactions.find(t),cliSchema:Y.find,cliReader:dc.find,daemonWriter:fc.find,cliOutputFormatter:J.find}),z({name:`gesture`,text:{summary:`Run pan, fling, swipe, pinch, rotate, transform, tap, or drag gestures`,cliDetail:`Argument shapes: pan <x> <y> <dx> <dy> [durationMs], fling <up|down|left|right> <x> <y> [distance], swipe <left|right|left-edge|right-edge>, pinch <scale> [x] [y], rotate <degrees> [x] [y], transform <x> <y> <dx> <dy> <scale> <degrees> [durationMs], tap <x1> <y1> <x2> <y2> [... <x5> <y5>] [--hold-ms <ms>] [--count <n>] [--pause-ms <ms>], or drag <source-selector|pinned-ref> <destination-selector|pinned-ref> [sourceHoldMs] [moveMs] [destinationHoldMs]. For command plans, output only command lines. Android transform verification should use all app-observable effects, for example wait text "pan changed yes", wait text "pinch changed yes", and wait text "rotate changed yes", not exact transform values.`},metadata:X(`gesture`),run:(e,t)=>e.interactions.gesture({...ut(t),...h(t)}),cliSchema:Y.gesture,cliReader:Bs.gesture,daemonWriter:Vs.gesture})]});function X(e){let t=Rs.find(t=>t.name===e);if(!t)throw Error(`Missing interaction command metadata for ${e}`);return t}function Fc(e){return{...Ic(e),button:e.button}}function Ic(e){return{...h(e),...ai(e.target),...ci(e),...si(e),verify:e.verify,...Bc(e)}}function Lc(e){return{...h(e),...ai(e.target),...ci(e),text:e.text,delayMs:e.delayMs,recordAs:e.recordAs,textStdin:e.textStdin,verify:e.verify,...Bc(e)}}function Rc(e){return{...h(e),...ai(e.target),...ci(e),durationMs:e.durationMs,...Bc(e)}}function zc(e){return{...h(e),...ai(e.target),...ci(e),...Bc(e)}}function Bc(e){return{settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs}}function Vc(e){return{...h(e),...oi(e.target),...ci(e),format:e.format,record:e.record}}async function Hc(e){let{serializeDevice:t}=await import(`./result-serialization.js`).then(e=>e.t);return{data:{devices:e.map(t)},text:e.map(nl).join(`
21
- `)}}async function Uc(e){let{serializeDevice:t}=await import(`./result-serialization.js`).then(e=>e.t);return{data:{device:t(e.device),availableCommands:e.availableCommands},text:[`${nl(e.device)} supports ${e.availableCommands.length} commands:`,e.availableCommands.join(` `)].join(`
22
- `)}}function Wc(e){return{data:{apps:e.result},stderr:e.appsFilter===`all`?`Showing all apps, including system apps.
12
+ `)}function xo(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 So(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(`
13
+ `)}\n`:``}function Co(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 wo(e){return e.map(e=>JSON.stringify(e)).join(`
14
+ `)}function To(e){return Bo(e).join(`
15
+ `)}function Eo(e){return Lo(lt(e,{summarizeTextSurfaces:!0})).join(`
16
+ `)}function Do(e){return e&&e.summaryLines.length>0?`\n${e.summaryLines.join(`
17
+ `)}`:``}function Oo(e,t,n,r,i=0){let a=ko(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:Ao([...a?.reasons??[],`offscreen-nodes`])}:a||(s?{partial:!0,visibleNodeCount:n,totalNodeCount:n,reasons:[]}:null)}function ko(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 Ao(e){return[...new Set(e)]}function jo(e,t,n,r={nodes:t,filteredCount:0}){let i=[...Io(e),...Mo(e)];if(No(e)){let e=Fo(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&&fo(a)&&i.push(`Warning: possible repeated nav subtree detected.`),i}function Mo(e){let t=e.fallbackScreenshotPath;return typeof t==`string`&&t.length>0?[`Captured a screenshot of this screen automatically as visual truth: ${t}`]:[]}function No(e){return!e.snapshotQuality&&!Po(e)}function Po(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 Fo(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 Io(e){return sn(e).filter(e=>e.length>0)}function Lo(e){let t=[],n=[],r=new Map(e.map(e=>[e.node.index,e.node])),i=e=>{for(;n.length>0&&(!e||Ro(e,n.at(-1),r));)t.push(...Vo(n.pop(),`below`))};for(let r of e)i(r),t.push(r.text),t.push(...Vo(r,`above`)),r.node.hiddenContentBelow&&n.push(r);return i(),t}function Ro(e,t,n){return!zo(e.node,t.node,n)&&e.depth<=t.depth}function zo(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 Bo(e){return lt(e,{summarizeTextSurfaces:!0}).flatMap(e=>[nt(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...Vo({...e,depth:0})])}function Vo(e,t){let n=Ho(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 Ho(e){return e===`scroll-area`||e===`list`||e===`collection`||e===`table`?e:null}async function Uo(e){let{serializeSnapshotResult:t}=await import(`./result-serialization.js`).then(e=>e.n),n=t(e.raw||!Array.isArray(e.result.nodes)?e.result:{...e.result,nodes:Ta(e.result.nodes)});return{data:n,jsonData:Go(n),stderr:e.result.snapshotDiagnostics?.warning?`${e.result.snapshotDiagnostics.warning}\n`:void 0,text:vo(n,{raw:e.raw,flatten:e.interactiveOnly,scoped:typeof e.scope==`string`&&e.scope.trim().length>0,depthLimited:typeof e.depth==`number`})}}const Wo={snapshot:async({input:e,result:t})=>await Uo({result:t,raw:e.raw,interactiveOnly:e.interactiveOnly,scope:e.scope,depth:e.depth}),wait:V,alert:V};function Go(e){let{unchanged:t,...n}=e;return n}const Ko=`snapshot`,qo=Object.entries(_n).map(([e,t])=>{let n=t.knownGaps.map(e=>`known gap ${e}`);return`${e}: hittable=${t.hittable}, regular-depth=${t.regularDepth}, deep-extension=${t.deepExtension}, depth-ladder=${t.depthLadder}${n.length>0?`, ${n.join(`, `)}`:``}`}).join(`; `),Jo=L(Ko,`Capture the accessibility tree or compare it with the previous session baseline. Use the returned refs for subsequent semantic interactions and the diff option to verify UI changes.`,{interactiveOnly:N(),depth:M(),scope:A(),raw:N(),customActions:Br(`snapshotCustomActions`),observeOnly:Br(`snapshotObserveOnly`),forceFull:N(),timeoutMs:M(`Maximum wall-clock time for the snapshot command.`),noRecord:N(`Do not record this action.`),record:N(`Force-record this out-of-band observation into a repair-armed heal (mutually exclusive with noRecord). Authored replay steps are recorded automatically and never need this.`)}),Yo={allowedFlags:[`snapshotDiff`,...ta,`snapshotCustomActions`,`snapshotObserveOnly`,`snapshotForceFull`,`timeoutMs`,`record`]},Xo=(e,n)=>({..._(n),...or(n),...t(n,s),timeoutMs:n.timeoutMs}),Zo=h(d.snapshot),Qo=R({name:Ko,text:{summary:`Capture or diff the accessibility tree`,cliDetail:`Regular iOS snapshots clip overflowing elements to their visible area and omit fully outside elements. --json reports clipping counts in snapshotQualityNotes with code regular-geometry-clipped; --raw retains reported frames. --observe-only is local iOS snapshot-only: an already-ready compatible runner reads the session app without activation or foreground repair, refuses unavailable observation, and reports XCUIApplication state rather than verified foreground ownership (#2696). Regular targetActivation disclosure stays unchanged (#2682, #2694). Repeated equivalent unfiltered Android snapshots return a compact unchanged acknowledgement. Use --force-full to re-emit the tree; --json and --raw retain full output. Android Appium JSON snapshots publish a display viewport only when measurements before and after the tree agree, independent of tree extent or keyboard content resizing. On Android, JSON value carries field content rather than static labels; saved selectors and replay scripts using value= for static labels must use label= instead; a reported showing hint means value is empty, and text equal to the placeholder is preserved when hint state is unknown. For iOS raw-coordinate fallback after a no-op ref press, inspect rects with snapshot -i --json, press the rect center, then verify with diff snapshot -i or snapshot --diff. iOS backend capability contract: ${qo}.`},metadata:Jo,run:(e,t)=>e.capture.snapshot(t),cliSchema:Yo,cliReader:Xo,daemonWriter:Zo,cliOutputFormatter:Wo.snapshot}),$o=[`duration`,`text`,`ref`,`selector`,`absent`,`stable`],es=`wait`,ts={wait:S({waitedMs:E(),kind:w(`selector`),text:T(),selector:T(),captures:E(),nodeCount:E(),hint:T(),warning:T()},[`waitedMs`])},ns=R({name:es,text:{summary:`Wait for a duration, text, selector, strict absence, or stable UI`},metadata:L(es,`Wait for a duration, text, snapshot ref, selector to appear, selector to be strictly absent, or stable UI. Use the strict absence target when zero selector matches are required; stable waits until the UI stays quiet for the requested window.`,{kind:P($o),durationMs:M(),text:A(),ref:A(),selector:A(),absent:A(),stable:N(),quietMs:M(),timeoutMs:M(),depth:M(),scope:A(),raw:N()}),run:(e,t)=>e.command.wait(rs(t)),cliSchema:{usageOverride:`wait <ms>|text <text>|@ref|<selector>|absent <selector> [timeoutMs]|stable [quietMs] [timeoutMs]`,usageFlags:[],positionalArgs:[`durationOrSelector`,`timeoutMs?`],allowsExtraPositionals:!0,allowedFlags:[...U]},cliReader:(e,t)=>is(e,t),daemonWriter:h(d.wait,e=>ss(e)),cliOutputFormatter:V});function rs(e){Un(e,`kind`,$o);let t={...e};return delete t.kind,t}function is(e,t){let r=Et(e);if(!r)throw new n(`INVALID_ARGS`,`wait requires <ms>, text <text>, @ref, <selector> [timeoutMs], absent <selector> [timeoutMs], or stable [quietMs] [timeoutMs].`);let i={...sr(t),...lr(t)};switch(r.kind){case`absent`:return as(i,r);case`sleep`:return{...i,durationMs:r.durationMs};case`text`:return os(i,r);case`ref`:return{...i,ref:r.rawRef,...cs(r.timeoutMs)};case`stable`:return{...i,stable:!0,...ls(r.quietMs),...cs(r.timeoutMs)};case`invalid`:throw new n(`INVALID_ARGS`,r.message);case`selector`:return{...i,selector:r.selectorExpression,...cs(r.timeoutMs)};default:return us(r)}}function as(e,t){let n=tt(e);if(n)throw yn(n,`wait`);return{...e,absent:t.selectorExpression,...cs(t.timeoutMs)}}function os(e,t){if(!t.text)throw new n(`INVALID_ARGS`,`wait requires text.`);return{...e,text:t.text,...cs(t.timeoutMs)}}function ss(e){if([e.durationMs===void 0?void 0:`durationMs`,e.text===void 0?void 0:`text`,e.ref===void 0?void 0:`ref`,e.selector===void 0?void 0:`selector`,e.absent===void 0?void 0:`absent`,e.stable===void 0?void 0:`stable`].filter(Boolean).length!==1)throw new n(`INVALID_ARGS`,`wait command requires exactly one of durationMs, text, ref, selector, absent, or stable.`);if(e.durationMs!==void 0)return[String(e.durationMs)];let t=y(e.timeoutMs);if(e.text!==void 0)return[`text`,e.text,...t];if(e.ref!==void 0)return[e.ref,...t];if(e.absent!==void 0){let r=tt(e);if(r)throw yn(r,`wait`);if(!St(e.absent))throw new n(`INVALID_ARGS`,`Invalid wait absent selector: ${e.absent}`);return[`absent`,e.absent,...t]}if(e.stable!==void 0){let r=y(e.quietMs);if(r.length===0&&t.length>0)throw new n(`INVALID_ARGS`,`wait stable requires quietMs before timeoutMs.`);return[`stable`,...r,...t]}let r=e.selector;if(!St(r))throw new n(`INVALID_ARGS`,`Invalid wait selector: ${r}`);return[r,...t]}function cs(e){return e===null?{}:{timeoutMs:e}}function ls(e){return e===null?{}:{quietMs:e}}function us(e){throw Error(`Unsupported wait positional target: ${String(e)}`)}const ds=z({name:`capture`,commands:[Qo,ha,pa,ns,Xi,Sa]});function fs(e){let t=[e.outPath,e.message];t.push(...ms(e));for(let n of e.matchedImages)t.push(`Matched: ${n.name} ${n.uuid}${n.arch?` ${n.arch}`:``}`);for(let n of e.warnings??[])t.push(`Warning: ${n}`);return{data:e,text:t.join(`
18
+ `)}}const ps={debug:B(fs)};function ms(e){let t=e.crash,n=[`Crash: ${t.appName??`unknown app`}${t.crashedThread===void 0?``:` thread ${t.crashedThread}`}`];t.bundleId&&n.push(`Bundle: ${t.bundleId}`),t.exceptionType&&n.push(`Exception: ${t.exceptionType}`),t.terminationReason&&n.push(`Termination: ${t.terminationReason}`);for(let e of t.topFrames)n.push(`Frame ${e.index}: ${e.image} ${e.symbol??e.address}`);for(let e of t.findings)n.push(`Finding: ${e}`);return n}const hs=`debug`,gs=z({name:`debugging`,commands:[R({name:hs,text:{summary:`Symbolicate Apple crash artifacts`},metadata:L(hs,`Symbolicate Apple crash artifacts with matching dSYM UUIDs. This debug namespace is intentionally narrow: use logs for app logs, network for HTTP evidence, perf for performance samples, record/trace for media and traces, and react-devtools for React Native components and render profiles.`,{action:k(P([`symbols`])),artifact:k(A(`Apple crash artifact path (.ips, .crash, or .log).`)),dsym:A(`Path to a matching .dSYM bundle.`),searchPath:A(`Directory to scan for matching .dSYM bundles.`),out:A(`Output path for the symbolicated artifact.`)}),run:(e,t)=>e.debug.symbols(t),cliSchema:{usageOverride:`debug symbols --artifact <crash.ips|crash.log> (--dsym <App.dSYM> | --search-path <dir>) [--out <symbolicated>]`,usageFlags:[],listUsageOverride:`debug`,positionalArgs:[`symbols`],allowedFlags:[`artifact`,`dsym`,`searchPath`,`out`]},cliReader:(e,t)=>({..._(t),action:_s(e[0]),artifact:t.artifact,dsym:t.dsym,searchPath:t.searchPath,out:t.out}),cliOutputFormatter:ps.debug})]});function _s(e){if(e===`symbols`)return e;throw new n(`INVALID_ARGS`,`debug supports only symbols; use logs, network, perf, record, trace, or react-devtools for other diagnostics`)}const vs=()=>N(`Capture cheap post-action evidence (AX digest, node counts, changedFromBefore) instead of a follow-up snapshot.`),ys=()=>({settle:N(`After the action, wait for the UI to go quiet and return the settled diff vs the pre-action tree in the same response. Best-effort; never fails the action.`),settleQuietMs:M(`Settle: quiet window in milliseconds (default 500; 300 when the settled tree comes from the iOS simulator snapshot bridge). On iOS, a broad screen replacement such as a modal dismissal is confirmed for at least 1500ms whatever window is asked for, within the timeoutMs settle deadline; a replacement from a screen the pre-action capture read as presenting nothing, such as a tab switch, gets no 1500ms confirmation and keeps the asked window.`,{min:0}),timeoutMs:M(`Settle: wait deadline in milliseconds (default 10000).`,{min:1})});function bs(e){return{...Ft(e)?{verify:vs()}:{},...It(e)?ys():{}}}function xs(e){let t=[];return Ft(e)&&t.push(`verify`),It(e)&&t.push(...oa),t}function Ss(e,t){return It(e)?ur(t):{}}const Cs=[`click`,`focus`,`exists`,`list`,`getText`,`getAttrs`,`wait`,`fill`,`type`],ws={click:`Activate a UI target by snapshot ref, selector, or coordinates. Prefer a ref or selector after a snapshot; use coordinates only when semantic targeting is unavailable. This can change app state. Success means the click was dispatched, not that it landed: use settle or verify to confirm the result without a follow-up snapshot, or wait for the expected screen. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was.`,press:`Short-press a UI target by snapshot ref, selector, or coordinates. Use longpress instead when the target requires a context-menu or hold gesture. Success means the press was dispatched, not that it landed: use settle or verify to confirm the result, or wait for the expected screen. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was.`,fill:`Replace text in a UI input selected by snapshot ref, selector, or coordinates. Pass an empty text to clear the field. Inspect unconfirmed evidence and assert the expected value or resulting screen before continuing. Prefer refs or selectors after snapshot; use recordAs to keep sensitive text out of a recorded replay while sending it to the live app.`,longpress:`Hold a UI target by snapshot ref, selector, or coordinates to open a context menu or perform another hold gesture. Set durationMs when the default hold duration is unsuitable.`,hover:`Move the pointer over a UI target by snapshot ref, selector, or coordinates without pressing, to reveal hover-gated UI such as row toolbars or menus. Web only; touch platforms have no hover state. Use settle to observe what the hover revealed without a follow-up snapshot.`,swipe:`Quick coordinate fling with optional repeat pattern.`,focus:`Move input focus to explicit screen coordinates without entering text. Prefer semantic interactions when a snapshot ref or selector is available; use type or fill after focus.`,type:`Append text to the currently focused input. Use fill when the existing field value should be replaced, and focus first when no input is active.`,scroll:`Scroll in a direction, or toward the top/bottom edge of scrollable content. Set until to a selector to reach an off-screen target in one command rather than a scroll-and-check loop. The optional amount is the finger-path fraction of the viewport axis, honored up to 0.8 of it; directional scrolls reduce release momentum, while app scroll physics determine the final content offset. A visible keyboard shortens the swiped band instead of being dismissed; when too little is left, the command refuses with scroll_keyboard_occludes_surface. A directional scroll also reports the movement it observed as movement: moved, at-edge, unchanged, or unobserved when the two reads could not back a claim either way; an unchanged surface inside a container that still hides content in that direction refuses with scroll_no_progress rather than repeating the requested distance. The movement field is absent where a tier verifies per pass (top/bottom, until), where the runtime cannot read a screen, or where a settle observation or a replay already owns that observation.`,get:`Read text or accessibility attributes from a snapshot ref or selector without changing the app. Use format text for visible content or attrs for the element attribute map.`,is:"Check whether a selector satisfies a UI predicate such as visible, hidden, exists, absent, editable, selected, focused, or text. `absent` passes only when one readable, complete, settled, unscoped, full-depth accessibility capture has zero matches. Use wait when the condition may appear asynchronously.",find:`Find by text/label/value/role/id and run action. The role locator matches snapshot kind vocabulary (button, text, text-field, switch, ...); pre-reconciliation leaf spellings (statictext, edittext, textview) stay accepted on the nodes that carried them during a deprecation window.`,gesture:`Perform a structured pan, fling, swipe, pinch, rotate, transform, tap, or drag gesture. Select the gesture kind, then provide only the inputs that apply to that kind. A tap touches 2 to 5 points at once; repeat it with count and pauseMs.`},Ts={target:k(qr()),button:P(st,`Pointer button for platforms that support mouse buttons.`),...Qr(),...$r(),...bs(`click`)},Es={target:k(qr()),...Qr(),...$r(),...bs(`press`)},Ds={target:k(qr()),text:k(A(`Text to enter into the target. Pass "" to clear it.`,{allowEmpty:!0})),delayMs:M(`Delay between typed characters.`,{min:0}),recordAs:A("When script recording is armed, send text to the live app but publish it as ${VAR}. Use an uppercase replay variable name such as PASSWORD."),textStdin:zr(N(`Operator-only: text was read from the CLI's stdin, so it is kept out of diagnostics and recorded actions.`),{operatorPath:`Pass --text-stdin on the CLI and pipe the text in; it is not exposed to model-facing tools.`}),...Qr(),...bs(`fill`)},Os={target:k(qr()),durationMs:M(`Long press duration in milliseconds.`,{min:0}),...Qr(),...bs(`longpress`)},ks={target:k(qr()),...Qr(),...bs(`hover`)},As={from:k(Yr(`Swipe start point.`)),to:k(Yr(`Swipe end point.`)),count:M(`Number of swipe repetitions.`,{min:1,max:200}),pauseMs:M(`Pause between repeated swipes.`,{min:0,max:Ee}),pattern:P(_e)},js={x:k(j(`X coordinate.`)),y:k(j(`Y coordinate.`))},Ms={text:k(A(`Text to type.`)),delayMs:M(`Delay between typed characters.`,{min:0})},Ns={direction:k(P(ke)),amount:j(`Platform scroll amount.`),pixels:M(`Pixel scroll amount.`,{min:0}),until:A(`Repeat scroll passes until this selector is visible on screen, then stop. Not valid with the top/bottom edge directions, which carry their own stop condition.`),maxPasses:M(`Maximum scroll gestures for an until search (default 12). Requires until.`,{min:1,max:200}),durationMs:M(`Scroll duration in milliseconds when the backend supports pacing.`,{min:0,max:oe}),...bs(`scroll`)},Ps=()=>({noRecord:N(`Do not record this action.`),record:N(`Force-record this out-of-band observation into a repair-armed heal (mutually exclusive with noRecord). Authored replay steps are recorded automatically and never need this. On find, valid only for a read-only action.`)}),Fs={format:k(P([`text`,`attrs`])),target:k(Jr()),...Qr(),...Ps()},Is={predicate:k(P(zt)),selector:k(A()),value:A(),...Qr(),...Ps()},Ls={locator:P(Tt),query:k(A()),action:P(Cs),value:A(void 0,{allowEmpty:!0}),timeoutMs:M(),first:N(),last:N(),depth:M(),raw:N(),...Ps()},Rs={kind:k(P(ct,`Gesture variant.`)),direction:P(Te,`Fling direction.`),preset:P(Ae,`Swipe preset.`),origin:Yr(`Gesture origin point.`),delta:Yr(`Movement delta for pan or transform gestures.`),distance:M(`Fling distance.`,{min:0}),scale:j(`Pinch or transform scale.`),degrees:j(`Rotation in degrees.`),durationMs:M(`Pan/transform duration.`,{min:16,max:1e4}),pointerCount:M(`Pan touch pointer count (1 or 2).`,{min:1,max:2}),points:Xr(`Tap contact points, held together for holdMs.`,{min:2,max:5}),holdMs:M(`Tap contact hold duration.`,{min:16,max:l}),count:M(`Tap repetitions; the same contacts run this many times.`,{min:1,max:200}),pauseMs:M(`Delay between tap repetitions, added to each repetition’s own time.`,{min:0,max:Ee}),source:A(`Drag source @ref or selector.`),destination:A(`Drag destination @ref or selector.`),sourceHoldMs:M(`Drag activation hold duration.`,{min:1,max:1e4}),moveMs:M(`Drag movement duration.`,{min:16,max:1e4}),destinationHoldMs:M(`Hold before releasing at the destination.`,{min:0,max:1e4})},zs=[G(`click`,Ts),G(`press`,Es),G(`fill`,Ds),G(`longpress`,Os),G(`hover`,ks),G(`swipe`,As),G(`focus`,js),G(`type`,Ms),G(`scroll`,Ns),G(`get`,Fs,{parseableOutput:!0}),G(`is`,Is),G(`find`,Ls,{parseableOutput:!0}),L(`gesture`,ws.gesture,Rs,{readInput:Bs})];function Bs(e){let t=In(e);return{...er(t),...ut(t)}}function G(e,t,n){return L(e,ws[e],t,n)}const Vs={gesture:Us},Hs={gesture:e=>{let t=Bs(e);return g(d.gesture,[],e,m(t))}};function Us(e,t){return{..._(t),...ft(e,{pointerCount:t.pointerCount,holdMs:t.holdMs,count:t.count,pauseMs:t.pauseMs})}}const K={click:(e,t)=>({..._(t),...cr(t),...dr(t),target:pr(bn(e)),button:t.clickButton,verify:t.verify}),press:(e,t)=>({..._(t),...cr(t),...dr(t),target:pr(bn(e)),verify:t.verify}),longpress:(e,t)=>{let n=Gs(e);return{..._(t),...cr(t),target:pr(n),durationMs:n.durationMs}},hover:(e,t)=>({..._(t),...cr(t),target:pr(bn(e))}),swipe:(e,t)=>({..._(t),...$e(e,{count:t.count,pauseMs:t.pauseMs,pattern:t.pattern})}),focus:(e,t)=>({..._(t),x:Number(e[0]),y:Number(e[1])}),type:(e,t)=>({..._(t),text:e.join(` `),delayMs:t.delayMs}),fill:(e,t)=>{let n=t.textStdin?Ws(e):xn(e);return{..._(t),...cr(t),target:pr(n.target),text:n.text,delayMs:t.delayMs,recordAs:t.recordAs,textStdin:t.textStdin,verify:t.verify}},scroll:(e,t)=>({..._(t),direction:Ys(e[0]),amount:Er(e[1]),pixels:t.pixels,durationMs:t.durationMs,until:t.until,maxPasses:t.maxPasses}),get:(e,t)=>({..._(t),...or(t),...cr(t),format:br(e[0]),target:pr(yr(e.slice(1)))})},q={click:e=>g(d.click,mr(e),{...e,clickButton:e.button}),press:h(d.press,e=>mr(e)),longpress:h(d.longPress,e=>Ks(e)),hover:h(d.hover,e=>mr(e)),swipe:e=>(Je(e),g(d.swipe,[],e,{from:e.from,to:e.to,count:e.count,pauseMs:e.pauseMs,pattern:e.pattern})),focus:h(d.focus,e=>[String(e.x),String(e.y)]),type:h(d.type,e=>qs(e)),fill:h(d.fill,e=>Js(e)),scroll:h(d.scroll,e=>[x(e.direction,`scroll requires direction`),...y(e.amount)]),get:h(d.get,e=>[x(e.format,`get requires format`),...hr(e)])};function Ws(e){let t;try{t=xn(e)}catch(e){throw e instanceof n?new n(`INVALID_ARGS`,`fill --text-stdin could not read the target.`,{reason:`fill_text_stdin_target_invalid`,hint:`Pass only the target: an @ref, a quoted selector, or x y coordinates. The text itself goes to stdin.`}):e}if(t.text!==void 0)throw new n(`INVALID_ARGS`,`fill --text-stdin reads the text from stdin, so it cannot also take a text argument.`,{reason:`fill_text_source_conflict`,hint:`Pass only the target, for example: printf %s "$PASSWORD" | agent-device fill @e3 --text-stdin. Quote a multi-word selector so no part of it is read as text.`});return t}function Gs(e){let t=Xs(e);return{...bn(t.target),...t.durationMs===void 0?{}:{durationMs:t.durationMs}}}function Ks(e){return[...mr(e),...y(e.durationMs)]}function qs(e){return[e.text]}function Js(e){return[...mr(e),e.text]}function Ys(e){if(e===`up`||e===`down`||e===`left`||e===`right`||e===`top`||e===`bottom`)return e;throw new n(`INVALID_ARGS`,`Unknown direction: ${String(e)}`,{hint:`scroll takes a direction first, then an optional amount: scroll <up|down|left|right|top|bottom> [amount]. It takes no @ref or selector — scroll the whole viewport, then retry the target with a selector.`})}function Xs(e){if(wr(e[0])&&wr(e[1]))return{target:e.slice(0,2),...e[2]===void 0?{}:{durationMs:Number(e[2])}};let t=e.at(-1);return e.length>1&&wr(t)?{target:e.slice(0,-1),durationMs:Number(t)}:{target:e}}function Zs(e){return t=>{let n=e(t);return n instanceof Promise?n.then(Qs):Qs(n)}}function Qs(e){return{data:e.data,text:ec(e.text,e.data)}}function $s(e){let t={...e};for(let[n,r]of Object.entries(e))It(n)&&(t[n]=Zs(r));return t}function ec(e,t){return`${e??``}${tc(t.settle)}`}function tc(e){if(!e||typeof e!=`object`)return``;let t=e,n=[ac(t),...nc(t),...ic(t)];return t.hint&&n.push(`hint: ${t.hint}`),`\n${n.join(`
19
+ `)}`}function nc(e){let t=e.diff,n=(t?.lines??[]).map(t=>`${t.kind===`removed`?`-`:`+`} ${rc(t,e.refsGeneration)}`);return t?.truncated&&n.push(`… changed lines truncated`),n}function rc(e,t){let n=e.text??``,r=Ti(e.ref,t);if(!r||!e.ref)return n;let i=`@${e.ref}`;return n.startsWith(`${i} `)?`${r}${n.slice(i.length)}`:`${r} ${n}`}function ic(e){let t=e.tail??[];if(t.length===0)return[];let n=[`unchanged interactive (${t.length}):`];for(let r of t){let t=r.label?` "${r.label}"`:``,i=Ti(r.ref,e.refsGeneration)??`@${r.ref??``}`;n.push(`= ${i} [${r.role??``}]${t}`)}return e.tailTruncated&&n.push(`… more interactive elements not shown, use snapshot -i`),n}function ac(e){let t=e.settled===!0?`settled`:`not settled`,n=e.diff?.summary;return n?`${t} after ${e.waitedMs??0}ms: +${n.additions??0} -${n.removals??0} (~${n.unchanged??0} unchanged)`:`${t} after ${e.waitedMs??0}ms`}function oc(e){let t=e.result;return e.format===`attrs`?{data:t,text:JSON.stringify(t.node??{},null,2)}:{data:t,text:typeof t.text==`string`?t.text:``}}function sc(e){let t=e,n=cn(t);if(n)return{data:t,text:n};if(typeof t.text==`string`)return{data:t,text:t.text};if(Array.isArray(t.matches))return{data:t,text:cc(t.matches,t.refsGeneration)};let r=Ti(t.ref,t.refsGeneration);return r?{data:t,text:`Found: ${r}`}:typeof t.found==`boolean`?{data:t,text:`Found: ${t.found}`}:t.node?{data:t,text:JSON.stringify(t.node,null,2)}:bi(t)}function cc(e,t){return[`${e.length} match${e.length===1?``:`es`}:`,...e.map(e=>lc(e,t))].join(`
20
+ `)}function lc(e,t){let n=e.ref===void 0?`(no ref)`:Ti(e.ref,t)??e.ref,r=c(e.node?.type??`Element`),i=e.node?ot(e.node,r):``;return`= ${n} [${r}]${i?` "${i}"`:``}`}function uc(e){let t=e;return{data:t,text:`Passed: is ${t.predicate??`assertion`}`}}function dc(e){let t=e,n=t.ref??``,r=t.x,i=t.y;return!n||typeof r!=`number`||typeof i!=`number`?bi(t):{data:t,text:`Tapped @${n} (${r}, ${i})`}}const J=$s({click:B(dc),press:B(dc),fill:V,longpress:V,hover:V,scroll:V,get:({input:e,result:t})=>oc({result:t,format:e.format===`attrs`?`attrs`:`text`}),is:B(uc),find:B(sc)}),fc={find:(e,t)=>gc(e,t),is:(e,t)=>_c(e,t)},pc={is:h(d.is,e=>mc(e)),find:e=>g(d.find,hc(e),{...e,findFirst:e.first,findLast:e.last})};function mc(e){return[e.predicate,e.selector,...e.predicate===`text`?[e.value]:[]]}function hc(e){let t=e.locator&&e.locator!==`any`?[e.locator,e.query]:[e.query];switch(e.action){case void 0:case`click`:case`focus`:case`exists`:case`list`:return e.action?[...t,e.action]:t;case`getText`:return[...t,`get`,`text`];case`getAttrs`:return[...t,`get`,`attrs`];case`wait`:return[...t,`wait`,...y(e.timeoutMs)];case`fill`:case`type`:return[...t,e.action,e.value]}}function gc(e,t){let r={...xc(t),...sr(t),...or(t),first:t.findFirst,last:t.findLast},i=bc(e[0]),a=i!==void 0,o=a?e[1]:e[0],s=a?2:1,c=At(e[s]);if(c===void 0)return{...r,locator:i,query:Sc(o)};if(c===`get`){let t=e[s+1];if(t===`text`)return{...r,locator:i,query:Sc(o),action:`getText`};if(t===`attrs`)return{...r,locator:i,query:Sc(o),action:`getAttrs`};throw new n(`INVALID_ARGS`,`find get only supports text or attrs`)}if(c===`wait`)return{...r,locator:i,query:Sc(o),action:`wait`,timeoutMs:Er(e[s+1])};if(c===`fill`||c===`type`){let t=e.slice(s+1);if(t.length===0)throw new n(`INVALID_ARGS`,c===`fill`?`find fill requires text (use "" to clear the field)`:`find type requires text`);return{...r,locator:i,query:Sc(o),action:c,value:t.join(` `)}}if(c===`click`||c===`focus`||c===`exists`||c===`list`)return{...r,locator:i,query:Sc(o),action:c};throw new n(`INVALID_ARGS`,`Unsupported find action: ${e[s]}`,{hint:Ot})}function _c(e,t){let r={...lr(t),...sr(t),...or(t)},i=wt(e),a=Dt(i[0]??``);if(!a.ok)throw new n(a.code,a.message,{hint:a.hint});let o=a.predicate;if(o===`absent`){let e=vc(r);if(e)throw yc(e)}let s=xr(i.slice(1),{preferTrailingValue:o===`text`});return o===`text`?{...r,predicate:o,selector:s.selectorExpression,value:s.rest.join(` `)}:{...r,predicate:o,selector:s.selectorExpression}}function vc(e){if(e.scope!==void 0)return`scope`;if(e.depth!==void 0)return`depth`}function yc(e){return new n(`INVALID_ARGS`,e===`scope`?`is absent does not support --scope; it requires an unscoped capture`:`is absent does not support --depth; it requires a full-depth capture`,{command:`is`,predicate:`absent`,rejectedOption:e})}function bc(e){if(e===`text`||e===`label`||e===`value`||e===`role`||e===`id`)return e}function xc(e){return{depth:e.snapshotDepth,raw:e.snapshotRaw}}function Sc(e){if(e===void 0||e===``)throw new n(`INVALID_ARGS`,`find requires query`);return e}const Cc=S({from:T(`Surface the pre-action baseline described: a host bundle id, or app.`),to:T(`Surface the post-action capture describes: a host bundle id, or app.`),disclosure:T(`Agent-facing sentence explaining the surface transition.`)},[`from`,`to`,`disclosure`],`Present when an in-place system surface (web sign-in or Apple Pay sheet) was presented over the app, or left it.`),wc=S({foregroundApp:T(`Foreground app bundle id or name, when the capture carries it.`),nodeCount:E(`Node count in the post-action interactive-only capture.`),interactiveNodeCount:E(`Subset of nodeCount the platform reports as hittable.`),digest:T(`Order-independent digest of the post-action node multiset.`),changedFromBefore:D(`Whether the post-action digest differs from the pre-action capture digest. false is evidence, not failure. With surfaceChange present, no digest comparison is made: it reports that surface transition.`),surfaceChange:Cc},[`nodeCount`,`interactiveNodeCount`,`digest`,`changedFromBefore`]),Tc=S({wallClockMs:E(`Total wall-clock time for the request in milliseconds.`),runnerRoundTrips:E(`Number of real runner round-trips made while serving the request.`),nodeCount:E(`Number of nodes in the original node tree when the response carries one.`)},[`wallClockMs`,`runnerRoundTrips`]),Ec=S({diagnosticRef:T(`Opaque non-@ diagnostic token. Never a snapshot ref: not issued via refsGeneration and cannot be pinned or reused as an @ref target. UTF-8 truncated to 256 bytes.`),role:T(`UTF-8 truncated to 256 bytes.`),label:T(`UTF-8 truncated to 256 bytes.`)},[`diagnosticRef`]),Dc={type:`object`,description:`Pre-action disclosure of how the acting path resolved its target. Absent when resolutionDisclosure is inapplicable for the path.`,oneOf:[S({source:w(`runtime`),phase:w(`pre-action`),kind:w(`unique`)},[`source`,`phase`,`kind`]),S({source:w(`runtime`),phase:w(`pre-action`),kind:w(`disambiguated`),matchCount:E(`Total matches resolveSelectorChain found before disambiguation.`),winnerDiagnostic:Ec,tiebreak:C([`visible`,`deepest`,`smallest-area`,`structural-equivalence`],`The comparison that decided the winner.`),alternatives:{type:`array`,description:`At most 5 losing candidates, document order. Present at default/full response levels and omitted in digest. The winner is never included.`,items:Ec}},[`source`,`phase`,`kind`,`matchCount`,`winnerDiagnostic`,`tiebreak`]),S({source:w(`ref`),phase:w(`pre-action`),kind:w(`exact`)},[`source`,`phase`,`kind`]),S({source:w(`ref`),phase:w(`pre-action`),kind:w(`label-fallback`)},[`source`,`phase`,`kind`]),S({source:w(`direct-ios`),kind:w(`not-observed`)},[`source`,`kind`])]};function Oc(e={}){let t=e.properties??{},n=e.required??[];return S({targetKind:C([`point`,`ref`,`selector`],`Resolved interaction target kind.`),x:E(`Resolved interaction x coordinate when available.`),y:E(`Resolved interaction y coordinate when available.`),referenceWidth:E(`Reference frame width for visualizing the interaction point.`),referenceHeight:E(`Reference frame height for visualizing the interaction point.`),ref:T(`Snapshot ref without the @ prefix when the target was an @ref.`),selector:T(`Selector expression when the target was a selector.`),selectorChain:Lr(),refLabel:T(),targetHittable:D(),hint:T(),warning:T(),message:T(),evidence:wc,resolution:Dc,cost:Tc,maestroNonHittableCoordinateFallbackAllowed:D(`Whether the direct iOS Maestro coordinate fallback was allowed for this selector.`),maestroNonHittableCoordinateFallbackUsed:D(`Whether the direct iOS Maestro coordinate fallback was actually used.`),maestroFallbackReason:w(`non-hittable-coordinate`),...t},[`targetKind`,...n])}const kc=Oc({properties:{evidence:wc,button:C([`secondary`,`middle`]),count:E(`Number of press/click repetitions.`),intervalMs:E(`Delay between repeated press/click actions.`),holdMs:E(`Hold duration for each action.`),jitterPx:E(`Deterministic per-axis coordinate jitter in pixels (each press offsets x and y by up to this amount).`),doubleTap:D(`Whether the command requested a double-tap action.`)}}),Ac={text:T(`Text submitted to the field.`),delayMs:E(`Delay between typed characters in milliseconds.`),evidence:wc},jc=S({resourceId:Fr(`Identifier of the exact field that changed: Android resource id or Apple accessibility identifier.`),className:Fr(`Type of the exact field that changed: Android class name or Apple element type.`),packageName:Fr(`App that owns the exact field: Android package name or Apple bundle id.`),rect:S({x:E(),y:E(),width:E(),height:E()},[`x`,`y`,`width`,`height`],`Screen-space rectangle of the exact field that changed.`)},[`resourceId`,`className`,`packageName`,`rect`],`Target identity captured before fill and matched after fill.`),Mc={press:kc,click:kc,fill:{type:`object`,description:`Fill response. Target-bound unconfirmed evidence reports an observed value different from the requested text. It does not establish that formatting preserved the input; assert the expected value or resulting screen before continuing.`,oneOf:[{...Oc({properties:Ac,required:[`text`]}),not:S({},[`verification`])},Oc({properties:{...Ac,verification:w(`unconfirmed`),requested:T(`Literal text requested by the fill command.`),before:Fr(`Raw target text captured before the fill.`),after:Fr(`Raw target text captured after the fill.`),target:jc},required:[`text`,`verification`,`requested`,`before`,`after`,`target`]})]},longpress:Oc({properties:{durationMs:E(),gesture:w(`longpress`)}}),hover:Oc({properties:{gesture:w(`hover`)}}),find:S({ref:T(`Snapshot ref without the @ prefix when the find action returns one.`),refsGeneration:E(`ADR 0014 ref frame epoch for read-only find actions.`),found:D(`Whether a wait/exists/read-only find satisfied its condition.`),waitedMs:E(`Milliseconds waited for a read-only find condition.`),text:T(`Text value returned by find get_text.`),node:O(`Snapshot node for find get_attrs/get_text.`),matches:{type:`array`,description:`Every match for the read-only find list action (#1625): { ref, node } each.`,items:O(`One listed match with its snapshot ref and node.`)},locator:T(`Locator kind used for the find action.`),query:T(`Query argument used for the find action.`),x:E(`Resolved x coordinate for mutating find actions.`),y:E(`Resolved y coordinate for mutating find actions.`),message:T(`Diagnostic message for mutating find actions.`),cost:Tc},[],`Daemon response data for the find command.`)},Nc=Ze,Pc=[...new Set(Object.values(Nc).flat())],Y={get:{usageOverride:`get text|attrs <@ref|selector>`,usageFlags:[],positionalArgs:[`subcommand`,`target`],allowsExtraPositionals:!0,allowedFlags:[...U,`record`]},find:{usageOverride:`find <locator|text> <action> [value] [--first|--last]`,usageFlags:[],positionalArgs:[`query`,`action`,`value?`],allowsExtraPositionals:!0,allowedFlags:[`snapshotDepth`,`snapshotRaw`,`findFirst`,`findLast`,`record`]},is:{positionalArgs:[`predicate`,`selector`,`value?`],allowsExtraPositionals:!0,allowedFlags:[...U,`record`]},click:{usageOverride:`click <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`target`],allowsExtraPositionals:!0,allowedFlags:[...aa,`clickButton`,...xs(`click`),...U]},press:{usageOverride:`press <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...aa,...xs(`press`),...U]},longpress:{usageOverride:`longpress <x y|@ref|selector> [durationMs]`,usageFlags:[],positionalArgs:[`targetOrX`,`yOrDurationMs?`,`durationMs?`],allowsExtraPositionals:!0,allowedFlags:[...xs(`longpress`),...U]},hover:{usageOverride:`hover <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...xs(`hover`),...U]},swipe:{positionalArgs:[`x1`,`y1`,`x2`,`y2`],allowsExtraPositionals:!0,allowedFlags:[`count`,`pauseMs`,`pattern`]},gesture:{usageOverride:`gesture <pan|fling|swipe|pinch|rotate|transform|tap|drag> ...`,usageFlags:[],listUsageOverride:`gesture <pan|fling|swipe|pinch|rotate|transform|tap|drag> ...`,positionalArgs:[`pan|fling|swipe|pinch|rotate|transform|tap|drag`,`args?`],allowsExtraPositionals:!0,allowedFlags:Pc,flagsByAction:Nc},focus:{positionalArgs:[`x`,`y`]},type:{positionalArgs:[`text`],allowsExtraPositionals:!0,allowedFlags:[`delayMs`]},fill:{usageOverride:`fill <x> <y> <text> | fill <@ref|selector> <text> | fill <x y|@ref|selector> --text-stdin`,usageFlags:[],positionalArgs:[`targetOrX`,`yOrText`,`text?`],allowsExtraPositionals:!0,allowedFlags:[...U,`delayMs`,`recordAs`,`textStdin`,...xs(`fill`)]},scroll:{usageOverride:`scroll <direction|top|bottom> [amount]`,usageFlags:[`until`,`maxPasses`,`pixels`,`durationMs`,`settle`],positionalArgs:[`directionOrEdge`,`amount?`],allowedFlags:[`pixels`,`durationMs`,`until`,`maxPasses`,...xs(`scroll`)]}},Fc=z({name:`interaction`,clientSurface:!1,commands:[R({name:`click`,text:{summary:`Click or tap a UI target`},metadata:X(`click`),run:(e,t)=>e.interactions.click(Ic(t)),cliSchema:Y.click,cliReader:K.click,daemonWriter:q.click,cliOutputFormatter:J.click}),R({name:`press`,text:{summary:`Short-press a UI target`,cliDetail:`The hold duration is positional on longpress, not press --hold-ms.`},metadata:X(`press`),run:(e,t)=>e.interactions.press(Lc(t)),cliSchema:Y.press,cliReader:K.press,daemonWriter:q.press,cliOutputFormatter:J.press}),R({name:`fill`,text:{summary:`Replace text in a UI input`,cliDetail:`Every positional after an @ref is the replacement text, so fill @e57 good morning enters "good morning"; quote the text when the shell must preserve exact whitespace. Clear a field with an empty text argument: fill @e57 "" (the argument must be present — fill @e57 alone is a missing argument, not a clear). When visible label text also matches a non-input element, constrain the target with editable=true, for example fill 'label="Email" editable=true' "qa@example.com". To keep a secret out of argv, omit the text and pipe it in: printf %s "$PASSWORD" | fill @e57 --text-stdin (max 64 KiB, one trailing newline removed). On web, a coordinate fill selects the clicked field in the page and refuses with COMMAND_FAILED and details.reason text_entry_focus_not_observed, before it sends any text or key, when the click did not reach an editable text field it can reach: a read-only, disabled, date, checkbox, or select control, a field in a cross-origin frame, a sandboxed frame without allow-same-origin, or a closed shadow root, or a click that missed. The click has already landed, so run snapshot -i again and fill the field it reports by ref (fill @e2 text); a selector fill reaches the same coordinate path and hits the same limits.`},metadata:X(`fill`),run:(e,t)=>e.interactions.fill(Rc(t)),cliSchema:Y.fill,cliReader:K.fill,daemonWriter:q.fill,cliOutputFormatter:J.fill}),R({name:`longpress`,text:{summary:`Hold a UI target to open a context menu`,cliDetail:`Duration is positional, for example longpress @e12 800 or longpress 300 500 800.`},metadata:X(`longpress`),run:(e,t)=>e.interactions.longPress(zc(t)),cliSchema:Y.longpress,cliReader:K.longpress,daemonWriter:q.longpress,cliOutputFormatter:J.longpress}),R({name:`hover`,text:{summary:`Hover the pointer over a UI target (web only)`,cliDetail:`The pointer stays where hover left it: read the revealed UI (--settle or snapshot -i) and act on it before another click or hover moves the pointer away.`},metadata:X(`hover`),run:(e,t)=>e.interactions.hover(Bc(t)),cliSchema:Y.hover,cliReader:K.hover,daemonWriter:q.hover,cliOutputFormatter:J.hover}),R({name:`swipe`,text:{summary:`Fling between coordinates`},metadata:X(`swipe`),run:(e,t)=>e.interactions.swipe(t),cliSchema:Y.swipe,cliReader:K.swipe,daemonWriter:q.swipe}),R({name:`focus`,text:{summary:`Focus input at screen coordinates`},metadata:X(`focus`),run:(e,t)=>e.interactions.focus(t),cliSchema:Y.focus,cliReader:K.focus,daemonWriter:q.focus}),R({name:`type`,text:{summary:`Append text to the focused input`},metadata:X(`type`),run:(e,t)=>e.interactions.type(t),cliSchema:Y.type,cliReader:K.type,daemonWriter:q.type}),R({name:`scroll`,text:{summary:`Scroll in a direction or to an edge`},metadata:X(`scroll`),run:(e,t)=>e.interactions.scroll(t),cliSchema:Y.scroll,cliReader:K.scroll,daemonWriter:q.scroll,cliOutputFormatter:J.scroll}),R({name:`get`,text:{summary:`Read element text or attributes`},metadata:X(`get`),run:(e,t)=>e.interactions.get(Hc(t)),cliSchema:Y.get,cliReader:K.get,daemonWriter:q.get,cliOutputFormatter:J.get}),R({name:`is`,text:{summary:`Check a UI predicate on a selector`},metadata:X(`is`),run:(e,t)=>e.interactions.is(t),cliSchema:Y.is,cliReader:fc.is,daemonWriter:pc.is,cliOutputFormatter:J.is}),R({name:`find`,text:{summary:`Find an element and act`},metadata:X(`find`),run:(e,t)=>e.interactions.find(t),cliSchema:Y.find,cliReader:fc.find,daemonWriter:pc.find,cliOutputFormatter:J.find}),R({name:`gesture`,text:{summary:`Run pan, fling, swipe, pinch, rotate, transform, tap, or drag gestures`,cliDetail:`Argument shapes: pan <x> <y> <dx> <dy> [durationMs], fling <up|down|left|right> <x> <y> [distance], swipe <left|right|left-edge|right-edge>, pinch <scale> [x] [y], rotate <degrees> [x] [y], transform <x> <y> <dx> <dy> <scale> <degrees> [durationMs], tap <x1> <y1> <x2> <y2> [... <x5> <y5>] [--hold-ms <ms>] [--count <n>] [--pause-ms <ms>], or drag <source-selector|pinned-ref> <destination-selector|pinned-ref> [sourceHoldMs] [moveMs] [destinationHoldMs]. For command plans, output only command lines. Android transform verification should use all app-observable effects, for example wait text "pan changed yes", wait text "pinch changed yes", and wait text "rotate changed yes", not exact transform values.`},metadata:X(`gesture`),run:(e,t)=>e.interactions.gesture({...ut(t),...tr(t)}),cliSchema:Y.gesture,cliReader:Vs.gesture,daemonWriter:Hs.gesture})]});function X(e){let t=zs.find(t=>t.name===e);if(!t)throw Error(`Missing interaction command metadata for ${e}`);return t}function Ic(e){return{...Lc(e),button:e.button}}function Lc(e){return{...tr(e),...si(e.target),...ui(e),...li(e),verify:e.verify,...Vc(e)}}function Rc(e){return{...tr(e),...si(e.target),...ui(e),text:e.text,delayMs:e.delayMs,recordAs:e.recordAs,textStdin:e.textStdin,verify:e.verify,...Vc(e)}}function zc(e){return{...tr(e),...si(e.target),...ui(e),durationMs:e.durationMs,...Vc(e)}}function Bc(e){return{...tr(e),...si(e.target),...ui(e),...Vc(e)}}function Vc(e){return{settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs}}function Hc(e){return{...tr(e),...ci(e.target),...ui(e),format:e.format,record:e.record}}async function Uc(e){let{serializeDevice:t}=await import(`./result-serialization.js`).then(e=>e.n);return{data:{devices:e.map(t)},text:e.map(il).join(`
21
+ `)}}async function Wc(e){let{serializeDevice:t}=await import(`./result-serialization.js`).then(e=>e.n);return{data:{device:t(e.device),availableCommands:e.availableCommands},text:[`${il(e.device)} supports ${e.availableCommands.length} commands:`,e.availableCommands.join(` `)].join(`
22
+ `)}}function Gc(e){return{data:{apps:e.result},stderr:e.appsFilter===`all`?`Showing all apps, including system apps.
23
23
  `:`Showing user-installed apps or deferred provider app assets. Use --all to include system apps on a live device.
24
24
  `,text:e.result.length>0?e.result.join(`
25
- `):e.appsFilter===`all`?`No apps found.`:`No user apps or provider app assets found.`}}async function Gc(e){if(`savedScript`in e)return{data:e,text:`Published script: ${e.savedScript}\nSession remains active: ${e.session}\nActions: ${e.actionCount}`};if(`stateDir`in e)return{data:e,text:e.stateDir};let{serializeSessionListEntry:t}=await import(`./result-serialization.js`).then(e=>e.t),n={sessions:e.sessions.map(t)};return{data:n,text:JSON.stringify(n,null,2)}}async function Kc(e){let{serializeOpenResult:t}=await import(`./result-serialization.js`).then(e=>e.t),n=t(e),r=[sn(n)].filter(e=>!!e);typeof n.sessionStateDir==`string`&&r.push(`Session state: ${n.sessionStateDir}`);for(let t of e.warnings??[])r.push(`Warning: ${t}`);let i=await qc(e.snapshot);return i&&(n.snapshot=i.jsonData??i.data,i.text&&r.push(i.text)),{data:n,...i?.stderr?{stderr:i.stderr}:{},text:r.join(`
26
- `)||null}}async function qc(e){return!e||!Array.isArray(e.nodes)?null:await Ho({result:e,interactiveOnly:!0})}async function Jc(e){let{serializeCloseResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return vi(t(e))}function Yc(e){if(Xc(e))return{data:e,text:e.artifacts.length>0?e.artifacts.map(il).join(`
27
- `):e.message??`No daemon artifacts available.`};let t=[e.message??`No cloud artifacts available for ${e.provider}.`],n=al(e);return n&&t.push(`Retry: ${n}`),{data:e,text:e.cloudArtifacts.length>0?e.cloudArtifacts.map(rl).join(`
25
+ `):e.appsFilter===`all`?`No apps found.`:`No user apps or provider app assets found.`}}async function Kc(e){if(`savedScript`in e)return{data:e,text:`Published script: ${e.savedScript}\nSession remains active: ${e.session}\nActions: ${e.actionCount}`};if(`stateDir`in e)return{data:e,text:e.stateDir};let{serializeSessionListEntry:t}=await import(`./result-serialization.js`).then(e=>e.n),n={sessions:e.sessions.map(t)};return{data:n,text:JSON.stringify(n,null,2)}}async function qc(e){let{serializeOpenResult:t}=await import(`./result-serialization.js`).then(e=>e.n),n=t(e),r=[cn(n)].filter(e=>!!e);typeof n.sessionStateDir==`string`&&r.push(`Session state: ${n.sessionStateDir}`);for(let t of e.warnings??[])r.push(`Warning: ${t}`);let i=await Jc(e.snapshot);return i&&(n.snapshot=i.jsonData??i.data,i.text&&r.push(i.text)),{data:n,...i?.stderr?{stderr:i.stderr}:{},text:r.join(`
26
+ `)||null}}async function Jc(e){return!e||!Array.isArray(e.nodes)?null:await Uo({result:e,interactiveOnly:!0})}async function Yc(e){let{serializeCloseResult:t}=await import(`./result-serialization.js`).then(e=>e.n);return bi(t(e))}function Xc(e){if(Zc(e))return{data:e,text:e.artifacts.length>0?e.artifacts.map(ol).join(`
27
+ `):e.message??`No daemon artifacts available.`};let t=[e.message??`No cloud artifacts available for ${e.provider}.`],n=sl(e);return n&&t.push(`Retry: ${n}`),{data:e,text:e.cloudArtifacts.length>0?[...e.cloudArtifacts.map(al),...e.message?[e.message]:[]].join(`
28
28
  `):t.join(`
29
- `)}}function Xc(e){return`source`in e&&e.source===`daemon`}async function Zc(e){let{serializeDeployResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return vi(t(e))}async function Qc(e){let{serializeInstallFromSourceResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return vi(t(e))}function $c(e){let t=e,n=t.platform??`unknown`;return{data:t,text:`Boot ready: ${t.device??t.id??`unknown`} (${n})`}}function el(e){let t=e,n=t.platform??`unknown`,r=t.device??t.id??`unknown`,i=t.shutdown;return{data:t,text:`${i&&typeof i==`object`&&`success`in i&&i.success===!0?`Shutdown`:`Shutdown failed`}: ${r} (${n})`}}async function tl(e,t,n){let{formatDoctorCheckDetailLines:r,formatDoctorCheckSummaryLine:i}=await import(`./doctor-lines.js`).then(e=>e.t),{shouldColorStatusMarkers:a}=await import(`./status-markers.js`).then(e=>e.r),o=a(t,!!process.stderr.isTTY),s=e,c=[`Doctor: ${typeof s.status==`string`?s.status:`unknown`}`],l=ol(s.checks);if(n?.renderedToStderr){let e=typeof s.summary==`string`?s.summary:void 0;e&&c.push(e)}else if(l.length===0){let e=typeof s.summary==`string`?s.summary:`No blockers found.`;c.push(e)}else for(let e of l)c.push(i(e,{useColor:o})),c.push(...r(e));return{data:s,text:c.join(`
30
- `)}}const Z={boot:V($c),shutdown:V(el),devices:V(Hc),capabilities:V(Uc),doctor:({result:e,env:t,progress:n})=>tl(e,t,n),apps:({input:e,result:t})=>Wc({result:t,appsFilter:e.appsFilter}),session:V(Gc),artifacts:V(Yc),open:V(Kc),close:V(Jc),install:V(Zc),reinstall:V(Zc),"install-from-source":V(Qc),prepare:H,viewport:H};function nl(e){let t=e.kind?` ${e.kind}`:``,n=e.target?` target=${e.target}`:``,r=e.model?` model=${JSON.stringify(e.model)}`:``,i=e.osVersion?` os=${e.osVersion}`:``,a=typeof e.booted==`boolean`?` booted=${e.booted}`:``,o=e.claimedBy?` claimed by session "${e.claimedBy.session}" in ${e.claimedBy.workspace}`:``;return`${e.name} (${e.platform}${t}${n}${r}${i})${a}${o}`}function rl(e){let t=e.url?` ${e.url}`:``,n=e.availability?` ${e.availability}`:``;return`${e.kind}: ${e.name}${n}${t}`}function il(e){let t=e.artifactType?` (${e.artifactType})`:``;return`${e.filename}${t}: ${e.mimeType} ${e.sizeBytes} bytes id=${e.id}`}function al(e){if(e.providerSessionId)return`agent-device artifacts ${e.providerSessionId} --provider ${e.provider} --json`}function ol(e){return Array.isArray(e)?e.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):[]}const sl=z({name:`artifacts`,text:{summary:`List daemon or cloud provider session artifacts`},metadata:R(`artifacts`,`List daemon or cloud provider artifacts for an active or completed session.`,{provider:j(`Cloud provider name, for example browserstack, aws-device-farm, or testmu.`),providerSessionId:j(`Cloud provider session id or ARN.`)}),run:(e,t)=>e.sessions.artifacts(t),cliSchema:{usageOverride:`artifacts [provider-session-id]`,usageFlags:[`provider`],positionalArgs:[`provider-session-id?`],allowedFlags:[`provider`,`providerSessionId`]},cliReader:(e,t)=>({...v(t),provider:t.provider,providerSessionId:e[0]??t.providerSessionId}),daemonWriter:g(d.artifacts),cliOutputFormatter:Z.artifacts});function cl(e){let{metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i}=e;if(t!==void 0||n!==void 0||r!==void 0||i!==void 0)return{metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i}}function ll(e){let{metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i,...a}=e,o=cl({metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i});return o?{...a,runtime:o}:a}const ul=R(`apps`,`List the apps installed on the selected device. Include system or OEM apps only when they are needed as automation targets.`,{appsFilter:F([`user-installed`,`all`],`Restrict the listing to user-installed apps, or include system and OEM apps.`)}),dl=R(`open`,`Boot the selected device when needed, then open an app, deep link, or URL in a session. Use the app or URL inputs to choose what becomes the foreground automation target.`,{app:j(`App name, bundle id, package, or URL.`),url:j(`Optional URL passed with an app shell.`),surface:F(Wt,`macOS presentation surface to open: the app itself, the frontmost app, the desktop, or the menu bar.`),activity:j(`Android activity name.`),launchConsole:j(`File path on the daemon host for the stdout and stderr of the initial app launch. Local iOS simulator direct app launches only; not for URL opens.`),launchArgs:Ur(`Launch arguments forwarded verbatim to the platform launch command.`),relaunch:P(`Force relaunch.`),timeoutMs:N(`Startup budget in milliseconds. Bounds the Simulator boot wait, so a never-booted Simulator can finish its first-boot migration; omit for the default startup behavior.`,{min:1}),waitMs:Rr(`waitMs`),foreground:Rr(`foreground`),saveScript:I({oneOf:[O(),E()]}),force:P(`Overwrite an existing --save-script target instead of refusing (alias: --overwrite).`),testIme:P(`Activate the headless Android test IME for deterministic Unicode text entry (default on for emulators; opt-in on real devices).`),noRecord:P(`Do not record this action.`),metroHost:j(`Session-scoped Metro/debug host hint applied to the opened app.`),metroPort:N(`Session-scoped Metro/debug port hint applied to the opened app. On an emulator/simulator the host defaults to the loopback alias (Android 10.0.2.2, iOS 127.0.0.1) when --metro-host is omitted; physical devices still require an explicit --metro-host.`,{min:1,max:65535}),bundleUrl:j(`Session-scoped bundle URL hint applied to the opened app.`),launchUrl:j(`Launch URL for the opened app; does not select the server used by metro reload.`),...Qr()}),fl=R(`close`,`Close the named app, or close the active session app when app is omitted. Use shutdown only when the selected simulator or emulator should also stop. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running.`,{app:j(`Optional app to close.`),shutdown:P(`Shutdown the session/device where supported.`),saveScript:I({oneOf:[O(),E()]}),force:P(`Overwrite an existing --save-script target instead of refusing (alias: --overwrite).`)});function pl(e){return ll(e)}const ml={allowedFlags:[`appsFilter`]},hl={positionalArgs:[`appOrUrl?`,`url?`],allowedFlags:[`activity`,`launchConsole`,`launchArgs`,`testIme`,`saveScript`,`force`,`noRecord`,`relaunch`,`foreground`,`timeoutMs`,`waitMs`,`surface`,...na,`launchUrl`,...ra]},gl={positionalArgs:[`app?`],allowedFlags:[`saveScript`,`force`,`shutdown`]},_l=(e,t)=>({...v(t),appsFilter:xn(t.appsFilter)}),vl=(e,t)=>({...v(t),app:e[0],url:e[1],surface:t.surface,activity:t.activity,launchConsole:t.launchConsole,launchArgs:t.launchArgs,relaunch:t.relaunch,foreground:t.foreground,timeoutMs:t.timeoutMs,waitMs:t.waitMs,saveScript:t.saveScript,force:t.force,testIme:t.testIme,noRecord:t.noRecord,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,launchUrl:t.launchUrl,...ur(t)}),yl=(e,t)=>({...v(t),app:e[0],shutdown:t.shutdown,saveScript:t.saveScript,force:t.force}),bl=g(d.apps),xl=g(d.open,Dl),Sl=g(d.close,e=>y(e.app)),Cl=z({name:`apps`,text:{summary:`List installed apps or deferred provider app assets`,cliDetail:`Before provider allocation, lists uploaded app assets when the selected provider exposes a catalog. On a live device, defaults to user-installed apps; use --all to include system/OEM apps.`},metadata:ul,run:(e,t)=>e.apps.list(t),cliSchema:ml,cliReader:_l,daemonWriter:bl,cliOutputFormatter:Z.apps}),wl=z({name:`open`,text:{summary:`Open an app, deep link or URL, save replays`,cliDetail:`Use --platform to bind URL/deep-link opens to the target platform. For local iOS simulator initial stdout/stderr, put --launch-console <path> on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app's Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app's launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+<slug> scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in <App>?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app's own alert (such as a permission prompt) rather than a translated launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app's target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. Only the English prompt title with Cancel and Open buttons is recognized, so on a Simulator set to another language the prompt stays on screen. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait <ms> to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session.`,mcpDetail:`metroHost, metroPort, and bundleUrl choose the app's Metro server and save its address for later reloads. launchUrl selects the app's launch URL and does not select the reload server. A fresh open without Metro hints clears an older same-name binding; close also clears it.`},metadata:dl,run:(e,t)=>e.apps.open(pl(t)),cliSchema:hl,cliReader:vl,daemonWriter:xl,cliOutputFormatter:Z.open}),Tl=z({name:`close`,text:{summary:`Close an app or end the session`},metadata:fl,run:(e,t)=>t.app?e.apps.close(t):e.sessions.close(El(t)),cliSchema:gl,cliReader:yl,daemonWriter:Sl,cliOutputFormatter:Z.close});function El(e){let{app:t,...n}=e;return n}function Dl(e){return e.app?e.url?[e.app,e.url]:[e.app]:[]}const Ol={platform:w(ht),target:w(_t),device:E(`Human-readable device name.`),id:E(`Stable device id.`),kind:w(vt)},kl=[`platform`,`target`,`device`,`id`,`kind`],Al=C({success:O(),exitCode:D(),stdout:E(),stderr:E(),error:k(`Normalized error detail when shutdown failed.`)},[`success`,`exitCode`,`stdout`,`stderr`]),jl={boot:C({...Ol,booted:{type:`boolean`,const:!0}},[...kl,`booted`]),shutdown:C({...Ol,shutdown:Al},[...kl,`shutdown`])},Ml=R(`devices`,`List available devices and simulators that can be selected for automation. Use platform, device, udid, or serial inputs on later commands to target one result.`,{}),Nl=R(`capabilities`,`List the commands supported by the selected device or active session. Use device-selection inputs when checking support before a session is open.`,{}),Pl=R(`boot`,`Boot or prepare the selected device or simulator so later commands can target it. The device is chosen through the device-selection inputs, not by naming it here.`,{headless:P(`Boot without showing simulator UI when supported.`),timeoutMs:N(`Startup budget in milliseconds. Bounds the boot wait, so a never-booted Simulator can finish its first-boot migration or a cold emulator its boot; omit for the default startup behavior.`,{min:1})}),Fl=R(`shutdown`,`Shutdown a selected simulator or emulator.`,{}),Il={allowedFlags:[`headless`,`timeoutMs`]},Ll={},Rl={},zl={},Bl=(e,t)=>v(t),Vl=(e,t)=>({...v(t),headless:t.headless,timeoutMs:t.timeoutMs}),Hl=g(d.devices),Ul=g(d.capabilities),Wl=g(d.boot),Gl=g(d.shutdown),Kl=[z({name:`devices`,text:{summary:`List available devices and simulators`},metadata:Ml,run:(e,t)=>e.devices.list(t),cliSchema:Ll,cliReader:Bl,daemonWriter:Hl,cliOutputFormatter:Z.devices}),z({name:`capabilities`,text:{summary:`List supported commands for the selected device`,cliDetail:`Select an explicit target with --platform/--device/--udid/--serial.`},metadata:Nl,run:(e,t)=>e.devices.capabilities(t),cliSchema:Rl,cliReader:Bl,daemonWriter:Ul,cliOutputFormatter:Z.capabilities}),z({name:`boot`,text:{summary:`Boot target device/simulator`},metadata:Pl,run:(e,t)=>e.devices.boot(t),cliSchema:Il,cliReader:Vl,daemonWriter:Wl,cliOutputFormatter:Z.boot}),z({name:`shutdown`,text:{summary:`Shutdown target simulator/emulator`},metadata:Fl,run:(e,t)=>e.devices.shutdown(t),cliSchema:zl,cliReader:Bl,daemonWriter:Gl,cliOutputFormatter:Z.shutdown})],ql={doctor:C({status:w([`pass`,`warn`,`fail`,`info`]),summary:E(),kind:w([`auto`,`react-native`,`expo`,`repack`]),platform:E(),target:w(_t),targetApp:E(),metro:C({host:E(),port:D()},[`host`,`port`]),checks:{type:`array`,items:C({id:E(),status:w([`pass`,`warn`,`fail`,`info`]),summary:E(),hint:E(),command:E(),evidence:k()},[`id`,`status`,`summary`])}},[`status`,`summary`,`kind`,`checks`])},Jl=z({name:`doctor`,text:{summary:`Diagnose device, app, dev-server, and RN/Expo readiness`,cliDetail:`Metro reachability is inferred from cwd/runtime. On iOS simulators it also warms the XCTest runner build cache in the background when missing. Pass --app to verify a target app on the one matching booted device without opening a session. Use --remote to check remote connection setup without probing local devices. Default output is compact; use --json for full checks and evidence.`,mcpDetail:`On iOS simulators it also warms the XCTest runner build cache in the background when missing, so run it before the first Apple snapshot or interaction of a session.`},metadata:R(`doctor`,`Diagnose device, app, development-server, and React Native or Expo readiness issues. Returns compact evidence for local inventory, sessions, optional app discovery, toolchains, and server reachability.`,{targetApp:j(`Installed app package/bundle id or app name to verify without opening a session.`),remote:P(`Check remote connection setup instead of local device inventory.`)}),run:(e,t)=>e.command.doctor(t),cliSchema:{usageOverride:`doctor [--platform ios|android|harmonyos|vega|macos|linux|web|apple]`,allowedFlags:[`targetApp`,`remote`]},cliReader:(e,t)=>({...v(t),targetApp:t.targetApp,remote:t.remote}),daemonWriter:g(d.doctor),cliOutputFormatter:Z.doctor});function Yl(e,t=`--github-actions-artifact`){let r=e.indexOf(`:`);if(r<=0||r===e.length-1)throw new n(`INVALID_ARGS`,`${t} must use owner/repo:artifact, for example thymikee/RNCLI83:6635342232`);let{owner:i,repo:a}=Ql(e.slice(0,r),t);return Zl(i,a,e.slice(r+1),`${t} artifact`)}function Xl(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`${t} installSource must be an object.`);let r=e;if(eu(r.type,`${t} installSource.type`)!==`github-actions-artifact`)throw new n(`INVALID_ARGS`,`${t} installSource.type must be "github-actions-artifact".`);let{owner:i,repo:a}=Ql(eu(r.repo,`${t} installSource.repo`),`${t} installSource.repo`);return Zl(i,a,r.artifact,`${t} installSource.artifact`)}function Zl(e,t,n,r){return typeof n==`number`||nu(n)?{kind:`github-actions-artifact`,owner:e,repo:t,artifactId:tu(n,r)}:{kind:`github-actions-artifact`,owner:e,repo:t,artifactName:eu(n,r)}}function Ql(e,t){let r=e.indexOf(`/`);if(r<=0||r===e.length-1||e.indexOf(`/`,r+1)!==-1)throw new n(`INVALID_ARGS`,`${t} must use owner/repo.`);let i={owner:e.slice(0,r).trim(),repo:e.slice(r+1).trim()};if(!i.owner||!i.repo)throw new n(`INVALID_ARGS`,`${t} must use owner/repo.`);return i}function $l(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function eu(e,t){let r=$l(e);if(!r)throw new n(`INVALID_ARGS`,`${t} must be a non-empty string.`);return r}function tu(e,t){let r=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;if(!Number.isInteger(r))throw new n(`INVALID_ARGS`,`${t} must be an integer.`);return r}function nu(e){return typeof e==`string`&&/^\d+$/.test(e.trim())}const ru=R(`install`,`Install an app binary from a local path. Provide an app identifier with the path when the target needs explicit app selection; use reinstall to replace an already installed app.`,{app:j(`Optional app identifier hint.`),appPath:A(j(`Path to app binary.`)),...Qr()}),iu=R(`reinstall`,`Replace an installed app with a binary from a local path. Use this when preserving the same app identity while installing a new build on the selected device.`,{app:A(j()),appPath:A(j(`Path to app binary.`)),...Qr()}),au=R(`uninstall`,`Remove an installed app from the selected device. A package name or bundle id that is not installed succeeds with wasInstalled: false.`,{app:A(j(`Package name, bundle id, or installed app name.`)),...Qr()}),ou=R(`install-from-source`,`Install app builds from URLs, remote source specs, or CI artifacts resolved by a remote daemon.`,{source:A(I(k(`Install source object.`))),retainPaths:P(),retentionMs:N()}),su={usageOverride:`install <path> | install <app> <path>`,listUsageOverride:`install <path>`,positionalArgs:[`appOrPath`,`path?`],allowedFlags:ra},cu={positionalArgs:[`app`,`path`],allowedFlags:ra},lu={positionalArgs:[`app`],allowedFlags:ra},uu={usageOverride:`install-from-source <url> | install-from-source --github-actions-artifact <owner/repo:artifact>`,usageFlags:[],listUsageOverride:`install-from-source`,positionalArgs:[`url?`],allowedFlags:[`header`,`githubActionsArtifact`,`installSource`,`retainPaths`,`retentionMs`]},du=(e,t)=>yu(e,t),fu=(e,t)=>bu(e,t),pu=(e,t)=>({...v(t),app:x(e[0],`uninstall requires app`),...ur(t)}),mu=(e,t)=>({...v(t),source:Cu(e,t),retainPaths:t.retainPaths,retentionMs:t.retentionMs}),hu=g(d.install,e=>xu(e.app,e.appPath)),gu=g(d.reinstall,e=>Su(e.app,e.appPath)),_u=g(d.uninstall,e=>[S(e.app,`missing app`)]),vu=[z({name:`install`,text:{summary:`Install an app binary from a path`},metadata:ru,run:(e,t)=>e.apps.install(t),cliSchema:su,cliReader:du,daemonWriter:hu,cliOutputFormatter:Z.install}),z({name:`reinstall`,text:{summary:`Replace an installed app with a new build`},metadata:iu,run:(e,t)=>e.apps.reinstall(t),cliSchema:cu,cliReader:fu,daemonWriter:gu,cliOutputFormatter:Z.reinstall}),z({name:`uninstall`,text:{summary:`Remove an installed app`},metadata:au,run:(e,t)=>e.apps.uninstall(t),cliSchema:lu,cliReader:pu,daemonWriter:_u}),z({name:`install-from-source`,text:{summary:`Install app builds from URLs or CI artifacts`},metadata:ou,run:(e,t)=>e.apps.installFromSource(t),cliSchema:uu,cliReader:mu,daemonWriter:e=>_(Xe.installSource,[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),cliOutputFormatter:Z[`install-from-source`]})];function yu(e,t){let[n,r]=e,i=r!==void 0;return{...v(t),...i?{app:x(n,`install requires app`)}:{},appPath:x(i?r:n,`install requires path`),...ur(t)}}function bu(e,t){return{...v(t),app:x(e[0],`reinstall requires app`),appPath:x(e[1],`reinstall requires path`),...ur(t)}}function xu(e,t){let n=S(t,`missing app path`);return typeof e==`string`&&e.length>0?[e,n]:[n]}function Su(e,t){return[S(e,`missing first positional`),S(t,`missing second positional`)]}function Cu(e,t){let r=e[0]?.trim();if(e.length>1)throw new n(`INVALID_ARGS`,`install-from-source accepts either one <url> positional or --github-actions-artifact`);let i=t.githubActionsArtifact?Yl(t.githubActionsArtifact):void 0,a=t.installSource;if(+!!r+ +!!i+ +!!a!=1)throw new n(`INVALID_ARGS`,`install-from-source requires exactly one source: <url>, --github-actions-artifact, or config installSource`);if(!r&&t.header&&t.header.length>0)throw new n(`INVALID_ARGS`,`install-from-source --header is only supported for URL sources`);if(i)return i;if(a)return a;if(!wu(r))throw new n(`INVALID_ARGS`,`install-from-source <url> must be an http(s) URL: ${r}`,{hint:`Install a local build with install <app> <path>.`});return{kind:`url`,url:r,headers:Tu(t.header)}}function wu(e){let t=URL.parse(e)?.protocol;return t===`http:`||t===`https:`}function Tu(e){if(!e||e.length===0)return;let t={};for(let r of e){let e=r.indexOf(`:`);if(e<=0)throw new n(`INVALID_ARGS`,`Invalid --header value "${r}". Expected "name:value".`);let i=r.slice(0,e).trim(),a=r.slice(e+1).trim();if(!i)throw new n(`INVALID_ARGS`,`Invalid --header value "${r}". Header name cannot be empty.`);t[i]=a}return t}const Eu=[`ios-runner`],Du={prepare:C({action:T(`ios-runner`),platform:w(ht),deviceId:E(),deviceName:E(),kind:w(vt),durationMs:D(),runner:C({},[]),cache:w([`exact`,`miss`,`external`]),artifact:w([`valid`,`rebuilt`]),buildMs:D(),connectMs:D(),healthCheckMs:D(),xctestrunPath:E(),recoveryReason:E(),failureReason:E(),timing:C({totalMs:D(),additiveParts:C({buildMs:D(),connectAfterBuildMs:D(),healthCheckMs:D()},[`connectAfterBuildMs`,`healthCheckMs`]),containment:C({connectMs:{type:`array`,items:T(`buildMs`)},healthCheckMs:{type:`array`,items:E()}},[`healthCheckMs`]),note:E()},[`totalMs`,`additiveParts`,`containment`,`note`]),message:E()},[`action`,`platform`,`deviceId`,`deviceName`,`kind`,`durationMs`,`runner`,`connectMs`,`healthCheckMs`,`timing`,`message`])},Ou=z({name:`prepare`,text:{summary:`Pre-warm platform helpers before automation`},metadata:R(`prepare`,`Prepare platform helper infrastructure. ios-runner builds/reuses, starts, and health-checks the XCTest runner so later Apple snapshots and interactions do not pay first-use startup cost. In JSON output, top-level buildMs/connectMs/healthCheckMs are diagnostic fields and may overlap; use timing.additiveParts for additive wall-clock phase totals. In CI, run it after boot/install and before replay/test; if replay/test starts a separate daemon, stop the prepare daemon before replay/test so it does not keep the prepared runner lease. It is not a recovery step for "runner already owned by another agent-device daemon"; stop the owning daemon on the Mac with simulator access instead. Runner build/start output is written to the session runner.log; daemon.log is for daemon lifecycle/startup issues.`,{action:A(F(Eu)),timeoutMs:N(`Maximum wall-clock time for the prepare command.`)}),run:(e,t)=>e.command.prepare(t),cliSchema:{usageOverride:`prepare ios-runner --platform ios|macos`,listUsageOverride:`prepare`,positionalArgs:[`ios-runner`],allowedFlags:[`timeoutMs`]},cliReader:(e,t)=>({...v(t),action:x(e[0],`prepare requires subcommand`),timeoutMs:t.timeoutMs}),daemonWriter:g(d.prepare,e=>[S(e.action,`prepare requires subcommand`)]),cliOutputFormatter:Z.prepare}),ku={push:{type:`object`,oneOf:[C({platform:T(`ios`),bundleId:E(),message:E()},[`platform`,`bundleId`,`message`]),C({platform:T(`android`),package:E(),action:E(),extrasCount:D(),message:E()},[`platform`,`package`,`action`,`extrasCount`,`message`])]},"trigger-app-event":C({event:E(),eventUrl:E(),transport:T(`deep-link`),message:E()},[`event`,`eventUrl`,`transport`,`message`])},Au=R(`push`,`Deliver push notification payloads to an installed app.`,{app:A(j()),payload:A(I({oneOf:[E(),k()]}))}),ju=R(`trigger-app-event`,`Ask the app to handle an app-defined automation or test event, with an optional structured payload. Call this only for event names and payload shapes the app documents.`,{event:A(j(`Name of an app-defined automation or test event the app documents.`)),payload:Vu(`Structured payload passed to the event, in the shape the app documents for it.`)}),Mu={listUsageOverride:`push`,positionalArgs:[`bundleOrPackage`,`payloadOrJson`]},Nu={usageOverride:`trigger-app-event <event> [payloadJson]`,listUsageOverride:`trigger-app-event`,positionalArgs:[`event`,`payloadJson?`]},Pu=(e,t)=>({...v(t),app:x(e[0],`push requires bundleOrPackage`),payload:x(e[1],`push requires payloadOrJson`)}),Fu=(e,t)=>({...v(t),event:x(e[0],`trigger-app-event requires event`),payload:e[1]?br(e[1],`trigger-app-event payload`):void 0}),Iu=g(d.push,e=>zu(e)),Lu=g(d.triggerAppEvent,e=>Bu(e)),Ru=[z({name:`push`,text:{summary:`Deliver a push notification payload`},metadata:Au,run:(e,t)=>e.apps.push(t),cliSchema:Mu,cliReader:Pu,daemonWriter:Iu}),z({name:`trigger-app-event`,text:{summary:`Invoke an app-defined automation event`},metadata:ju,run:(e,t)=>e.apps.triggerEvent(t),cliSchema:Nu,cliReader:Fu,daemonWriter:Lu})];function zu(e){return[e.app,typeof e.payload==`string`?e.payload:JSON.stringify(e.payload)]}function Bu(e){return[e.event,...e.payload?[JSON.stringify(e.payload)]:[]]}function Vu(e){return Hr(e)}const Hu=z({name:`session`,text:{summary:`List sessions, show the state dir, or publish a script`},metadata:R(`session`,`List active sessions, print the effective daemon state directory, or publish an armed open-to-destination script without closing its session`,{action:F([`list`,`state-dir`,`save-script`],`list shows active sessions; state-dir prints the daemon state directory; save-script publishes an armed recording without teardown.`),path:j(`Optional .ad output path for save-script.`),force:P(`Atomically replace an existing save-script target.`)}),run:async(e,{action:t,path:n,force:r,...i})=>{let a=t??`list`;return Wu(a,n,r),a===`state-dir`?{stateDir:await e.sessions.stateDir(i)}:a===`save-script`?await e.sessions.saveScript({...i,path:n,force:r}):{sessions:await e.sessions.list(i)}},cliSchema:{usageOverride:`session list | session state-dir | session save-script [path] [--force]`,usageFlags:[],listUsageOverride:`session`,positionalArgs:[`list|state-dir|save-script?`,`path?`],allowedFlags:[`force`]},cliReader:(e,t)=>({...v(t),action:Uu(e[0]),path:e[1],force:t.force}),cliOutputFormatter:Z.session});function Uu(e){let t=e??`list`;if(t===`list`||t===`state-dir`||t===`save-script`)return t;throw new n(`INVALID_ARGS`,`session only supports list, state-dir, or save-script`)}function Wu(e,t,r){if(e!==`save-script`&&(t!==void 0||r===!0))throw new n(`INVALID_ARGS`,`session ${e} does not accept a path or --force; use session save-script [path] [--force] to publish a recording.`)}const Gu={viewport:C({width:D(),height:D(),message:E()},[`width`,`height`,`message`])},Ku=z({name:`viewport`,text:{summary:`Resize the active web viewport for the current session`},metadata:R(`viewport`,`Resize the active web viewport before taking snapshots or screenshots. Useful for fixed-layout or 100vh apps where changing the viewport reveals different content.`,{width:A(N(`Viewport width in CSS pixels.`,{min:1})),height:A(N(`Viewport height in CSS pixels.`,{min:1}))}),run:(e,t)=>e.command.viewport(t),cliSchema:{positionalArgs:[`width`,`height`]},cliReader:(e,t)=>({...v(t),...qe(e)}),daemonWriter:g(d.viewport,e=>{let{width:t,height:n}=e;return[String(t),String(n)]}),cliOutputFormatter:Z.viewport}),qu=B({name:`management`,commands:[...Kl,sl,Jl,Ou,Cl,Hu,wl,Tl,Ku,...vu,...Ru]});function Ju(e){return{data:e.result,text:e.action===`reload`?`Reloaded React Native apps via ${e.result.reloadUrl}`:JSON.stringify(e.result,null,2)}}const Yu={metro:({input:e,result:t})=>Ju({result:t,action:e.action})},Xu=[`auto`,`react-native`,`expo`,`repack`];function Zu(e){if(e!==void 0){if(Xu.includes(e))return e;throw new n(`INVALID_ARGS`,`metro prepare --kind must be auto, react-native, expo, or repack`)}}const Qu=`metro`,$u=B({name:`metro`,commands:[z({name:Qu,text:{summary:`Prepare the dev server or reload apps`,cliDetail:`reload with no --metro-host/--metro-port/--bundle-url resolves against the dev server this session last bound via metro prepare or open's metro hint flags (falling back to localhost:8081 only when the session never bound one), so it never silently reloads a different project's server on the default port; pass an explicit flag to override the session hint for one call. After prepare, reload uses the local server address independently of the public or proxy address given to the device; a fresh open preserves it only when its client-config runtime points to the prepared device server, while explicit reload flags override it. For open or an explicit bundle URL, reload removes a .bundle/.jsbundle/.js entry filename and keeps the remaining path as the server mount, and when the server has no HTTP /reload route (Expo) the reload is broadcast over its /message websocket instead of trusting the app-page fallback. The binding is cleared when the session closes, and a fresh open without hint flags also clears any leftover binding from a previous same-name session. --kind expo (detected or forced) requests the virtual-entry bundle URL (.expo/.virtual-metro-entry.bundle) instead of index.bundle, since index.bundle 404s/500s against Expo dev servers in monorepos. Dependency install auto-detects the package manager from the nearest yarn.lock/pnpm-lock.yaml/bun.lock/bun.lockb/package-lock.json walking up from --project-root (bounded at the repo root), so Yarn/pnpm workspace monorepos with the lockfile at the repo root do not wrongly fall back to npm install (which fails on workspace: dependency specifiers); if install still fails, pass --no-install-deps when dependencies are already installed (for example via a monorepo root install).`,mcpDetail:`The binding is cleared when the session closes, and a fresh open without runtime hints also clears any leftover binding from a previous same-name session.`},metadata:R(Qu,`Prepare a React Native development server or ask connected apps to reload, using the development server this session is bound to. Provide explicit runtime inputs only to override that binding for one call.`,{action:A(F([`prepare`,`reload`])),projectRoot:j(),kind:I(E()),publicBaseUrl:j(),proxyBaseUrl:Lr(j(),{operatorPath:`Configure the remote proxy in the remote-config profile or operator config for the process serving these tools.`}),bearerToken:Lr(j(),{envFlagKeys:[`metroBearerToken`,`daemonAuthToken`]}),bridgeScope:I({type:`object`,additionalProperties:!0}),launchUrl:j(),port:N(),listenHost:j(),statusHost:j(),startupTimeoutMs:N(),probeTimeoutMs:N(),reuseExisting:P(),installDependenciesIfNeeded:P(),runtimeFilePath:j(),logPath:j(),metroHost:j(),metroPort:N(),bundleUrl:j(),timeoutMs:N()}),run:async(e,t)=>t.action===`prepare`?await e.metro.prepare(ed(t)):await e.metro.reload(nd(t)),cliSchema:{usageOverride:`metro prepare (--public-base-url <url> | --proxy-base-url <url>) [--project-root <path>] [--port <port>] [--kind auto|react-native|expo|repack]
31
- agent-device metro reload [--metro-host <host>] [--metro-port <port>] [--bundle-url <url>]`,usageFlags:[],listUsageOverride:`metro`,positionalArgs:[`prepare|reload`],allowedFlags:[...na,...ta]},cliReader:(e,t)=>{let r=(e[0]??``).toLowerCase();if(r!==`prepare`&&r!==`reload`)throw new n(`INVALID_ARGS`,`metro requires a subcommand: prepare or reload`);if(r===`reload`)return{action:r,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,timeoutMs:t.metroProbeTimeoutMs};if(!t.metroPublicBaseUrl&&!t.metroProxyBaseUrl)throw new n(`INVALID_ARGS`,`metro prepare requires --public-base-url <url> or --proxy-base-url <url>.`);return{action:r,projectRoot:t.metroProjectRoot,kind:Zu(t.kind??t.metroKind),port:t.metroPreparePort,listenHost:t.metroListenHost,statusHost:t.metroStatusHost,publicBaseUrl:t.metroPublicBaseUrl,proxyBaseUrl:t.metroProxyBaseUrl,bearerToken:t.metroBearerToken,bridgeScope:t.tenant&&t.runId&&t.leaseId?{tenantId:t.tenant,runId:t.runId,leaseId:t.leaseId}:void 0,startupTimeoutMs:t.metroStartupTimeoutMs,probeTimeoutMs:t.metroProbeTimeoutMs,reuseExisting:!t.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!t.metroNoInstallDeps&&void 0,runtimeFilePath:t.metroRuntimeFile}},cliOutputFormatter:Yu.metro})]});function ed(e){return{projectRoot:e.projectRoot,kind:e.kind,publicBaseUrl:e.publicBaseUrl,proxyBaseUrl:e.proxyBaseUrl,bearerToken:e.bearerToken,bridgeScope:e.bridgeScope??td(e),port:e.port,listenHost:e.listenHost,statusHost:e.statusHost,startupTimeoutMs:e.startupTimeoutMs,probeTimeoutMs:e.probeTimeoutMs,reuseExisting:e.reuseExisting,installDependenciesIfNeeded:e.installDependenciesIfNeeded,runtimeFilePath:e.runtimeFilePath}}function td(e){return e.tenant&&e.runId&&e.leaseId?{tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId}:void 0}function nd(e){return{metroHost:e.metroHost,metroPort:e.metroPort,bundleUrl:e.bundleUrl,timeoutMs:e.timeoutMs}}function rd(e,t){return e.includes(t)}function id(e,t,r={}){let i=t===void 0?void 0:r.normalize?.(t)??t;if(i!==void 0&&rd(e,i))return i;let a=typeof r.message==`function`?r.message(t):r.message;throw new n(`INVALID_ARGS`,a??`Invalid value: ${t}. Use ${e.join(`|`)}.`)}const ad=[`started`,`stopped`,`marked`,`cleared`,`restarted`,`removedRotatedFiles`];function od(e){return{data:e,text:e.path,stderr:Md([Ad(e,[`active`,`state`,`backend`,`sizeBytes`]),Ad(e,ad),e.hint,jd(e.notes)])}}function sd(e){let t=e.events??[];return{data:e,text:t.length>0?dd(t):`No session events found.`,stderr:Md([Ad(e,[`path`,`cursor`,`nextCursor`,`limit`])])}}function cd(e){let t=[],n=e.entries??[];if(e.path&&t.push(e.path),n.length===0)t.push(`No recent HTTP(s) entries found.`);else for(let e of n)t.push(...Dd(e));return{data:e,text:t.join(`
32
- `),stderr:Md([Ad(e,[`active`,`state`,`backend`,`include`,`scannedLines`,`matchedLines`]),jd(e.notes)])}}function ld(e){return{data:e,text:[`Audio probe: ${String(e.state??`stopped`)} heard=${String(e.heard===!0)}`,Cd(`rmsDbfs`,e.rmsDbfs),Cd(`peakDbfs`,e.peakDbfs)].filter(e=>!!e).join(`
33
- `),stderr:Md([Ad(e,[`active`,`backend`,`source`,`durationMs`,`elapsedMs`,`bucketMs`,`sampleCount`,`sourceCount`,`mediaElementCount`]),jd(e.notes)])}}const ud={logs:V(od),events:V(sd),network:V(cd),audio:V(ld)};function dd(e){let t=e.map(fd),n=Math.min(Math.max(...t.map(e=>e.label.length),5),32);return t.map(e=>pd(e,n)).join(`
34
- `)}function fd(e){return{timestamp:md(e.ts),label:hd(e),summary:gd(e)}}function pd(e,t){let n=e.label.padEnd(t),r=e.timestamp?`${e.timestamp} ${n}`:n.trimEnd();return e.summary?`${r} ${e.summary}`:r.trimEnd()}function md(e){return e?e.replace(`T`,` `):``}function hd(e){let t=e.command??`command`;switch(e.kind){case`request.started`:return`start ${t}`;case`request.finished`:return wd([e.status===`error`?`error`:`ok`,t,Sd(Ed(e.details?.durationMs))]);case`action.recorded`:return`action ${t}`;default:return wd([e.kind??`event`,e.command])}}function gd(e){let t=_d(e.summary,e);return`${t}${vd(e,t)}`.trim()}function _d(e,t){let n=e?.trim()??``,r=t.command??``;return t.kind===`request.started`&&n===`Started ${r}`||t.kind===`request.finished`&&n===`Finished ${r}`?``:n}function vd(e,t){if(e.kind!==`action.recorded`)return``;let n=e.details;if(!n)return``;let r=[yd(n,t),xd(Ed(n.textLength))].filter(e=>!!e);return r.length>0?` (${r.join(`, `)})`:``}function yd(e,t){let n=Td(e.ref)??Td(e.selector)??bd(e);if(!(!n||t.includes(n)))return`target=${n}`}function bd(e){let t=Ed(e.x),n=Ed(e.y);return t===void 0||n===void 0?void 0:`(${t}, ${n})`}function xd(e){return e===void 0?void 0:`text=${e} chars`}function Sd(e){return e===void 0?void 0:`${Math.round(e)}ms`}function Cd(e,t){if(!Array.isArray(t))return;let n=t.filter(e=>typeof e==`number`&&Number.isFinite(e));return n.length>0?`${e}: [${n.join(`, `)}]`:void 0}function wd(e){return e.filter(e=>!!e).join(` `)}function Td(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function Ed(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Dd(e){let t=e.method??`HTTP`,n=e.url??`<unknown-url>`,r=e.status===void 0?``:` status=${e.status}`,i=e.timestamp?`${e.timestamp} `:``,a=e.durationMs===void 0?``:` durationMs=${e.durationMs}`,o=[`${i}${t} ${n}${`pathUnavailable`in e&&e.pathUnavailable?` (request path not logged)`:``}${r}${a}`];return e.headers?kd(o,`headers`,e.headers):(Od(o,`request headers`,e.requestHeaders),Od(o,`response headers`,e.responseHeaders)),kd(o,`request`,e.requestBody),kd(o,`response`,e.responseBody),o}function Od(e,t,n){!n||Object.keys(n).length===0||e.push(` ${t}: ${JSON.stringify(n)}`)}function kd(e,t,n){n!==void 0&&e.push(` ${t}: ${n}`)}function Ad(e,t){return t.map(t=>e[t]!==void 0&&e[t]!==null?`${t}=${e[t]}`:``).filter(Boolean).join(` `)||void 0}function jd(e){let t=e?.filter(e=>e.length>0)??[];return t.length>0?t.join(`
35
- `):void 0}function Md(e){return e.filter(e=>!!e).join(`
36
- `)||void 0}const Nd=`logs`,Pd=`events`,Fd=`network`,Id=`audio`,Ld=[`dump`,`log`],Rd=[`probe`],zd=[`start`,`status`,`stop`],Bd=R(Nd,`Session app log info, start/stop streaming, diagnostics, and markers`,{action:F(Tn),message:j(),restart:P()}),Vd=R(Pd,`Read the daemon-owned session event timeline as paged JSON-friendly entries`,{limit:N(),cursor:j()}),Hd=R(Fd,`Dump recent HTTP(s) traffic parsed from the session app log`,{action:F(Ld),limit:N(),include:F(o)}),Ud=R(Id,`Measure browser or host-rendered simulator/emulator audio as compact dBFS buckets. Start a probe before requesting its status or stopping it.`,{action:F(Rd),probeAction:F(zd),durationMs:N(`Probe duration in milliseconds.`),bucketMs:N(`Audio level bucket size in milliseconds.`)}),Wd=B({name:`observability`,commands:[z({name:Nd,text:{summary:`Manage session app logs`},metadata:Bd,run:(e,t)=>e.observability.logs(t),cliSchema:{usageOverride:`logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]`,usageFlags:[],positionalArgs:[`path|start|stop|clear|doctor|mark`,`message?`],allowsExtraPositionals:!0,allowedFlags:[`restart`]},cliReader:(e,t)=>({...v(t),action:Yd(e[0]),message:e.slice(1).join(` `)||void 0,restart:t.restart}),daemonWriter:g(Nd,e=>Gd(e)),cliOutputFormatter:ud.logs}),z({name:Pd,text:{summary:`Read session event timeline`},metadata:Vd,run:(e,t)=>e.observability.events(t),cliSchema:{usageOverride:`events [limit] [cursor]`,listUsageOverride:`events`,positionalArgs:[`limit?`,`cursor?`]},cliReader:(e,t)=>({...v(t),limit:e[0]?.trim()?wr(e[0]):void 0,cursor:e[1]}),daemonWriter:e=>_(Pd,Kd(e),e),cliOutputFormatter:ud.events}),z({name:Fd,text:{summary:`Inspect HTTP(S) traffic from session logs`},metadata:Hd,run:(e,t)=>e.observability.network(t),cliSchema:{usageOverride:`network dump [limit] [summary|headers|body|all] [--include summary|headers|body|all] | network log [limit] [summary|headers|body|all] [--include summary|headers|body|all]`,usageFlags:[],listUsageOverride:`network`,positionalArgs:[`dump|log`,`limit?`,`include?`],allowedFlags:[`networkInclude`]},cliReader:(e,t)=>({...v(t),action:Xd(e[0]),limit:wr(e[1]),include:t.networkInclude??Zd(e[2])}),daemonWriter:e=>_(Fd,qd(e),{...e,networkInclude:e.include}),cliOutputFormatter:ud.network}),z({name:Id,text:{summary:`Probe audio levels`},metadata:Ud,run:(e,t)=>e.observability.audio(t),cliSchema:{usageOverride:`audio probe start [durationSeconds] [bucketMs] | audio probe status | audio probe stop`,listUsageOverride:`audio`,positionalArgs:[`probe`,`start|status|stop`,`durationSeconds?`,`bucketMs?`]},cliReader:(e,t)=>({...v(t),action:Qd(e[0]),probeAction:$d(e[1]),durationMs:ef(e[2]),bucketMs:wr(e[3])}),daemonWriter:e=>_(Id,Jd(e),e),cliOutputFormatter:ud.audio})]});function Gd(e){return[e.action??`path`,...y(e.message)]}function Kd(e){return e.cursor===void 0?b(e.limit):[e.limit===void 0?``:String(e.limit),e.cursor]}function qd(e){return[...e.action?[e.action]:[],...b(e.limit)]}function Jd(e){return[e.action??`probe`,e.probeAction??`status`,...b(e.durationMs),...b(e.bucketMs)]}function Yd(e){if(e!==void 0)return id(Tn,e,{message:`logs requires path, start, stop, doctor, mark, or clear`})}function Xd(e){if(e!==void 0){if(e===`dump`||e===`log`)return e;throw new n(`INVALID_ARGS`,`network requires dump or log`)}}function Zd(e){if(e!==void 0)return id(o,e,{message:`network include must be summary, headers, body, or all`})}function Qd(e){if(e!==void 0)return id(Rd,e,{message:`audio requires probe`})}function $d(e){if(e!==void 0)return id(zd,e,{message:`audio probe requires start, status, or stop`})}function ef(e){let t=wr(e);return t===void 0?void 0:Math.round(t*1e3)}function tf(e){let t=e;return{data:t,text:rf(t)}}const nf={perf:V(tf)};function rf(e){return df(e)??af(e)}function af(e){let t=u(e.artifact)?e.artifact:void 0;return t?uf(t):of(u(e.metrics)?e.metrics:void 0)}function of(e){return u(e?.fps)?cf(e):sf(e)??`Memory: unavailable - missing memory metric`}function sf(e){let t=u(e?.memory)?e.memory:void 0;if(!t)return;if(t.available===!1)return`Memory: unavailable - ${Cf(t)}`;let n=kf(t);return n?`Performance: ${n}`:`Memory: unavailable - missing memory metric`}function cf(e){let t=u(e?.fps)?e.fps:void 0;if(!t)return Sf(`missing frame metric`);if(t.available===!1)return Sf(Cf(t));let n=wf(t);return n?lf(t,n):Sf(`missing dropped-frame summary`)}function lf(e,t){let n=[`Frame health: ${t}`],r=Df(e);return r.length>0&&n.push(`Worst windows:`,...r),n.join(`
37
- `)}function uf(e){let t=typeof e.kind==`string`?e.kind:`memory`;if(e.available===!1)return`Memory artifact (${t}): unavailable - ${typeof e.reason==`string`&&e.reason.length>0?e.reason:`not available`}`;let n=typeof e.path==`string`?e.path:void 0,r=Q(e.sizeBytes),i=r===void 0?``:` (${Nf(r)})`;return n?`Memory artifact (${t}): ${n}${i}`:`Memory artifact (${t}): captured${i}`}function df(e){return e.kind===`xctrace`?ff(e):gf(e)}function ff(e){let t=typeof e.perf==`string`?e.perf:void 0,n=mf(e);if(!t||!n||e.kind!==`xctrace`)return;let r=hf(n,typeof e.mode==`string`?e.mode:`capture`,t,e.template),i=pf(e);return i.length>0?`${r}\nTop CPU self time:\n${i.join(`
38
- `)}`:r}function pf(e){let t=u(e.summary)?e.summary:void 0;return Array.isArray(t?.topFunctions)?t.topFunctions.slice(0,5).flatMap(e=>{if(!u(e))return[];let t=bf(e.symbol),n=Q(e.selfSamplePercent);if(!t||n===void 0)return[];let r=bf(e.binary);return[`- ${Af(n)} ${t}${r?` (${r})`:``}`]}):[]}function mf(e){return typeof e.outPath==`string`?e.outPath:typeof e.reportPath==`string`?e.reportPath:void 0}function hf(e,t,n,r){let i=[e,`Perf ${t}: ${n}`];return typeof r==`string`&&i.push(`Template: ${r}`),i.join(`
39
- `)}function gf(e){let t=_f(e);if(!t)return;let n=`Perf ${t.action}: ${t.kind} ${t.type}${vf(e)}${yf(e)}${xf(e)}`,r=pf(e);return r.length>0?`${n}\nTop CPU self time:\n${r.join(`
40
- `)}`:n}function _f(e){let t=bf(e.action),n=bf(e.kind),r=bf(e.type);return t&&n&&r?{action:t,kind:n,type:r}:void 0}function vf(e){let t=bf(e.state);return t?` state=${t}`:``}function yf(e){let t=bf(e.outPath);if(!t)return``;let n=Q(e.sizeBytes);return`\n${t}${n===void 0?``:` (${Nf(n)})`}`}function bf(e){return typeof e==`string`?e:void 0}function xf(e){let t=u(e.summary)?e.summary:void 0,n=u(t?.frameHealth)?t.frameHealth:void 0;if(!n||n.available!==!0)return``;let r=Q(n.droppedFramePercent),i=Q(n.droppedFrameCount),a=Q(n.totalFrameCount);return r===void 0||i===void 0||a===void 0?``:`\nTrace frame health: dropped ${Af(r)} (${Math.round(i)}/${Math.round(a)} frames)`}function Sf(e){return`Frame health: unavailable - ${e}`}function Cf(e){return typeof e.reason==`string`&&e.reason.length>0?e.reason:`not available`}function wf(e){let t=Q(e.droppedFramePercent),n=Q(e.droppedFrameCount);if(t!==void 0&&n!==void 0)return[`dropped ${Af(t)}`,Tf(n,Q(e.totalFrameCount)),Ef(Q(e.sampleWindowMs))].filter(Boolean).join(` `)}function Tf(e,t){return t===void 0?`(${Math.round(e)} dropped frames)`:`(${Math.round(e)}/${Math.round(t)} frames)`}function Ef(e){return e===void 0?``:`window ${jf(e)}`}function Df(e){return Array.isArray(e.worstWindows)?e.worstWindows.flatMap(e=>{if(!u(e))return[];let t=Of(e);return t?[t]:[]}):[]}function Of(e){let t=Q(e.startOffsetMs),n=Q(e.endOffsetMs),r=Q(e.missedDeadlineFrameCount);if(t===void 0||n===void 0||r===void 0)return;let i=Q(e.worstFrameMs),a=i===void 0?``:`, worst ${jf(i)}`;return`- +${jf(t)}-+${jf(n)}: ${Math.round(r)} missed-deadline frames${a}`}function kf(e){if(e?.available!==!0)return;let t=Q(e.residentMemoryKb)??Q(e.totalPssKb)??Q(e.totalRssKb);return t===void 0?void 0:`memory ${Mf(t)}`}function Q(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Af(e){return`${Number.isInteger(e)?e:e.toFixed(1)}%`}function jf(e){let t=Math.max(0,Math.round(e));if(t<1e3)return`${t}ms`;let n=Math.round(t/1e3);if(n<60)return`${n}s`;let r=Math.floor(n/60),i=n%60;return i>0?`${r}m ${i}s`:`${r}m`}function Mf(e){let t=e/1024;return`${t>=10?Math.round(t):t.toFixed(1)}MB`}function Nf(e){if(e<1024)return`${Math.round(e)}B`;let t=e/1024;if(t<1024)return`${t>=10?Math.round(t):t.toFixed(1)}KB`;let n=t/1024;return`${n>=10?Math.round(n):n.toFixed(1)}MB`}const Pf=`perf`,Ff=B({name:`perf`,commands:[z({name:Pf,text:{summary:`Check frames, memory, or native profiles`,cliDetail:`Use perf frames for bounded frame-health evidence and perf memory sample for a compact process-memory reading. On iOS simulators and macOS, process sampling and captures target the resolved app executable and exclude other copies with the same name. Apple xctrace and Android Simpleperf/Perfetto captures keep raw artifacts on disk; report produces bounded agent-readable evidence. For React render performance, run agent-device react-devtools profile start before the interaction and react-devtools profile stop after it.`,mcpDetail:`For CPU profiles, start and stop write the raw artifact while report writes a compact summary; request the report when the task needs readable native CPU evidence. Profiling output is evidence only: compact state, artifact path, and size.`},metadata:R(Pf,`Collect frame health, memory diagnostics, and platform profiling artifacts with compact agent-readable summaries.`,{area:A(F(en)),subject:F(an),action:F($t),kind:F(Kt),template:j(`xctrace template name, for example Time Profiler.`),out:j(`Output artifact path.`),tracePath:j(`Existing .trace path to report, defaults to the latest session trace.`)}),run:(e,t)=>e.observability.perf(t),cliSchema:{usageOverride:`perf frames --json
29
+ `)}}function Zc(e){return`source`in e&&e.source===`daemon`}async function Qc(e){let{serializeDeployResult:t}=await import(`./result-serialization.js`).then(e=>e.n);return bi(t(e))}async function $c(e){let{serializeInstallFromSourceResult:t}=await import(`./result-serialization.js`).then(e=>e.n);return bi(t(e))}function el(e){let t=e,n=t.platform??`unknown`;return{data:t,text:`Boot ready: ${t.device??t.id??`unknown`} (${n})${tl(t.selection)}`}}function tl(e){if(typeof e!=`object`||!e)return``;let{reason:t,candidateCount:n}=e;return t===`newest-bootable-local`?`, picked by --pick newest from ${n} matching devices`:``}function nl(e){let t=e,n=t.platform??`unknown`,r=t.device??t.id??`unknown`,i=t.shutdown;return{data:t,text:`${i&&typeof i==`object`&&`success`in i&&i.success===!0?`Shutdown`:`Shutdown failed`}: ${r} (${n})`}}async function rl(e,t,n){let{formatDoctorCheckDetailLines:r,formatDoctorCheckSummaryLine:i}=await import(`./doctor-lines.js`).then(e=>e.t),{shouldColorStatusMarkers:a}=await import(`./status-markers.js`).then(e=>e.r),o=a(t,!!process.stderr.isTTY),s=e,c=[`Doctor: ${typeof s.status==`string`?s.status:`unknown`}`],l=cl(s.checks);if(n?.renderedToStderr){let e=typeof s.summary==`string`?s.summary:void 0;e&&c.push(e)}else if(l.length===0){let e=typeof s.summary==`string`?s.summary:`No blockers found.`;c.push(e)}else for(let e of l)c.push(i(e,{useColor:o})),c.push(...r(e));return{data:s,text:c.join(`
30
+ `)}}const Z={boot:B(el),shutdown:B(nl),devices:B(Uc),capabilities:B(Wc),doctor:({result:e,env:t,progress:n})=>rl(e,t,n),apps:({input:e,result:t})=>Gc({result:t,appsFilter:e.appsFilter}),session:B(Kc),artifacts:B(Xc),open:B(qc),close:B(Yc),install:B(Qc),reinstall:B(Qc),"install-from-source":B($c),prepare:V,viewport:V};function il(e){let t=e.kind?` ${e.kind}`:``,n=e.target?` target=${e.target}`:``,r=e.model?` model=${JSON.stringify(e.model)}`:``,i=e.osVersion?` os=${e.osVersion}`:``,a=typeof e.booted==`boolean`?` booted=${e.booted}`:``,o=e.claimedBy?` claimed by session "${e.claimedBy.session}" in ${e.claimedBy.workspace}`:``;return`${e.name} (${e.platform}${t}${n}${r}${i})${a}${o}`}function al(e){let t=e.url?` ${e.url}`:``,n=e.availability?` ${e.availability}`:``;return`${e.kind}: ${e.name}${n}${t}`}function ol(e){let t=e.artifactType?` (${e.artifactType})`:``;return`${e.filename}${t}: ${e.mimeType} ${e.sizeBytes} bytes id=${e.id}`}function sl(e){if(e.providerSessionId)return`agent-device artifacts ${e.providerSessionId} --provider ${e.provider} --json`}function cl(e){return Array.isArray(e)?e.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):[]}const ll=R({name:`artifacts`,text:{summary:`List daemon or cloud provider session artifacts`},metadata:L(`artifacts`,`List daemon or cloud provider artifacts for an active or completed session.`,{provider:A(`Cloud provider name, for example browserstack, aws-device-farm, or testmu.`),providerSessionId:A(`Cloud provider session id or ARN.`)}),run:(e,t)=>e.sessions.artifacts(t),cliSchema:{usageOverride:`artifacts [provider-session-id]`,usageFlags:[`provider`],positionalArgs:[`provider-session-id?`],allowedFlags:[`provider`,`providerSessionId`]},cliReader:(e,t)=>({..._(t),provider:t.provider,providerSessionId:e[0]??t.providerSessionId}),daemonWriter:h(d.artifacts),cliOutputFormatter:Z.artifacts});function ul(e){let{metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i}=e;if(t!==void 0||n!==void 0||r!==void 0||i!==void 0)return{metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i}}function dl(e){let{metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i,...a}=e,o=ul({metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i});return o?{...a,runtime:o}:a}const fl=L(`apps`,`List the apps installed on the selected device. Include system or OEM apps only when they are needed as automation targets.`,{appsFilter:P([`user-installed`,`all`],`Restrict the listing to user-installed apps, or include system and OEM apps.`)}),pl=L(`open`,`Boot the selected device when needed, then open an app, deep link, or URL in a session. Use the app or URL inputs to choose what becomes the foreground automation target.`,{app:A(`App name, bundle id, package, or URL.`),url:A(`Optional URL passed with an app shell.`),surface:P(Gt,`macOS presentation surface to open: the app itself, the frontmost app, the desktop, or the menu bar.`),activity:A(`Android activity name.`),launchConsole:A(`File path on the daemon host for the stdout and stderr of the initial app launch. Local iOS simulator direct app launches only; not for URL opens.`),launchArgs:Gr(`Launch arguments forwarded verbatim to the platform launch command.`),relaunch:N(`Force relaunch.`),timeoutMs:M(`Startup budget in milliseconds. Bounds the Simulator boot wait, so a never-booted Simulator can finish its first-boot migration; omit for the default startup behavior.`,{min:1}),waitMs:Br(`waitMs`),foreground:Br(`foreground`),saveScript:F({oneOf:[D(),T()]}),force:N(`Overwrite an existing --save-script target instead of refusing (alias: --overwrite).`),testIme:N(`Activate the headless Android test IME for deterministic Unicode text entry (default on for emulators; opt-in on real devices).`),noRecord:N(`Do not record this action.`),metroHost:A(`Session-scoped Metro/debug host hint applied to the opened app.`),metroPort:M(`Session-scoped Metro/debug port hint applied to the opened app. On an emulator/simulator the host defaults to the loopback alias (Android 10.0.2.2, iOS 127.0.0.1) when --metro-host is omitted; physical devices still require an explicit --metro-host.`,{min:1,max:65535}),bundleUrl:A(`Session-scoped bundle URL hint applied to the opened app.`),launchUrl:A(`Launch URL for the opened app; does not select the server used by metro reload.`),...ei()}),ml=L(`close`,`Close the named app, or close the active session app when app is omitted. Use shutdown only when the selected simulator or emulator should also stop. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running.`,{app:A(`Optional app to close.`),shutdown:N(`Shutdown the session/device where supported.`),saveScript:F({oneOf:[D(),T()]}),force:N(`Overwrite an existing --save-script target instead of refusing (alias: --overwrite).`)});function hl(e){return dl(e)}const gl={allowedFlags:[`appsFilter`]},_l={positionalArgs:[`appOrUrl?`,`url?`],allowedFlags:[`activity`,`launchConsole`,`launchArgs`,`testIme`,`saveScript`,`force`,`noRecord`,`relaunch`,`foreground`,`timeoutMs`,`waitMs`,`surface`,...ra,`launchUrl`,...ia]},vl={positionalArgs:[`app?`],allowedFlags:[`saveScript`,`force`,`shutdown`]},yl=(e,t)=>({..._(t),appsFilter:Sn(t.appsFilter)}),bl=(e,t)=>({..._(t),app:e[0],url:e[1],surface:t.surface,activity:t.activity,launchConsole:t.launchConsole,launchArgs:t.launchArgs,relaunch:t.relaunch,foreground:t.foreground,timeoutMs:t.timeoutMs,waitMs:t.waitMs,saveScript:t.saveScript,force:t.force,testIme:t.testIme,noRecord:t.noRecord,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,launchUrl:t.launchUrl,...fr(t)}),xl=(e,t)=>({..._(t),app:e[0],shutdown:t.shutdown,saveScript:t.saveScript,force:t.force}),Sl=h(d.apps),Cl=h(d.open,kl),wl=h(d.close,e=>v(e.app)),Tl=R({name:`apps`,text:{summary:`List installed apps or deferred provider app assets`,cliDetail:`Before provider allocation, lists uploaded app assets when the selected provider exposes a catalog. On a live device, defaults to user-installed apps; use --all to include system/OEM apps.`},metadata:fl,run:(e,t)=>e.apps.list(t),cliSchema:gl,cliReader:yl,daemonWriter:Sl,cliOutputFormatter:Z.apps}),El=R({name:`open`,text:{summary:`Open an app, deep link or URL, save replays`,cliDetail:`Use --platform to bind URL/deep-link opens to the target platform. For local iOS simulator initial stdout/stderr, put --launch-console <path> on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app's Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app's launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+<slug> scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in <App>?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app's own alert (such as a permission prompt) rather than a translated launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app's target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. Only the English prompt title with Cancel and Open buttons is recognized, so on a Simulator set to another language the prompt stays on screen. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait <ms> to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session.`,mcpDetail:`metroHost, metroPort, and bundleUrl choose the app's Metro server and save its address for later reloads. launchUrl selects the app's launch URL and does not select the reload server. A fresh open without Metro hints clears an older same-name binding; close also clears it.`},metadata:pl,run:(e,t)=>e.apps.open(hl(t)),cliSchema:_l,cliReader:bl,daemonWriter:Cl,cliOutputFormatter:Z.open}),Dl=R({name:`close`,text:{summary:`Close an app or end the session`},metadata:ml,run:(e,t)=>t.app?e.apps.close(t):e.sessions.close(Ol(t)),cliSchema:vl,cliReader:xl,daemonWriter:wl,cliOutputFormatter:Z.close});function Ol(e){let{app:t,...n}=e;return n}function kl(e){return e.app?e.url?[e.app,e.url]:[e.app]:[]}const Al={platform:C(_t),target:C(vt),device:T(`Human-readable device name.`),id:T(`Stable device id.`),kind:C(gt)},jl=[`platform`,`target`,`device`,`id`,`kind`],Ml=S({success:D(),exitCode:E(),stdout:T(),stderr:T(),error:O(`Normalized error detail when shutdown failed.`)},[`success`,`exitCode`,`stdout`,`stderr`]),Nl={boot:S({...Al,booted:{type:`boolean`,const:!0},selection:S({reason:T(`Why this device was chosen, such as newest-bootable-local.`),source:T(`Where it came from: session, local, or provider.`),candidateCount:E(),bootOccurred:D()},[`reason`,`source`,`candidateCount`,`bootOccurred`])},[...jl,`booted`]),shutdown:S({...Al,shutdown:Ml},[...jl,`shutdown`])},Pl=L(`devices`,`List available devices and simulators that can be selected for automation. Use platform, device, udid, or serial inputs on later commands to target one result.`,{}),Fl=L(`capabilities`,`List the commands supported by the selected device or active session. Use device-selection inputs when checking support before a session is open.`,{}),Il=L(`boot`,`Boot or prepare the selected device or simulator so later commands can target it. The device is chosen through the device-selection inputs, not by naming it here.`,{headless:N(`Boot without showing simulator UI when supported.`),pick:P(yt,`When no device is named and several equally preferred devices match, all shut down, boot one instead of failing: newest picks mobile over TV, then the newest OS version, then the first name in name order (numbers compared by value; not device age), which alone decides for stopped Android AVDs because they report no OS version. Several booted matches still fail.`),timeoutMs:M(`Startup budget in milliseconds. Bounds the boot wait, so a never-booted Simulator can finish its first-boot migration or a cold emulator its boot; omit for the default startup behavior.`,{min:1})}),Ll=L(`shutdown`,`Shutdown a selected simulator or emulator.`,{}),Rl={allowedFlags:[`headless`,`pick`,`timeoutMs`]},zl={},Bl={},Vl={},Hl=(e,t)=>_(t),Ul=(e,t)=>({..._(t),headless:t.headless,pick:t.pick,timeoutMs:t.timeoutMs}),Wl=h(d.devices),Gl=h(d.capabilities),Kl=h(d.boot),ql=h(d.shutdown),Jl=[R({name:`devices`,text:{summary:`List available devices and simulators`},metadata:Pl,run:(e,t)=>e.devices.list(t),cliSchema:zl,cliReader:Hl,daemonWriter:Wl,cliOutputFormatter:Z.devices}),R({name:`capabilities`,text:{summary:`List supported commands for the selected device`,cliDetail:`Select an explicit target with --platform/--device/--udid/--serial.`},metadata:Fl,run:(e,t)=>e.devices.capabilities(t),cliSchema:Bl,cliReader:Hl,daemonWriter:Gl,cliOutputFormatter:Z.capabilities}),R({name:`boot`,text:{summary:`Boot target device/simulator`},metadata:Il,run:(e,t)=>e.devices.boot(t),cliSchema:Rl,cliReader:Ul,daemonWriter:Kl,cliOutputFormatter:Z.boot}),R({name:`shutdown`,text:{summary:`Shutdown target simulator/emulator`},metadata:Ll,run:(e,t)=>e.devices.shutdown(t),cliSchema:Vl,cliReader:Hl,daemonWriter:ql,cliOutputFormatter:Z.shutdown})],Yl={doctor:S({status:C([`pass`,`warn`,`fail`,`info`]),summary:T(),kind:C([`auto`,`react-native`,`expo`,`repack`]),platform:T(),target:C(vt),targetApp:T(),metro:S({host:T(),port:E()},[`host`,`port`]),checks:{type:`array`,items:S({id:T(),status:C([`pass`,`warn`,`fail`,`info`]),summary:T(),hint:T(),command:T(),evidence:O()},[`id`,`status`,`summary`])}},[`status`,`summary`,`kind`,`checks`])},Xl=R({name:`doctor`,text:{summary:`Diagnose device, app, dev-server, and RN/Expo readiness`,cliDetail:`Metro reachability is inferred from cwd/runtime. On iOS simulators it also warms the XCTest runner build cache in the background when missing. Pass --app to verify a target app on the one matching booted device without opening a session. Use --remote to check remote connection setup without probing local devices. Default output is compact; use --json for full checks and evidence.`,mcpDetail:`On iOS simulators it also warms the XCTest runner build cache in the background when missing, so run it before the first Apple snapshot or interaction of a session.`},metadata:L(`doctor`,`Diagnose device, app, development-server, and React Native or Expo readiness issues. Returns compact evidence for local inventory, sessions, optional app discovery, toolchains, and server reachability.`,{targetApp:A(`Installed app package/bundle id or app name to verify without opening a session.`),remote:N(`Check remote connection setup instead of local device inventory.`)}),run:(e,t)=>e.command.doctor(t),cliSchema:{usageOverride:`doctor [--platform ios|android|harmonyos|vega|macos|linux|web|apple]`,allowedFlags:[`targetApp`,`remote`]},cliReader:(e,t)=>({..._(t),targetApp:t.targetApp,remote:t.remote}),daemonWriter:h(d.doctor),cliOutputFormatter:Z.doctor});function Zl(e,t=`--github-actions-artifact`){let r=e.indexOf(`:`);if(r<=0||r===e.length-1)throw new n(`INVALID_ARGS`,`${t} must use owner/repo:artifact, for example thymikee/RNCLI83:6635342232`);let{owner:i,repo:a}=eu(e.slice(0,r),t);return $l(i,a,e.slice(r+1),`${t} artifact`)}function Ql(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`${t} installSource must be an object.`);let r=e;if(nu(r.type,`${t} installSource.type`)!==`github-actions-artifact`)throw new n(`INVALID_ARGS`,`${t} installSource.type must be "github-actions-artifact".`);let{owner:i,repo:a}=eu(nu(r.repo,`${t} installSource.repo`),`${t} installSource.repo`);return $l(i,a,r.artifact,`${t} installSource.artifact`)}function $l(e,t,n,r){return typeof n==`number`||iu(n)?{kind:`github-actions-artifact`,owner:e,repo:t,artifactId:ru(n,r)}:{kind:`github-actions-artifact`,owner:e,repo:t,artifactName:nu(n,r)}}function eu(e,t){let r=e.indexOf(`/`);if(r<=0||r===e.length-1||e.indexOf(`/`,r+1)!==-1)throw new n(`INVALID_ARGS`,`${t} must use owner/repo.`);let i={owner:e.slice(0,r).trim(),repo:e.slice(r+1).trim()};if(!i.owner||!i.repo)throw new n(`INVALID_ARGS`,`${t} must use owner/repo.`);return i}function tu(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function nu(e,t){let r=tu(e);if(!r)throw new n(`INVALID_ARGS`,`${t} must be a non-empty string.`);return r}function ru(e,t){let r=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;if(!Number.isInteger(r))throw new n(`INVALID_ARGS`,`${t} must be an integer.`);return r}function iu(e){return typeof e==`string`&&/^\d+$/.test(e.trim())}const au=L(`install`,`Install an app binary from a local path. Provide an app identifier with the path when the target needs explicit app selection; use reinstall to replace an already installed app.`,{app:A(`Optional app identifier hint.`),appPath:k(A(`Path to app binary.`)),...ei()}),ou=L(`reinstall`,`Replace an installed app with a binary from a local path. Use this when preserving the same app identity while installing a new build on the selected device.`,{app:k(A()),appPath:k(A(`Path to app binary.`)),...ei()}),su=L(`uninstall`,`Remove an installed app from the selected device. A package name or bundle id that is not installed succeeds with wasInstalled: false.`,{app:k(A(`Package name, bundle id, or installed app name.`)),...ei()}),cu=L(`install-from-source`,`Install app builds from URLs, remote source specs, or CI artifacts resolved by a remote daemon.`,{source:k(F(O(`Install source object.`))),retainPaths:N(),retentionMs:M()}),lu={usageOverride:`install <path> | install <app> <path>`,listUsageOverride:`install <path>`,positionalArgs:[`appOrPath`,`path?`],allowedFlags:ia},uu={positionalArgs:[`app`,`path`],allowedFlags:ia},du={positionalArgs:[`app`],allowedFlags:ia},fu={usageOverride:`install-from-source <url> | install-from-source --github-actions-artifact <owner/repo:artifact>`,usageFlags:[],listUsageOverride:`install-from-source`,positionalArgs:[`url?`],allowedFlags:[`header`,`githubActionsArtifact`,`installSource`,`retainPaths`,`retentionMs`]},pu=(e,t)=>xu(e,t),mu=(e,t)=>Su(e,t),hu=(e,t)=>({..._(t),app:b(e[0],`uninstall requires app`),...fr(t)}),gu=(e,t)=>({..._(t),source:Tu(e,t),retainPaths:t.retainPaths,retentionMs:t.retentionMs}),_u=h(d.install,e=>Cu(e.app,e.appPath)),vu=h(d.reinstall,e=>wu(e.app,e.appPath)),yu=h(d.uninstall,e=>[x(e.app,`missing app`)]),bu=[R({name:`install`,text:{summary:`Install an app binary from a path`},metadata:au,run:(e,t)=>e.apps.install(t),cliSchema:lu,cliReader:pu,daemonWriter:_u,cliOutputFormatter:Z.install}),R({name:`reinstall`,text:{summary:`Replace an installed app with a new build`},metadata:ou,run:(e,t)=>e.apps.reinstall(t),cliSchema:uu,cliReader:mu,daemonWriter:vu,cliOutputFormatter:Z.reinstall}),R({name:`uninstall`,text:{summary:`Remove an installed app`},metadata:su,run:(e,t)=>e.apps.uninstall(t),cliSchema:du,cliReader:hu,daemonWriter:yu}),R({name:`install-from-source`,text:{summary:`Install app builds from URLs or CI artifacts`},metadata:cu,run:(e,t)=>e.apps.installFromSource(t),cliSchema:fu,cliReader:gu,daemonWriter:e=>g(Xe.installSource,[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),cliOutputFormatter:Z[`install-from-source`]})];function xu(e,t){let[n,r]=e,i=r!==void 0;return{..._(t),...i?{app:b(n,`install requires app`)}:{},appPath:b(i?r:n,`install requires path`),...fr(t)}}function Su(e,t){return{..._(t),app:b(e[0],`reinstall requires app`),appPath:b(e[1],`reinstall requires path`),...fr(t)}}function Cu(e,t){let n=x(t,`missing app path`);return typeof e==`string`&&e.length>0?[e,n]:[n]}function wu(e,t){return[x(e,`missing first positional`),x(t,`missing second positional`)]}function Tu(e,t){let r=e[0]?.trim();if(e.length>1)throw new n(`INVALID_ARGS`,`install-from-source accepts either one <url> positional or --github-actions-artifact`);let i=t.githubActionsArtifact?Zl(t.githubActionsArtifact):void 0,a=t.installSource;if(+!!r+ +!!i+ +!!a!=1)throw new n(`INVALID_ARGS`,`install-from-source requires exactly one source: <url>, --github-actions-artifact, or config installSource`);if(!r&&t.header&&t.header.length>0)throw new n(`INVALID_ARGS`,`install-from-source --header is only supported for URL sources`);if(i)return i;if(a)return a;if(!Eu(r))throw new n(`INVALID_ARGS`,`install-from-source <url> must be an http(s) URL: ${r}`,{hint:`Install a local build with install <app> <path>.`});return{kind:`url`,url:r,headers:Du(t.header)}}function Eu(e){let t=URL.parse(e)?.protocol;return t===`http:`||t===`https:`}function Du(e){if(!e||e.length===0)return;let t={};for(let r of e){let e=r.indexOf(`:`);if(e<=0)throw new n(`INVALID_ARGS`,`Invalid --header value "${r}". Expected "name:value".`);let i=r.slice(0,e).trim(),a=r.slice(e+1).trim();if(!i)throw new n(`INVALID_ARGS`,`Invalid --header value "${r}". Header name cannot be empty.`);t[i]=a}return t}const Ou=[`ios-runner`],ku={prepare:S({action:w(`ios-runner`),platform:C(_t),deviceId:T(),deviceName:T(),kind:C(gt),durationMs:E(),runner:S({},[]),cache:C([`exact`,`miss`,`external`]),artifact:C([`valid`,`rebuilt`]),buildMs:E(),connectMs:E(),healthCheckMs:E(),xctestrunPath:T(),recoveryReason:T(),failureReason:T(),timing:S({totalMs:E(),additiveParts:S({buildMs:E(),connectAfterBuildMs:E(),healthCheckMs:E()},[`connectAfterBuildMs`,`healthCheckMs`]),containment:S({connectMs:{type:`array`,items:w(`buildMs`)},healthCheckMs:{type:`array`,items:T()}},[`healthCheckMs`]),note:T()},[`totalMs`,`additiveParts`,`containment`,`note`]),message:T()},[`action`,`platform`,`deviceId`,`deviceName`,`kind`,`durationMs`,`runner`,`connectMs`,`healthCheckMs`,`timing`,`message`])},Au=R({name:`prepare`,text:{summary:`Pre-warm platform helpers before automation`},metadata:L(`prepare`,`Prepare platform helper infrastructure. ios-runner builds/reuses, starts, and health-checks the XCTest runner so later Apple snapshots and interactions do not pay first-use startup cost. In JSON output, top-level buildMs/connectMs/healthCheckMs are diagnostic fields and may overlap; use timing.additiveParts for additive wall-clock phase totals. In CI, run it after boot/install and before replay/test; if replay/test starts a separate daemon, stop the prepare daemon before replay/test so it does not keep the prepared runner lease. It is not a recovery step for "runner already owned by another agent-device daemon"; stop the owning daemon on the Mac with simulator access instead. Runner build/start output is written to the session runner.log; daemon.log is for daemon lifecycle/startup issues.`,{action:k(P(Ou)),timeoutMs:M(`Maximum wall-clock time for the prepare command.`)}),run:(e,t)=>e.command.prepare(t),cliSchema:{usageOverride:`prepare ios-runner --platform ios|macos`,listUsageOverride:`prepare`,positionalArgs:[`ios-runner`],allowedFlags:[`timeoutMs`]},cliReader:(e,t)=>({..._(t),action:b(e[0],`prepare requires subcommand`),timeoutMs:t.timeoutMs}),daemonWriter:h(d.prepare,e=>[x(e.action,`prepare requires subcommand`)]),cliOutputFormatter:Z.prepare}),ju={push:{type:`object`,oneOf:[S({platform:w(`ios`),bundleId:T(),message:T()},[`platform`,`bundleId`,`message`]),S({platform:w(`android`),package:T(),action:T(),extrasCount:E(),message:T()},[`platform`,`package`,`action`,`extrasCount`,`message`])]},"trigger-app-event":S({event:T(),eventUrl:T(),transport:w(`deep-link`),message:T()},[`event`,`eventUrl`,`transport`,`message`])},Mu=L(`push`,`Deliver push notification payloads to an installed app.`,{app:k(A()),payload:k(F({oneOf:[T(),O()]}))}),Nu=L(`trigger-app-event`,`Ask the app to handle an app-defined automation or test event, with an optional structured payload. Call this only for event names and payload shapes the app documents.`,{event:k(A(`Name of an app-defined automation or test event the app documents.`)),payload:Uu(`Structured payload passed to the event, in the shape the app documents for it.`)}),Pu={listUsageOverride:`push`,positionalArgs:[`bundleOrPackage`,`payloadOrJson`]},Fu={usageOverride:`trigger-app-event <event> [payloadJson]`,listUsageOverride:`trigger-app-event`,positionalArgs:[`event`,`payloadJson?`]},Iu=(e,t)=>({..._(t),app:b(e[0],`push requires bundleOrPackage`),payload:b(e[1],`push requires payloadOrJson`)}),Lu=(e,t)=>({..._(t),event:b(e[0],`trigger-app-event requires event`),payload:e[1]?Sr(e[1],`trigger-app-event payload`):void 0}),Ru=h(d.push,e=>Vu(e)),zu=h(d.triggerAppEvent,e=>Hu(e)),Bu=[R({name:`push`,text:{summary:`Deliver a push notification payload`},metadata:Mu,run:(e,t)=>e.apps.push(t),cliSchema:Pu,cliReader:Iu,daemonWriter:Ru}),R({name:`trigger-app-event`,text:{summary:`Invoke an app-defined automation event`},metadata:Nu,run:(e,t)=>e.apps.triggerEvent(t),cliSchema:Fu,cliReader:Lu,daemonWriter:zu})];function Vu(e){return[e.app,typeof e.payload==`string`?e.payload:JSON.stringify(e.payload)]}function Hu(e){return[e.event,...e.payload?[JSON.stringify(e.payload)]:[]]}function Uu(e){return Wr(e)}const Wu=R({name:`session`,text:{summary:`List sessions, show the state dir, or publish a script`},metadata:L(`session`,`List active sessions, print the effective daemon state directory, or publish an armed open-to-destination script without closing its session`,{action:P([`list`,`state-dir`,`save-script`],`list shows active sessions; state-dir prints the daemon state directory; save-script publishes an armed recording without teardown.`),path:A(`Optional .ad output path for save-script.`),force:N(`Atomically replace an existing save-script target.`)}),run:async(e,{action:t,path:n,force:r,...i})=>{let a=t??`list`;return Ku(a,n,r),a===`state-dir`?{stateDir:await e.sessions.stateDir(i)}:a===`save-script`?await e.sessions.saveScript({...i,path:n,force:r}):{sessions:await e.sessions.list(i)}},cliSchema:{usageOverride:`session list | session state-dir | session save-script [path] [--force]`,usageFlags:[],listUsageOverride:`session`,positionalArgs:[`list|state-dir|save-script?`,`path?`],allowedFlags:[`force`]},cliReader:(e,t)=>({..._(t),action:Gu(e[0]),path:e[1],force:t.force}),cliOutputFormatter:Z.session});function Gu(e){let t=e??`list`;if(t===`list`||t===`state-dir`||t===`save-script`)return t;throw new n(`INVALID_ARGS`,`session only supports list, state-dir, or save-script`)}function Ku(e,t,r){if(e!==`save-script`&&(t!==void 0||r===!0))throw new n(`INVALID_ARGS`,`session ${e} does not accept a path or --force; use session save-script [path] [--force] to publish a recording.`)}const qu={viewport:S({width:E(),height:E(),message:T()},[`width`,`height`,`message`])},Ju=R({name:`viewport`,text:{summary:`Resize the active web viewport for the current session`},metadata:L(`viewport`,`Resize the active web viewport before taking snapshots or screenshots. Useful for fixed-layout or 100vh apps where changing the viewport reveals different content.`,{width:k(M(`Viewport width in CSS pixels.`,{min:1})),height:k(M(`Viewport height in CSS pixels.`,{min:1}))}),run:(e,t)=>e.command.viewport(t),cliSchema:{positionalArgs:[`width`,`height`]},cliReader:(e,t)=>({..._(t),...qe(e)}),daemonWriter:h(d.viewport,e=>{let{width:t,height:n}=e;return[String(t),String(n)]}),cliOutputFormatter:Z.viewport}),Yu=z({name:`management`,commands:[...Jl,ll,Xl,Au,Tl,Wu,El,Dl,Ju,...bu,...Bu]});function Xu(e){return{data:e.result,text:e.action===`reload`?`Reloaded React Native apps via ${e.result.reloadUrl}`:JSON.stringify(e.result,null,2)}}const Zu={metro:({input:e,result:t})=>Xu({result:t,action:e.action})},Qu=[`auto`,`react-native`,`expo`,`repack`];function $u(e){if(e!==void 0){if(Qu.includes(e))return e;throw new n(`INVALID_ARGS`,`metro prepare --kind must be auto, react-native, expo, or repack`)}}const ed=`metro`,td=z({name:`metro`,commands:[R({name:ed,text:{summary:`Prepare the dev server or reload apps`,cliDetail:`reload with no --metro-host/--metro-port/--bundle-url resolves against the dev server this session last bound via metro prepare or open's metro hint flags (falling back to localhost:8081 only when the session never bound one), so it never silently reloads a different project's server on the default port; pass an explicit flag to override the session hint for one call. After prepare, reload uses the local server address independently of the public or proxy address given to the device; a fresh open preserves it only when its client-config runtime points to the prepared device server, while explicit reload flags override it. For open or an explicit bundle URL, reload removes a .bundle/.jsbundle/.js entry filename and keeps the remaining path as the server mount, and when the server has no HTTP /reload route (Expo) the reload is broadcast over its /message websocket instead of trusting the app-page fallback. The binding is cleared when the session closes, and a fresh open without hint flags also clears any leftover binding from a previous same-name session. --kind expo (detected or forced) requests the virtual-entry bundle URL (.expo/.virtual-metro-entry.bundle) instead of index.bundle, since index.bundle 404s/500s against Expo dev servers in monorepos. Dependency install auto-detects the package manager from the nearest yarn.lock/pnpm-lock.yaml/bun.lock/bun.lockb/package-lock.json walking up from --project-root (bounded at the repo root), so Yarn/pnpm workspace monorepos with the lockfile at the repo root do not wrongly fall back to npm install (which fails on workspace: dependency specifiers); if install still fails, pass --no-install-deps when dependencies are already installed (for example via a monorepo root install).`,mcpDetail:`The binding is cleared when the session closes, and a fresh open without runtime hints also clears any leftover binding from a previous same-name session.`},metadata:L(ed,`Prepare a React Native development server or ask connected apps to reload, using the development server this session is bound to. Provide explicit runtime inputs only to override that binding for one call.`,{action:k(P([`prepare`,`reload`])),projectRoot:A(),kind:F(T()),publicBaseUrl:A(),proxyBaseUrl:zr(A(),{operatorPath:`Configure the remote proxy in the remote-config profile or operator config for the process serving these tools.`}),bearerToken:zr(A(),{envFlagKeys:[`metroBearerToken`,`daemonAuthToken`]}),bridgeScope:F({type:`object`,additionalProperties:!0}),launchUrl:A(),port:M(),listenHost:A(),statusHost:A(),startupTimeoutMs:M(),probeTimeoutMs:M(),reuseExisting:N(),installDependenciesIfNeeded:N(),runtimeFilePath:A(),logPath:A(),metroHost:A(),metroPort:M(),bundleUrl:A(),timeoutMs:M()}),run:async(e,t)=>t.action===`prepare`?await e.metro.prepare(nd(t)):await e.metro.reload(id(t)),cliSchema:{usageOverride:`metro prepare (--public-base-url <url> | --proxy-base-url <url>) [--project-root <path>] [--port <port>] [--kind auto|react-native|expo|repack]
31
+ agent-device metro reload [--metro-host <host>] [--metro-port <port>] [--bundle-url <url>]`,usageFlags:[],listUsageOverride:`metro`,positionalArgs:[`prepare|reload`],allowedFlags:[...ra,...na]},cliReader:(e,t)=>{let r=(e[0]??``).toLowerCase();if(r!==`prepare`&&r!==`reload`)throw new n(`INVALID_ARGS`,`metro requires a subcommand: prepare or reload`);if(r===`reload`)return{action:r,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,timeoutMs:t.metroProbeTimeoutMs};if(!t.metroPublicBaseUrl&&!t.metroProxyBaseUrl)throw new n(`INVALID_ARGS`,`metro prepare requires --public-base-url <url> or --proxy-base-url <url>.`);return{action:r,projectRoot:t.metroProjectRoot,kind:$u(t.kind??t.metroKind),port:t.metroPreparePort,listenHost:t.metroListenHost,statusHost:t.metroStatusHost,publicBaseUrl:t.metroPublicBaseUrl,proxyBaseUrl:t.metroProxyBaseUrl,bearerToken:t.metroBearerToken,bridgeScope:t.tenant&&t.runId&&t.leaseId?{tenantId:t.tenant,runId:t.runId,leaseId:t.leaseId}:void 0,startupTimeoutMs:t.metroStartupTimeoutMs,probeTimeoutMs:t.metroProbeTimeoutMs,reuseExisting:!t.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!t.metroNoInstallDeps&&void 0,runtimeFilePath:t.metroRuntimeFile}},cliOutputFormatter:Zu.metro})]});function nd(e){return{projectRoot:e.projectRoot,kind:e.kind,publicBaseUrl:e.publicBaseUrl,proxyBaseUrl:e.proxyBaseUrl,bearerToken:e.bearerToken,bridgeScope:e.bridgeScope??rd(e),port:e.port,listenHost:e.listenHost,statusHost:e.statusHost,startupTimeoutMs:e.startupTimeoutMs,probeTimeoutMs:e.probeTimeoutMs,reuseExisting:e.reuseExisting,installDependenciesIfNeeded:e.installDependenciesIfNeeded,runtimeFilePath:e.runtimeFilePath}}function rd(e){return e.tenant&&e.runId&&e.leaseId?{tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId}:void 0}function id(e){return{metroHost:e.metroHost,metroPort:e.metroPort,bundleUrl:e.bundleUrl,timeoutMs:e.timeoutMs}}function ad(e,t){return e.includes(t)}function od(e,t,r={}){let i=t===void 0?void 0:r.normalize?.(t)??t;if(i!==void 0&&ad(e,i))return i;let a=typeof r.message==`function`?r.message(t):r.message;throw new n(`INVALID_ARGS`,a??`Invalid value: ${t}. Use ${e.join(`|`)}.`)}const sd=[`started`,`stopped`,`marked`,`cleared`,`restarted`,`removedRotatedFiles`];function cd(e){return{data:e,text:e.path,stderr:Pd([Md(e,[`active`,`state`,`backend`,`sizeBytes`]),Md(e,sd),e.hint,Nd(e.notes)])}}function ld(e){let t=e.events??[];return{data:e,text:t.length>0?pd(t):`No session events found.`,stderr:Pd([Md(e,[`path`,`cursor`,`nextCursor`,`limit`])])}}function ud(e){let t=[],n=e.entries??[];if(e.path&&t.push(e.path),n.length===0)t.push(`No recent HTTP(s) entries found.`);else for(let e of n)t.push(...kd(e));return{data:e,text:t.join(`
32
+ `),stderr:Pd([Md(e,[`active`,`state`,`backend`,`include`,`scannedLines`,`matchedLines`]),Nd(e.notes)])}}function dd(e){return{data:e,text:[`Audio probe: ${String(e.state??`stopped`)} heard=${String(e.heard===!0)}`,Td(`rmsDbfs`,e.rmsDbfs),Td(`peakDbfs`,e.peakDbfs)].filter(e=>!!e).join(`
33
+ `),stderr:Pd([Md(e,[`active`,`backend`,`source`,`durationMs`,`elapsedMs`,`bucketMs`,`sampleCount`,`sourceCount`,`mediaElementCount`]),Nd(e.notes)])}}const fd={logs:B(cd),events:B(ld),network:B(ud),audio:B(dd)};function pd(e){let t=e.map(md),n=Math.min(Math.max(...t.map(e=>e.label.length),5),32);return t.map(e=>hd(e,n)).join(`
34
+ `)}function md(e){return{timestamp:gd(e.ts),label:_d(e),summary:vd(e)}}function hd(e,t){let n=e.label.padEnd(t),r=e.timestamp?`${e.timestamp} ${n}`:n.trimEnd();return e.summary?`${r} ${e.summary}`:r.trimEnd()}function gd(e){return e?e.replace(`T`,` `):``}function _d(e){let t=e.command??`command`;switch(e.kind){case`request.started`:return`start ${t}`;case`request.finished`:return Ed([e.status===`error`?`error`:`ok`,t,wd(Od(e.details?.durationMs))]);case`action.recorded`:return`action ${t}`;default:return Ed([e.kind??`event`,e.command])}}function vd(e){let t=yd(e.summary,e);return`${t}${bd(e,t)}`.trim()}function yd(e,t){let n=e?.trim()??``,r=t.command??``;return t.kind===`request.started`&&n===`Started ${r}`||t.kind===`request.finished`&&n===`Finished ${r}`?``:n}function bd(e,t){if(e.kind!==`action.recorded`)return``;let n=e.details;if(!n)return``;let r=[xd(n,t),Cd(Od(n.textLength))].filter(e=>!!e);return r.length>0?` (${r.join(`, `)})`:``}function xd(e,t){let n=Dd(e.ref)??Dd(e.selector)??Sd(e);if(!(!n||t.includes(n)))return`target=${n}`}function Sd(e){let t=Od(e.x),n=Od(e.y);return t===void 0||n===void 0?void 0:`(${t}, ${n})`}function Cd(e){return e===void 0?void 0:`text=${e} chars`}function wd(e){return e===void 0?void 0:`${Math.round(e)}ms`}function Td(e,t){if(!Array.isArray(t))return;let n=t.filter(e=>typeof e==`number`&&Number.isFinite(e));return n.length>0?`${e}: [${n.join(`, `)}]`:void 0}function Ed(e){return e.filter(e=>!!e).join(` `)}function Dd(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function Od(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function kd(e){let t=e.method??`HTTP`,n=e.url??`<unknown-url>`,r=e.status===void 0?``:` status=${e.status}`,i=e.timestamp?`${e.timestamp} `:``,a=e.durationMs===void 0?``:` durationMs=${e.durationMs}`,o=[`${i}${t} ${n}${`pathUnavailable`in e&&e.pathUnavailable?` (request path not logged)`:``}${r}${a}`];return e.headers?jd(o,`headers`,e.headers):(Ad(o,`request headers`,e.requestHeaders),Ad(o,`response headers`,e.responseHeaders)),jd(o,`request`,e.requestBody),jd(o,`response`,e.responseBody),o}function Ad(e,t,n){!n||Object.keys(n).length===0||e.push(` ${t}: ${JSON.stringify(n)}`)}function jd(e,t,n){n!==void 0&&e.push(` ${t}: ${n}`)}function Md(e,t){return t.map(t=>e[t]!==void 0&&e[t]!==null?`${t}=${e[t]}`:``).filter(Boolean).join(` `)||void 0}function Nd(e){let t=e?.filter(e=>e.length>0)??[];return t.length>0?t.join(`
35
+ `):void 0}function Pd(e){return e.filter(e=>!!e).join(`
36
+ `)||void 0}const Fd=`logs`,Id=`events`,Ld=`network`,Rd=`audio`,zd=[`dump`,`log`],Bd=[`probe`],Vd=[`start`,`status`,`stop`],Hd=L(Fd,`Session app log info, start/stop streaming, diagnostics, and markers`,{action:P(En),message:A(),restart:N()}),Ud=L(Id,`Read the daemon-owned session event timeline as paged JSON-friendly entries`,{limit:M(),cursor:A()}),Wd=L(Ld,`Dump recent HTTP(s) traffic parsed from the session app log`,{action:P(zd),limit:M(),include:P(o)}),Gd=L(Rd,`Measure browser or host-rendered simulator/emulator audio as compact dBFS buckets. Start a probe before requesting its status or stopping it.`,{action:P(Bd),probeAction:P(Vd),durationMs:M(`Probe duration in milliseconds.`),bucketMs:M(`Audio level bucket size in milliseconds.`)}),Kd=z({name:`observability`,commands:[R({name:Fd,text:{summary:`Manage session app logs`},metadata:Hd,run:(e,t)=>e.observability.logs(t),cliSchema:{usageOverride:`logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]`,usageFlags:[],positionalArgs:[`path|start|stop|clear|doctor|mark`,`message?`],allowsExtraPositionals:!0,allowedFlags:[`restart`]},cliReader:(e,t)=>({..._(t),action:Zd(e[0]),message:e.slice(1).join(` `)||void 0,restart:t.restart}),daemonWriter:h(Fd,e=>qd(e)),cliOutputFormatter:fd.logs}),R({name:Id,text:{summary:`Read session event timeline`},metadata:Ud,run:(e,t)=>e.observability.events(t),cliSchema:{usageOverride:`events [limit] [cursor]`,listUsageOverride:`events`,positionalArgs:[`limit?`,`cursor?`]},cliReader:(e,t)=>({..._(t),limit:e[0]?.trim()?Er(e[0]):void 0,cursor:e[1]}),daemonWriter:e=>g(Id,Jd(e),e),cliOutputFormatter:fd.events}),R({name:Ld,text:{summary:`Inspect HTTP(S) traffic from session logs`},metadata:Wd,run:(e,t)=>e.observability.network(t),cliSchema:{usageOverride:`network dump [limit] [summary|headers|body|all] [--include summary|headers|body|all] | network log [limit] [summary|headers|body|all] [--include summary|headers|body|all]`,usageFlags:[],listUsageOverride:`network`,positionalArgs:[`dump|log`,`limit?`,`include?`],allowedFlags:[`networkInclude`]},cliReader:(e,t)=>({..._(t),action:Qd(e[0]),limit:Er(e[1]),include:t.networkInclude??$d(e[2])}),daemonWriter:e=>g(Ld,Yd(e),{...e,networkInclude:e.include}),cliOutputFormatter:fd.network}),R({name:Rd,text:{summary:`Probe audio levels`},metadata:Gd,run:(e,t)=>e.observability.audio(t),cliSchema:{usageOverride:`audio probe start [durationSeconds] [bucketMs] | audio probe status | audio probe stop`,listUsageOverride:`audio`,positionalArgs:[`probe`,`start|status|stop`,`durationSeconds?`,`bucketMs?`]},cliReader:(e,t)=>({..._(t),action:ef(e[0]),probeAction:tf(e[1]),durationMs:nf(e[2]),bucketMs:Er(e[3])}),daemonWriter:e=>g(Rd,Xd(e),e),cliOutputFormatter:fd.audio})]});function qd(e){return[e.action??`path`,...v(e.message)]}function Jd(e){return e.cursor===void 0?y(e.limit):[e.limit===void 0?``:String(e.limit),e.cursor]}function Yd(e){return[...e.action?[e.action]:[],...y(e.limit)]}function Xd(e){return[e.action??`probe`,e.probeAction??`status`,...y(e.durationMs),...y(e.bucketMs)]}function Zd(e){if(e!==void 0)return od(En,e,{message:`logs requires path, start, stop, doctor, mark, or clear`})}function Qd(e){if(e!==void 0){if(e===`dump`||e===`log`)return e;throw new n(`INVALID_ARGS`,`network requires dump or log`)}}function $d(e){if(e!==void 0)return od(o,e,{message:`network include must be summary, headers, body, or all`})}function ef(e){if(e!==void 0)return od(Bd,e,{message:`audio requires probe`})}function tf(e){if(e!==void 0)return od(Vd,e,{message:`audio probe requires start, status, or stop`})}function nf(e){let t=Er(e);return t===void 0?void 0:Math.round(t*1e3)}function rf(e){let t=e;return{data:t,text:of(t)}}const af={perf:B(rf)};function of(e){return pf(e)??sf(e)}function sf(e){let t=u(e.artifact)?e.artifact:void 0;return t?ff(t):cf(u(e.metrics)?e.metrics:void 0)}function cf(e){return u(e?.fps)?uf(e):lf(e)??`Memory: unavailable - missing memory metric`}function lf(e){let t=u(e?.memory)?e.memory:void 0;if(!t)return;if(t.available===!1)return`Memory: unavailable - ${Tf(t)}`;let n=jf(t);return n?`Performance: ${n}`:`Memory: unavailable - missing memory metric`}function uf(e){let t=u(e?.fps)?e.fps:void 0;if(!t)return wf(`missing frame metric`);if(t.available===!1)return wf(Tf(t));let n=Ef(t);return n?df(t,n):wf(`missing dropped-frame summary`)}function df(e,t){let n=[`Frame health: ${t}`],r=kf(e);return r.length>0&&n.push(`Worst windows:`,...r),n.join(`
37
+ `)}function ff(e){let t=typeof e.kind==`string`?e.kind:`memory`;if(e.available===!1)return`Memory artifact (${t}): unavailable - ${typeof e.reason==`string`&&e.reason.length>0?e.reason:`not available`}`;let n=typeof e.path==`string`?e.path:void 0,r=Q(e.sizeBytes),i=r===void 0?``:` (${Ff(r)})`;return n?`Memory artifact (${t}): ${n}${i}`:`Memory artifact (${t}): captured${i}`}function pf(e){return e.kind===`xctrace`?mf(e):vf(e)}function mf(e){let t=typeof e.perf==`string`?e.perf:void 0,n=gf(e);if(!t||!n||e.kind!==`xctrace`)return;let r=_f(n,typeof e.mode==`string`?e.mode:`capture`,t,e.template),i=hf(e);return i.length>0?`${r}\nTop CPU self time:\n${i.join(`
38
+ `)}`:r}function hf(e){let t=u(e.summary)?e.summary:void 0;return Array.isArray(t?.topFunctions)?t.topFunctions.slice(0,5).flatMap(e=>{if(!u(e))return[];let t=Sf(e.symbol),n=Q(e.selfSamplePercent);if(!t||n===void 0)return[];let r=Sf(e.binary);return[`- ${Mf(n)} ${t}${r?` (${r})`:``}`]}):[]}function gf(e){return typeof e.outPath==`string`?e.outPath:typeof e.reportPath==`string`?e.reportPath:void 0}function _f(e,t,n,r){let i=[e,`Perf ${t}: ${n}`];return typeof r==`string`&&i.push(`Template: ${r}`),i.join(`
39
+ `)}function vf(e){let t=yf(e);if(!t)return;let n=`Perf ${t.action}: ${t.kind} ${t.type}${bf(e)}${xf(e)}${Cf(e)}`,r=hf(e);return r.length>0?`${n}\nTop CPU self time:\n${r.join(`
40
+ `)}`:n}function yf(e){let t=Sf(e.action),n=Sf(e.kind),r=Sf(e.type);return t&&n&&r?{action:t,kind:n,type:r}:void 0}function bf(e){let t=Sf(e.state);return t?` state=${t}`:``}function xf(e){let t=Sf(e.outPath);if(!t)return``;let n=Q(e.sizeBytes);return`\n${t}${n===void 0?``:` (${Ff(n)})`}`}function Sf(e){return typeof e==`string`?e:void 0}function Cf(e){let t=u(e.summary)?e.summary:void 0,n=u(t?.frameHealth)?t.frameHealth:void 0;if(!n||n.available!==!0)return``;let r=Q(n.droppedFramePercent),i=Q(n.droppedFrameCount),a=Q(n.totalFrameCount);return r===void 0||i===void 0||a===void 0?``:`\nTrace frame health: dropped ${Mf(r)} (${Math.round(i)}/${Math.round(a)} frames)`}function wf(e){return`Frame health: unavailable - ${e}`}function Tf(e){return typeof e.reason==`string`&&e.reason.length>0?e.reason:`not available`}function Ef(e){let t=Q(e.droppedFramePercent),n=Q(e.droppedFrameCount);if(t!==void 0&&n!==void 0)return[`dropped ${Mf(t)}`,Df(n,Q(e.totalFrameCount)),Of(Q(e.sampleWindowMs))].filter(Boolean).join(` `)}function Df(e,t){return t===void 0?`(${Math.round(e)} dropped frames)`:`(${Math.round(e)}/${Math.round(t)} frames)`}function Of(e){return e===void 0?``:`window ${Nf(e)}`}function kf(e){return Array.isArray(e.worstWindows)?e.worstWindows.flatMap(e=>{if(!u(e))return[];let t=Af(e);return t?[t]:[]}):[]}function Af(e){let t=Q(e.startOffsetMs),n=Q(e.endOffsetMs),r=Q(e.missedDeadlineFrameCount);if(t===void 0||n===void 0||r===void 0)return;let i=Q(e.worstFrameMs),a=i===void 0?``:`, worst ${Nf(i)}`;return`- +${Nf(t)}-+${Nf(n)}: ${Math.round(r)} missed-deadline frames${a}`}function jf(e){if(e?.available!==!0)return;let t=Q(e.residentMemoryKb)??Q(e.totalPssKb)??Q(e.totalRssKb);return t===void 0?void 0:`memory ${Pf(t)}`}function Q(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Mf(e){return`${Number.isInteger(e)?e:e.toFixed(1)}%`}function Nf(e){let t=Math.max(0,Math.round(e));if(t<1e3)return`${t}ms`;let n=Math.round(t/1e3);if(n<60)return`${n}s`;let r=Math.floor(n/60),i=n%60;return i>0?`${r}m ${i}s`:`${r}m`}function Pf(e){let t=e/1024;return`${t>=10?Math.round(t):t.toFixed(1)}MB`}function Ff(e){if(e<1024)return`${Math.round(e)}B`;let t=e/1024;if(t<1024)return`${t>=10?Math.round(t):t.toFixed(1)}KB`;let n=t/1024;return`${n>=10?Math.round(n):n.toFixed(1)}MB`}const If=`perf`,Lf=z({name:`perf`,commands:[R({name:If,text:{summary:`Check frames, memory, or native profiles`,cliDetail:`Use perf frames for bounded frame-health evidence and perf memory sample for a compact process-memory reading. On iOS simulators and macOS, process sampling and captures target the resolved app executable and exclude other copies with the same name. Apple xctrace and Android Simpleperf/Perfetto captures keep raw artifacts on disk; report produces bounded agent-readable evidence. For React render performance, run agent-device react-devtools profile start before the interaction and react-devtools profile stop after it.`,mcpDetail:`For CPU profiles, start and stop write the raw artifact while report writes a compact summary; request the report when the task needs readable native CPU evidence. Profiling output is evidence only: compact state, artifact path, and size.`},metadata:L(If,`Collect frame health, memory diagnostics, and platform profiling artifacts with compact agent-readable summaries.`,{area:k(P(tn)),subject:P(on),action:P(en),kind:P(qt),template:A(`xctrace template name, for example Time Profiler.`),out:A(`Output artifact path.`),tracePath:A(`Existing .trace path to report, defaults to the latest session trace.`)}),run:(e,t)=>e.observability.perf(t),cliSchema:{usageOverride:`perf frames --json
41
41
  agent-device perf memory sample --json
42
42
  agent-device perf memory snapshot [--kind android-hprof|memgraph] [--out <path>]
43
43
  agent-device perf cpu profile start --kind xctrace [--template <name>] --out <profile.trace>
@@ -49,12 +49,12 @@ import{L as e,M as t,R as n,h as r,j as i,k as a,n as o,v as s,w as c}from"./sdk
49
49
  agent-device perf cpu profile report --kind simpleperf --out <cpu-report.json>
50
50
  agent-device perf trace start|stop --kind perfetto [--out <path>]
51
51
 
52
- Aggregate perf was removed in 0.21. Use one of the explicit forms above.`,usageFlags:[],listUsageOverride:`perf`,positionalArgs:[`area`,`subjectOrAction?`,`action?`],allowedFlags:[`kind`,`perfTemplate`,`out`]},cliReader:(e,t)=>({...v(t),...Rf(e,{kind:Wf(t.kind),template:t.perfTemplate,out:t.out})}),daemonWriter:g(Pf,e=>If(e)),cliOutputFormatter:nf.perf})]});function If(e){let t=e.area;return t===`cpu`?Lf([...y(t),...y(e.subject),...y(e.action),...y(e.kind)],e):t===`trace`?Lf([...y(t),...y(e.action),...y(e.kind)],e):[...y(t),...y(e.action)]}function Lf(e,t){let n=[...e];return(t.template||t.out||t.tracePath)&&n.push(t.template??``),(t.out||t.tracePath)&&n.push(t.out??``),t.tracePath&&n.push(t.tracePath),n}function Rf(e,t={}){let n=Bf(e[0]);if(n===`cpu`)return{area:n,subject:Hf(e[1]),action:Vf(e[2]),kind:Uf(t.kind),template:t.template,out:t.out};if(n===`trace`)return{area:n,action:Vf(e[1]),kind:Uf(t.kind),template:t.template,out:t.out};let r=Vf(e[1]),i=Uf(t.kind);return zf(n,r,i,t.out),{area:n,action:r,kind:i,out:t.out}}function zf(e,t,r,i){if(e===`frames`){if(r!==void 0)throw new n(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(i!==void 0)throw new n(`INVALID_ARGS`,`--out is only supported with perf memory snapshot, perf cpu profile, or perf trace`)}if(e===`memory`){if(t!==`snapshot`&&r!==void 0)throw new n(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(t!==`snapshot`&&i!==void 0)throw new n(`INVALID_ARGS`,`--out is only supported with perf memory snapshot`)}}function Bf(e){let t=e?.toLowerCase();if(Yt(t))throw new n(`INVALID_ARGS`,Zt);if(Jt(t))return t;throw new n(`INVALID_ARGS`,Gt)}function Vf(e){if(e===void 0)return;let t=e.toLowerCase();if(qt(t))return t;throw new n(`INVALID_ARGS`,rn)}function Hf(e){let t=e?.toLowerCase();if(t!==void 0&&Xt(t))return t;throw new n(`INVALID_ARGS`,Qt)}function Uf(e){if(e===void 0)return;let t=e.toLowerCase();if(tn(t))return t;throw new n(`INVALID_ARGS`,nn)}function Wf(e){return typeof e==`string`?Uf(e):void 0}const Gf=`react-native`,Kf=B({name:`react-native`,commands:[z({name:Gf,text:{summary:`Run React Native automation helpers`},metadata:R(Gf,`Run supported React Native automation helpers. Use dismiss-overlay to close a visible development error overlay before continuing normal UI automation.`,{action:A(F([`dismiss-overlay`]))}),run:(e,t)=>e.command.reactNative(t),cliSchema:{usageOverride:`react-native dismiss-overlay`,listUsageOverride:`react-native dismiss-overlay`,positionalArgs:[`dismiss-overlay`]},cliReader:(e,t)=>({...v(t),action:qf(e[0])}),daemonWriter:g(Gf,e=>[S(e.action,`react-native requires action`)])})]});function qf(e){if(e===`dismiss-overlay`)return e;throw new n(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}function Jf(e){let t=e,n=typeof t.outPath==`string`?t.outPath:``,r=Zf(t);if(r.length<=1)return{data:t,text:Xf(t,n)};let i=[`Recording chunks:`];for(let e of r)i.push(` ${e.index}: ${e.path}`);return typeof t.telemetryPath==`string`&&i.push(`Telemetry: ${t.telemetryPath}`),typeof t.warning==`string`&&i.push(`Warning: ${t.warning}`),typeof t.overlayWarning==`string`&&i.push(`Overlay warning: ${t.overlayWarning}`),{data:t,text:i.join(`
53
- `)}}const Yf={record:V(Jf)};function Xf(e,t){let n=[];return t&&n.push(t),typeof e.sessionStateDir==`string`&&n.push(`Session state: ${e.sessionStateDir}`),typeof e.warning==`string`&&n.push(`Warning: ${e.warning}`),typeof e.overlayWarning==`string`&&n.push(`Overlay warning: ${e.overlayWarning}`),n.join(`
54
- `)}function Zf(e){let t=e.chunks;return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.index!=`number`||typeof t.path!=`string`?[]:[{index:t.index,path:t.path}]}):[]}const Qf=`record`,$f=`trace`,ep=[`start`,`stop`],tp=R(Qf,`Start or stop a screen recording for the active app session or, where supported, the selected device, or build a contact-sheet PNG from a recording already exported. Long Android recordings can return multiple video artifacts; HarmonyOS supports whole-screen recording on physical devices.`,{action:A(F(ep)),path:j(),fps:N(),maxSize:Ir(Ie.migration.record),quality:F(zt),hideTouches:P(),recordingScope:F(Bt)},{parseableOutput:!0}),np=R($f,`Start or stop trace-log capture and return the resulting artifact when capture ends. Without a path, start writes a timestamped trace log named after the session in the sessions directory of the daemon state; a path on stop moves the finished trace there.`,{action:A(F(ep)),path:j()}),rp={start:[`recordingScope`,`fps`,`quality`,`hideTouches`],stop:[],"contact-sheet":[`out`]},ip={usageOverride:`record start [path] [--scope <app|device|system>] [--fps <n>] [--quality <medium|high>] [--hide-touches] | record stop | record contact-sheet <video.mp4> [--out <sheet.png>]`,usageFlags:[],listUsageOverride:`record start [path] | record stop | record contact-sheet <video>`,positionalArgs:[`start|stop|contact-sheet`,`path?`],allowedFlags:[...new Set(Object.values(rp).flat())],flagsByAction:rp},ap={usageOverride:`trace start [path] | trace stop [path]`,listUsageOverride:`trace start [path] | trace stop [path]`,positionalArgs:[`start|stop`,`path?`]},op=(e,t)=>({...v(t),action:pp(e[0],Qf),path:e[1],fps:t.fps,quality:t.quality,hideTouches:t.hideTouches,recordingScope:t.recordingScope}),sp=(e,t)=>({...v(t),action:pp(e[0],$f),path:e[1]}),cp=g(Qf,e=>fp(e)),lp=e=>(xe(`record`,e),cp(e)),up=g($f,e=>fp(e)),dp=B({name:`recording`,commands:[z({name:Qf,text:{summary:`Start or stop screen recording`,cliDetail:`The default --scope app requires an active app session from open <app>; use --scope device/system to explicitly request whole-screen recording where the selected backend supports it. Android record start publishes a durable device manifest, recordings longer than the 180s adb screenrecord limit are returned as multiple MP4 chunks while the daemon stays alive, and daemon-restart recovery uses only manifest-owned chunks. Android screenrecord encodes a frame only when the screen changes, so a clip can end at the last frame the recorder encoded instead of at record stop; durationMs is host wall clock from record start until the export finished, and capturedDurationMs reports the video timeline when it can be measured, with a warning naming how much of the window that video covers. An Android manifest left by an unreachable recording is retired on the next start once its recorders are proven gone; one still owned refuses with non-retriable DEVICE_IN_USE and reason native_recovery_evidence_open naming the session to run record stop for, and a recorder that is still writing an artifact refuses with DEVICE_IN_USE and reason native_recording_artifact_claimed, which clears itself once that recorder ends at the 180s limit. HarmonyOS supports whole-screen recording on physical devices only: use --scope device/system; --fps, --quality, and --hide-touches are unsupported. Use --quality to choose medium or high export quality on supported backends. The touch overlay renders at most 30 frames a second, or at --fps when lower; a lower --fps makes record stop faster on a long recording, and an overlay export that runs past its budget returns the raw video with an overlayWarning. An iOS simulator host recording lock returns non-retriable DEVICE_IN_USE with reason apple_simulator_recording_busy. Stop the recording in its owning session; if a dead recorder left the host locked, ask the host operator to restart the CoreSimulator stream service. A record stop that cannot produce its export keeps what a retry reads back — on Android the device-side artifact and the native manifest — leaves the recording manifest of that session open, and returns its own error, so retry record stop in that session; only closing the session disposes them. Every stopped recording also reports what became of its recorder and of the file that recorder writes to: recorder is confirmed, or lost when the session holding it died, and nativePathDisposition is retirable while that file still owes a removal or retired once its removal was verified. Both are optional disclosures, not failures; ADR 0024 declares further states (unconfirmed, pending) for the steps that gain those probes, and no stop reports them yet. record contact-sheet <video.mp4> [--out <sheet.png>] is a local report over a file you already exported: it decodes frames out of that MP4 and writes one PNG holding the cells where the screen visibly changed, each labeled with its elapsed time on the clip timeline. It needs no session and no device, rebuilds any past recording, and works for every backend that exports MP4; a WebM recording is refused with reason contact_sheet_container_unsupported. The sample grid is bounded and spread across the whole clip, so it reports coverage rather than a review: a flash that opens and closes entirely between two sample times is not in the sheet, which is why the result also reports how many times it sampled and how many frames came back. Frame decoding is Apple AVFoundation tooling, so the command runs only on macOS hosts and refuses elsewhere with reason contact_sheet_unsupported_host.`},metadata:tp,run:(e,t)=>e.recording.record(t),cliSchema:ip,cliReader:op,daemonWriter:lp,cliOutputFormatter:Yf.record}),z({name:$f,text:{summary:`Start or stop trace capture`},metadata:np,run:(e,t)=>e.recording.trace(t),cliSchema:ap,cliReader:sp,daemonWriter:up})]});function fp(e){return[e.action,...y(e.path)]}function pp(e,t){if(e===`start`||e===`stop`)return e;throw new n(`INVALID_ARGS`,`${t} requires start|stop`)}const mp=2097152;async function hp(e){let t=Cn(e.inputPath,{cwd:e.cwd}),n=_p(t,e.inputPath),r=Ke(t,e.replayBackend);return r===`ad`?gp(t,{[t]:n},e.inputPath):gp(t,(await(await import(`./replay-backend-registry.js`).then(e=>e.n)).getReplayBackend(r)).collectSourceFiles({entryPath:t,entrySource:n,env:e.env,readSource:vp}),e.inputPath)}function gp(e,t,n){return yp(t,n),{entry:e,files:t}}function _p(e,t){try{return wn.readFileSync(e,`utf8`)}catch(r){throw new n(`INVALID_ARGS`,`replay script not found on this machine: ${t}`,{path:e,hint:`Replay scripts are read by the client and sent to the daemon, so the path must resolve where you ran the command.`},r instanceof Error?r:void 0)}}function vp(e){try{return wn.readFileSync(e,`utf8`)}catch{return}}function yp(e,t){let r=Object.values(e).reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0);if(!(r<=2097152))throw new n(`INVALID_ARGS`,`replay script sources for ${t} total ${r} bytes, over the ${mp}-byte limit; split the flow or drop unused runFlow includes.`,{limitBytes:mp,totalBytes:r})}const bp=/[*?[\]{}]/;function xp(e){let t=e.replayBackend===`maestro`?new Set([`.yaml`,`.yml`,`.ad`]):new Set([`.ad`]),n=[],r=[];for(let i of e.inputs){let a=Sp(i,e.cwd,t);if(a.source===`file`){n.push(...a.paths);continue}r.push(a.source===`directory`?Dp(a.paths):Tp(a.paths))}return Dp([...n,...r.flat()])}function Sp(e,t,r){let i=Cn(e,{cwd:t});if(wn.existsSync(i)){let t=wn.statSync(i);return t.isDirectory()?{paths:wp(i,r),source:`directory`}:t.isFile()?(Cp(e,i,r),{paths:[i],source:`file`}):{paths:[],source:`file`}}if(!Op(e))throw new n(`INVALID_ARGS`,`test input not found: ${e}`);return{source:`glob`,paths:wn.globSync(Sn(e),{cwd:t}).map(e=>f.isAbsolute(e)?e:f.resolve(t,e)).filter(e=>r.has(f.extname(e).toLowerCase())&&kp(e))}}function Cp(e,t,r){if(!r.has(f.extname(t).toLowerCase()))throw at(t)&&!r.has(`.yaml`)?new n(`INVALID_ARGS`,rt(`test`,e)):new n(`INVALID_ARGS`,`test does not support this file type: ${e}`)}function wp(e,t){let n=[],r=wn.opendirSync(e);try{let i;for(;(i=r.readSync())!==null;){let r=f.join(e,i.name);i.isDirectory()?n.push(...wp(r,t)):i.isFile()&&t.has(f.extname(i.name).toLowerCase())&&n.push(r)}}finally{r.closeSync()}return n}function Tp(e){return e.map(e=>f.normalize(e)).sort((e,t)=>{let n=Ep(e)-Ep(t);return n===0?e.localeCompare(t):n})}function Ep(e){return+(f.extname(e).toLowerCase()===`.ad`)}function Dp(e){return[...new Set(e.map(e=>f.normalize(e)))]}function Op(e){return bp.test(e)}function kp(e){try{return wn.statSync(e).isFile()}catch{return!1}}const Ap=`replay`,jp=`test`,Mp=R(Ap,`Run a recorded automation script, including compatible Maestro YAML flows. A script without a terminal close leaves its session active for subsequent automation.`,{path:A(j()),update:P(),backend:j(),maestro:P(),env:Ur(),metroHost:j(`Metro/debug host hint inherited by replay-opened sessions.`),metroPort:N(`Metro/debug port hint inherited by replay-opened sessions.`),bundleUrl:j(`Bundle URL hint inherited by replay-opened sessions.`),resumeFrom:N(),resumePlanDigest:j(),keepSession:P(`Leave the session active by suppressing exactly an authored terminal close in native .ad.`),timeoutMs:N(`Operation wall-clock budget in milliseconds (default 60000). The client allows another 30000 milliseconds for the daemon result.`),saveScript:I({oneOf:[O(),E()]}),force:P(),testIme:P(`Activate the headless Android test IME for the sessions this replay opens (default on for emulators; opt-in on real devices).`)}),Np=R(jp,`Run one or more replay scripts as a serial test suite`,{paths:A(Ur()),update:P(),backend:j(),maestro:P(),env:Ur(),metroHost:j(`Metro/debug host hint inherited by each test session.`),metroPort:N(`Metro/debug port hint inherited by each test session.`),bundleUrl:j(`Bundle URL hint inherited by each test session.`),failFast:P(),timeoutMs:N(),retries:N(),recordVideo:P(),artifactsDir:j(),shardAll:N(),shardSplit:N(),testIme:P(`Activate the headless Android test IME for the sessions each suite attempt opens (default on for emulators; opt-in on real devices).`)}),Pp={replay:C({replayed:D(),healed:D(),session:E(),sessionActive:O(`True iff the session is still active — the script had no terminal close.`),artifactPaths:Fr(),snapshotDiagnostics:k(),message:E()},[`replayed`,`healed`,`session`,`sessionActive`,`artifactPaths`,`message`]),test:C({total:D(),executed:D(),passed:D(),failed:D(),skipped:D(),notRun:D(),durationMs:D(),failures:{type:`array`,items:k()},tests:{type:`array`,items:k()},snapshotDiagnostics:k()},[`total`,`executed`,`passed`,`failed`,`skipped`,`notRun`,`durationMs`,`failures`,`tests`])},Fp={usageOverride:`replay <path> | replay export <file.ad> [--out <path>]`,usageFlags:[],positionalArgs:[`path`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...oa,...na,`replayFrom`,`replayPlanDigest`,`replayKeepSession`,`timeoutMs`,`out`,`saveScript`,`force`,`testIme`],flagDescriptionOverrides:{saveScript:`Arm a repair transaction from this replay (ADR 0012): recording starts at step 1, and the healed script commits when the repair-armed session tears down (close, close --save-script, or idle-reap). Independent of the open/close authoring arm-on-open. Optional custom output path.`}},Ip={usageOverride:`test <path-or-glob>...`,usageFlags:[],listUsageOverride:`test <path-or-glob>...`,positionalArgs:[`pathOrGlob`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...oa,...na,`failFast`,`timeoutMs`,`retries`,`recordVideo`,`artifactsDir`,`reporter`,`reportJunit`,`shardAll`,`shardSplit`,`testIme`]},Lp=B({name:`replay`,commands:[z({name:Ap,text:{summary:`Replay a recorded session or Maestro flow`,cliDetail:`Replay has a 60-second work budget inside a 90-second client timeout; --timeout <ms> sets a work budget of X and client timeout of X + 30000 ms. The running step receives ordinary request cancellation at the budget. When it settles, failure returns details.reason daemon_request_timeout and details.timeoutMs, preserving the failing script path and line. The daemon and other sessions stay available if it responds; an authored close may already have ended its session. A completed replay returns success even if it settles just after the deadline. Cancellation does not prove native device work stopped. A step that ignores cancellation beyond the 30-second margin may cause a transport timeout; an unresponsive daemon retains the client liveness-based reset. Direct test keeps its own timeout behavior. For Maestro YAML compatibility flows, use replay <flow.yaml> --maestro and keep the target binding such as --platform ios on the replay command. A script with no terminal close leaves its session (and daemon) running until you close it or it idle-reaps — no different from a session opened interactively. For native .ad scripts, --keep-session suppresses exactly an authored terminal close so you can continue interactively. replay export <file.ad> converts compatible actions to Maestro YAML locally, including app switches with explicit launchApp.appId targets, deep links (including tel: and mailto:) as openLink, and home as pressKey: Home.`},metadata:Mp,run:(e,t)=>e.replay.run(ll(t)),cliSchema:Fp,cliReader:(e,t)=>({...v(t),path:x(e[0],`replay requires path`),update:t.replayUpdate,backend:t.replayMaestro?`maestro`:void 0,env:t.replayEnv,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,resumeFrom:t.replayFrom,resumePlanDigest:t.replayPlanDigest,keepSession:t.replayKeepSession,timeoutMs:t.timeoutMs,saveScript:t.saveScript,force:t.force,testIme:t.testIme}),daemonWriter:async(e,t)=>{let n=S(e.path,`replay requires path`),r=Bp(e),i=Hp(t.env);return _(Ap,[n],{...e,replayUpdate:e.update,replayBackend:r,replayEnv:e.env,replayShellEnv:i,replayScriptSource:await hp({inputPath:n,cwd:zp(e,t.cwd),replayBackend:r,env:Rp(e,i)}),replayFrom:e.resumeFrom,replayPlanDigest:e.resumePlanDigest,replayKeepSession:e.keepSession,saveScript:e.saveScript})},cliOutputFormatter:H}),z({name:jp,text:{summary:`Run replay test suites`,cliDetail:`Relative globs are expanded on the caller from its working directory, whose name is treated literally. Quote glob inputs to defer expansion to test. Copied diagnostic artifacts receive numbered filenames when needed to preserve other artifacts, replay sources, timing traces, and attempt manifests. JUnit reports (--reporter junit:<path>) replace characters forbidden by XML 1.0 with U+FFFD and preserve legal Unicode and whitespace. JSON and other reporters retain the original suite values. Custom reporter getExitCode hooks must return an integer from 0 to 255 or undefined; the highest valid code wins and cannot lower a failing suite's exit code. A nested test stops after a bounded resource refusal even with --retries; other failures keep their configured retries.`},metadata:Np,run:(e,t)=>e.replay.test(ll(t)),cliSchema:Ip,cliReader:(e,t)=>({...v(t),paths:e,update:t.replayUpdate,backend:t.replayMaestro?`maestro`:void 0,env:t.replayEnv,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,failFast:t.failFast,timeoutMs:t.timeoutMs,retries:t.retries,recordVideo:t.recordVideo,artifactsDir:t.artifactsDir,shardAll:t.shardAll,shardSplit:t.shardSplit,testIme:t.testIme}),daemonWriter:async(e,t)=>{let n=e.paths??[],r=Bp(e),i=zp(e,t.cwd),a=Hp(t.env),o=Rp(e,a);return _(jp,n,{...Vp(e),replayUpdate:e.update,replayBackend:r,replayEnv:e.env,replayShellEnv:a,replayScriptSources:await Promise.all(xp({inputs:n,cwd:i,replayBackend:r}).map(async e=>await hp({inputPath:e,cwd:i,replayBackend:r,env:o})))})}})]});function Rp(e,t){return{...Ut(t),...Ht(Vt(e.env))}}function zp(e,t){return typeof e.cwd==`string`&&e.cwd.length>0?e.cwd:t}function Bp(e){return e.backend??(e.maestro===!0?`maestro`:void 0)}function Vp(e){let t={...e};return delete t.reporter,delete t.reportJunit,t}function Hp(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&n.startsWith(`AD_VAR_`)&&(t[n]=r);return t}function Up(e){return{data:e,text:Kp(e)}}function Wp(e){if(e.platform===`android`&&e.action===`status`){let t=[`Keyboard visible: ${e.visible===!0?`yes`:`no`}`,`Input type: ${e.type??e.inputType??`unknown`}`,`Input owner: ${e.inputOwner??`unknown`}`];return e.inputMethodPackage&&t.push(`Input method: ${e.inputMethodPackage}`),e.focusedPackage&&t.push(`Focused package: ${e.focusedPackage}`),e.focusedResourceId&&t.push(`Focused resource: ${e.focusedResourceId}`),t.push(`Next action: ${Jp(e.visible,e.inputOwner)}`),{data:e,text:t.join(`
55
- `)}}return vi(e)}function Gp(e){return e.action===`read`?{data:e,text:e.text}:vi(e)}const $=Qs({appstate:V(Up),back:H,home:H,orientation:H,fold:H,"app-switcher":H,"action-button":H,keyboard:V(Wp),clipboard:V(Gp),"tv-remote":H,"hardware-button":H,telephony:H});function Kp(e){switch(e.platform){case`ios`:case`macos`:return qp(e);case`android`:case`harmonyos`:{let t=[`Foreground app: ${e.package??`unknown`}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join(`
56
- `)}}}function qp(e){let t=[`Session app: ${e.appName??e.appBundleId??`unknown`}`];return e.appBundleId&&t.push(`Bundle: ${e.appBundleId}`),e.state&&t.push(`State: ${e.state}`),e.source&&t.push(`Source: ${e.source}`),t.join(`
57
- `)}function Jp(e,t){return t===`ime`?`Focused input appears to be owned by the keyboard/IME; dismiss or change the IME before retrying text entry.`:e===!0?`Keyboard is visible and focused input appears app-owned; fill/type can proceed.`:`Keyboard is hidden; focus an app field before type, or use fill with a concrete target.`}const Yp=`back`,Xp=`orientation`,Zp=`fold`,Qp=`hardware-button`,$p=`keyboard`,em=`clipboard`,tm=`tv-remote`,nm=`telephony`,rm=[`read`,`write`],im=[`status`,`dismiss`,`enter`,`return`],am={description:`TV remote button. Android TV also accepts android-keycode:<n> with n from 1 to 2147483647.`,oneOf:[w(we),{type:`string`,pattern:je.source}]},om={back:C({action:T(`back`),mode:w(dt),message:E()},[`action`,`mode`,`message`]),home:C({action:T(`home`),message:E()},[`action`,`message`]),orientation:C({action:T(`orientation`),orientation:w(le),message:E(),confirmed:O(),warning:E()},[`action`,`orientation`,`message`]),"app-switcher":C({action:T(`app-switcher`),message:E()},[`action`,`message`]),fold:C({action:T(`fold`),pose:w(Fe),hingeAngleDegrees:D(`Hinge angle read back after the pose settled: from CoreMotion inside the simulator on iOS, from the emulator hinge sensor on Android.`),screen:C({display:E(`CoreDevice name of the panel the device now lights.`),coordinateSpace:T(te),widthPt:D(`Panel width in native panel points (pixels divided by point scale), NOT snapshot coordinates; take a fresh snapshot to place a tap.`),heightPt:D(`Panel height in native panel points (pixels divided by point scale), NOT snapshot coordinates; take a fresh snapshot to place a tap.`)},[`display`,`coordinateSpace`,`widthPt`,`heightPt`]),message:E()},[`action`,`pose`,`hingeAngleDegrees`,`message`]),"action-button":C({action:T(`action-button`),message:E()},[`action`,`message`]),"tv-remote":C({action:T(`tv-remote`),button:am,durationMs:D(),message:E()},[`action`,`button`,`message`]),"hardware-button":C({action:T(`hardware-button`),button:w(Pe),message:E()},[`action`,`button`,`message`]),telephony:{type:`object`,oneOf:[C({action:w(Ce),number:E(),message:E()},[`action`,`number`,`message`]),C({action:T(`sms`),number:E(),textLength:D(`Length of the delivered message text.`),message:E()},[`action`,`number`,`textLength`,`message`])]},clipboard:{type:`object`,oneOf:[C({action:T(`read`),text:E()},[`action`,`text`]),C({action:T(`write`),textLength:D(),message:E()},[`action`,`textLength`,`message`])]},appstate:{type:`object`,oneOf:[C({platform:w([`ios`,`macos`]),appName:E(),appBundleId:E(),source:w([`session`,`runner`],`runner when a live runner read the session app state; session when the record alone answered.`),state:w(r,`The session app XCUIApplication state as a live runner reads it; absent with source session.`),surface:w(Wt),device_udid:E(`iOS only — the session device UDID.`),ios_simulator_device_set:{type:[`string`,`null`],description:`iOS only — the simulator set path, or null when unknown.`}},[`platform`,`appName`,`source`,`surface`]),C({platform:w([`android`,`harmonyos`]),package:E(),activity:E()},[`platform`,`package`,`activity`])]},keyboard:C({platform:w([`android`,`ios`]),action:w([`status`,`dismiss`,`enter`]),visible:O(),wasVisible:O(),dismissed:O(),attempts:D(),inputType:E(),type:w([`text`,`number`,`email`,`phone`,`password`,`datetime`,`unknown`]),inputMethodPackage:E(),focusedPackage:E(),focusedResourceId:E(),inputOwner:w([`app`,`ime`,`unknown`]),message:E()},[`platform`,`action`])},sm={hingeEvent:`simulator HID hinge event`,permissions:`Device Hub and host Accessibility permission are not required.`},cm=`Fold or unfold a foldable iPhone simulator (iPhone Duo) or a foldable Android emulator into the closed, half-open, or open pose. iOS sends a ${sm.hingeEvent}, then reads the hinge angle back inside the simulator to confirm it, and can follow timestamped angle keyframes; Android sets the emulator console posture, then confirms the device state the guest commits and reports the hinge angle the AVD profile defines for that posture, and dismisses the lock screen a fold to the cover display can raise. On iOS a pose change moves the app to a different panel with a different point size; on Android a fold to or from closed moves the app between the cover and inner displays, and any pose change can reshape the app window, whose size the next snapshot reports. Either way every ref and coordinate from before it is stale: re-snapshot after this command. Taps, long presses, and scrolling target the app window on its current panel in closed, half-open, and open poses. Simulator and emulator only; iOS requires the iOS simulator SDK; ${sm.permissions} An iOS simulator in a scoped simulator set folds the same way as one in the default set.`,lm={summary:`Foldable devices: panels, pose, and which screen you are on`,body:`agent-device help foldable
52
+ Aggregate perf was removed in 0.21. Use one of the explicit forms above.`,usageFlags:[],listUsageOverride:`perf`,positionalArgs:[`area`,`subjectOrAction?`,`action?`],allowedFlags:[`kind`,`perfTemplate`,`out`]},cliReader:(e,t)=>({..._(t),...Bf(e,{kind:Kf(t.kind),template:t.perfTemplate,out:t.out})}),daemonWriter:h(If,e=>Rf(e)),cliOutputFormatter:af.perf})]});function Rf(e){let t=e.area;return t===`cpu`?zf([...v(t),...v(e.subject),...v(e.action),...v(e.kind)],e):t===`trace`?zf([...v(t),...v(e.action),...v(e.kind)],e):[...v(t),...v(e.action)]}function zf(e,t){let n=[...e];return(t.template||t.out||t.tracePath)&&n.push(t.template??``),(t.out||t.tracePath)&&n.push(t.out??``),t.tracePath&&n.push(t.tracePath),n}function Bf(e,t={}){let n=Hf(e[0]);if(n===`cpu`)return{area:n,subject:Wf(e[1]),action:Uf(e[2]),kind:Gf(t.kind),template:t.template,out:t.out};if(n===`trace`)return{area:n,action:Uf(e[1]),kind:Gf(t.kind),template:t.template,out:t.out};let r=Uf(e[1]),i=Gf(t.kind);return Vf(n,r,i,t.out),{area:n,action:r,kind:i,out:t.out}}function Vf(e,t,r,i){if(e===`frames`){if(r!==void 0)throw new n(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(i!==void 0)throw new n(`INVALID_ARGS`,`--out is only supported with perf memory snapshot, perf cpu profile, or perf trace`)}if(e===`memory`){if(t!==`snapshot`&&r!==void 0)throw new n(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(t!==`snapshot`&&i!==void 0)throw new n(`INVALID_ARGS`,`--out is only supported with perf memory snapshot`)}}function Hf(e){let t=e?.toLowerCase();if(Xt(t))throw new n(`INVALID_ARGS`,Qt);if(Yt(t))return t;throw new n(`INVALID_ARGS`,Kt)}function Uf(e){if(e===void 0)return;let t=e.toLowerCase();if(Jt(t))return t;throw new n(`INVALID_ARGS`,an)}function Wf(e){let t=e?.toLowerCase();if(t!==void 0&&Zt(t))return t;throw new n(`INVALID_ARGS`,$t)}function Gf(e){if(e===void 0)return;let t=e.toLowerCase();if(nn(t))return t;throw new n(`INVALID_ARGS`,rn)}function Kf(e){return typeof e==`string`?Gf(e):void 0}const qf=`react-native`,Jf=z({name:`react-native`,commands:[R({name:qf,text:{summary:`Run React Native automation helpers`},metadata:L(qf,`Run supported React Native automation helpers. Use dismiss-overlay to close a visible development error overlay before continuing normal UI automation.`,{action:k(P([`dismiss-overlay`]))}),run:(e,t)=>e.command.reactNative(t),cliSchema:{usageOverride:`react-native dismiss-overlay`,listUsageOverride:`react-native dismiss-overlay`,positionalArgs:[`dismiss-overlay`]},cliReader:(e,t)=>({..._(t),action:Yf(e[0])}),daemonWriter:h(qf,e=>[x(e.action,`react-native requires action`)])})]});function Yf(e){if(e===`dismiss-overlay`)return e;throw new n(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}function Xf(e){let t=e,n=typeof t.outPath==`string`?t.outPath:``,r=$f(t);if(r.length<=1)return{data:t,text:Qf(t,n)};let i=[`Recording chunks:`];for(let e of r)i.push(` ${e.index}: ${e.path}`);return typeof t.telemetryPath==`string`&&i.push(`Telemetry: ${t.telemetryPath}`),typeof t.warning==`string`&&i.push(`Warning: ${t.warning}`),typeof t.overlayWarning==`string`&&i.push(`Overlay warning: ${t.overlayWarning}`),{data:t,text:i.join(`
53
+ `)}}const Zf={record:B(Xf)};function Qf(e,t){let n=[];return t&&n.push(t),typeof e.sessionStateDir==`string`&&n.push(`Session state: ${e.sessionStateDir}`),typeof e.warning==`string`&&n.push(`Warning: ${e.warning}`),typeof e.overlayWarning==`string`&&n.push(`Overlay warning: ${e.overlayWarning}`),n.join(`
54
+ `)}function $f(e){let t=e.chunks;return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.index!=`number`||typeof t.path!=`string`?[]:[{index:t.index,path:t.path}]}):[]}const ep=`record`,tp=`trace`,np=[`start`,`stop`],rp=L(ep,`Start or stop a screen recording for the active app session or, where supported, the selected device, or build a contact-sheet PNG from a recording already exported. Long Android recordings can return multiple video artifacts; HarmonyOS supports whole-screen recording on physical devices.`,{action:k(P(np)),path:A(),fps:M(),maxSize:Rr(Ie.migration.record),quality:P(Bt),hideTouches:N(),recordingScope:P(Vt)},{parseableOutput:!0}),ip=L(tp,`Start or stop trace-log capture and return the resulting artifact when capture ends. Without a path, start writes a timestamped trace log named after the session in the sessions directory of the daemon state; a path on stop moves the finished trace there.`,{action:k(P(np)),path:A()}),ap={start:[`recordingScope`,`fps`,`quality`,`hideTouches`],stop:[],"contact-sheet":[`out`]},op={usageOverride:`record start [path] [--scope <app|device|system>] [--fps <n>] [--quality <medium|high>] [--hide-touches] | record stop | record contact-sheet <video.mp4> [--out <sheet.png>]`,usageFlags:[],listUsageOverride:`record start [path] | record stop | record contact-sheet <video>`,positionalArgs:[`start|stop|contact-sheet`,`path?`],allowedFlags:[...new Set(Object.values(ap).flat())],flagsByAction:ap},sp={usageOverride:`trace start [path] | trace stop [path]`,listUsageOverride:`trace start [path] | trace stop [path]`,positionalArgs:[`start|stop`,`path?`]},cp=(e,t)=>({..._(t),action:hp(e[0],ep),path:e[1],fps:t.fps,quality:t.quality,hideTouches:t.hideTouches,recordingScope:t.recordingScope}),lp=(e,t)=>({..._(t),action:hp(e[0],tp),path:e[1]}),up=h(ep,e=>mp(e)),dp=e=>(xe(`record`,e),up(e)),fp=h(tp,e=>mp(e)),pp=z({name:`recording`,commands:[R({name:ep,text:{summary:`Start or stop screen recording`,cliDetail:`The default --scope app requires an active app session from open <app>; use --scope device/system to explicitly request whole-screen recording where the selected backend supports it. Android record start publishes a durable device manifest, recordings longer than the 180s adb screenrecord limit are returned as multiple MP4 chunks while the daemon stays alive, and daemon-restart recovery uses only manifest-owned chunks. Android screenrecord encodes a frame only when the screen changes, so a clip can end at the last frame the recorder encoded instead of at record stop; durationMs is host wall clock from record start until the export finished, and capturedDurationMs reports the video timeline when it can be measured, with a warning naming how much of the window that video covers. An Android manifest left by an unreachable recording is retired on the next start once its recorders are proven gone; one still owned refuses with non-retriable DEVICE_IN_USE and reason native_recovery_evidence_open naming the session to run record stop for, and a recorder that is still writing an artifact refuses with DEVICE_IN_USE and reason native_recording_artifact_claimed, which clears itself once that recorder ends at the 180s limit. HarmonyOS supports whole-screen recording on physical devices only: use --scope device/system; --fps, --quality, and --hide-touches are unsupported. Use --quality to choose medium or high export quality on supported backends. The touch overlay renders at most 30 frames a second, or at --fps when lower; a lower --fps makes record stop faster on a long recording, and an overlay export that runs past its budget returns the raw video with an overlayWarning. An iOS simulator host recording lock returns non-retriable DEVICE_IN_USE with reason apple_simulator_recording_busy. Stop the recording in its owning session; if a dead recorder left the host locked, ask the host operator to restart the CoreSimulator stream service. A record stop that cannot produce its export keeps what a retry reads back — on Android the device-side artifact and the native manifest — leaves the recording manifest of that session open, and returns its own error, so retry record stop in that session; only closing the session disposes them. Every stopped recording also reports what became of its recorder and of the file that recorder writes to: recorder is confirmed, or lost when the session holding it died, and nativePathDisposition is retirable while that file still owes a removal or retired once its removal was verified. Both are optional disclosures, not failures; ADR 0024 declares further states (unconfirmed, pending) for the steps that gain those probes, and no stop reports them yet. record contact-sheet <video.mp4> [--out <sheet.png>] is a local report over a file you already exported: it decodes frames out of that MP4 and writes one PNG holding the cells where the screen visibly changed, each labeled with its elapsed time on the clip timeline. It needs no session and no device, rebuilds any past recording, and works for every backend that exports MP4; a WebM recording is refused with reason contact_sheet_container_unsupported. The sample grid is bounded and spread across the whole clip, so it reports coverage rather than a review: a flash that opens and closes entirely between two sample times is not in the sheet, which is why the result also reports how many times it sampled and how many frames came back. Frame decoding is Apple AVFoundation tooling, so the command runs only on macOS hosts and refuses elsewhere with reason contact_sheet_unsupported_host.`},metadata:rp,run:(e,t)=>e.recording.record(t),cliSchema:op,cliReader:cp,daemonWriter:dp,cliOutputFormatter:Zf.record}),R({name:tp,text:{summary:`Start or stop trace capture`},metadata:ip,run:(e,t)=>e.recording.trace(t),cliSchema:sp,cliReader:lp,daemonWriter:fp})]});function mp(e){return[e.action,...v(e.path)]}function hp(e,t){if(e===`start`||e===`stop`)return e;throw new n(`INVALID_ARGS`,`${t} requires start|stop`)}const gp=2097152;async function _p(e){let t=wn(e.inputPath,{cwd:e.cwd}),n=yp(t,e.inputPath),r=Ke(t,e.replayBackend);return r===`ad`?vp(t,{[t]:n},e.inputPath):vp(t,(await(await import(`./replay-backend-registry.js`).then(e=>e.n)).getReplayBackend(r)).collectSourceFiles({entryPath:t,entrySource:n,env:e.env,readSource:bp}),e.inputPath)}function vp(e,t,n){return xp(t,n),{entry:e,files:t}}function yp(e,t){try{return Tn.readFileSync(e,`utf8`)}catch(r){throw new n(`INVALID_ARGS`,`replay script not found on this machine: ${t}`,{path:e,hint:`Replay scripts are read by the client and sent to the daemon, so the path must resolve where you ran the command.`},r instanceof Error?r:void 0)}}function bp(e){try{return Tn.readFileSync(e,`utf8`)}catch{return}}function xp(e,t){let r=Object.values(e).reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0);if(!(r<=2097152))throw new n(`INVALID_ARGS`,`replay script sources for ${t} total ${r} bytes, over the ${gp}-byte limit; split the flow or drop unused runFlow includes.`,{limitBytes:gp,totalBytes:r})}const Sp=/[*?[\]{}]/;function Cp(e){let t=e.replayBackend===`maestro`?new Set([`.yaml`,`.yml`,`.ad`]):new Set([`.ad`]),n=[],r=[];for(let i of e.inputs){let a=wp(i,e.cwd,t);if(a.source===`file`){n.push(...a.paths);continue}r.push(a.source===`directory`?kp(a.paths):Dp(a.paths))}return kp([...n,...r.flat()])}function wp(e,t,r){let i=wn(e,{cwd:t});if(Tn.existsSync(i)){let t=Tn.statSync(i);return t.isDirectory()?{paths:Ep(i,r),source:`directory`}:t.isFile()?(Tp(e,i,r),{paths:[i],source:`file`}):{paths:[],source:`file`}}if(!Ap(e))throw new n(`INVALID_ARGS`,`test input not found: ${e}`);return{source:`glob`,paths:Tn.globSync(Cn(e),{cwd:t}).map(e=>f.isAbsolute(e)?e:f.resolve(t,e)).filter(e=>r.has(f.extname(e).toLowerCase())&&jp(e))}}function Tp(e,t,r){if(!r.has(f.extname(t).toLowerCase()))throw at(t)&&!r.has(`.yaml`)?new n(`INVALID_ARGS`,rt(`test`,e)):new n(`INVALID_ARGS`,`test does not support this file type: ${e}`)}function Ep(e,t){let n=[],r=Tn.opendirSync(e);try{let i;for(;(i=r.readSync())!==null;){let r=f.join(e,i.name);i.isDirectory()?n.push(...Ep(r,t)):i.isFile()&&t.has(f.extname(i.name).toLowerCase())&&n.push(r)}}finally{r.closeSync()}return n}function Dp(e){return e.map(e=>f.normalize(e)).sort((e,t)=>{let n=Op(e)-Op(t);return n===0?e.localeCompare(t):n})}function Op(e){return+(f.extname(e).toLowerCase()===`.ad`)}function kp(e){return[...new Set(e.map(e=>f.normalize(e)))]}function Ap(e){return Sp.test(e)}function jp(e){try{return Tn.statSync(e).isFile()}catch{return!1}}const Mp=`replay`,Np=`test`,Pp=L(Mp,`Run a recorded automation script, including compatible Maestro YAML flows. A script without a terminal close leaves its session active for subsequent automation.`,{path:k(A()),update:N(),backend:A(),maestro:N(),env:Gr(),metroHost:A(`Metro/debug host hint inherited by replay-opened sessions.`),metroPort:M(`Metro/debug port hint inherited by replay-opened sessions.`),bundleUrl:A(`Bundle URL hint inherited by replay-opened sessions.`),resumeFrom:M(),resumePlanDigest:A(),keepSession:N(`Leave the session active by suppressing exactly an authored terminal close in native .ad.`),timeoutMs:M(`Operation wall-clock budget in milliseconds (default 60000). The client allows another 30000 milliseconds for the daemon result.`),saveScript:F({oneOf:[D(),T()]}),force:N(),testIme:N(`Activate the headless Android test IME for the sessions this replay opens (default on for emulators; opt-in on real devices).`)}),Fp=L(Np,`Run one or more replay scripts as a serial test suite`,{paths:k(Gr()),update:N(),backend:A(),maestro:N(),env:Gr(),metroHost:A(`Metro/debug host hint inherited by each test session.`),metroPort:M(`Metro/debug port hint inherited by each test session.`),bundleUrl:A(`Bundle URL hint inherited by each test session.`),failFast:N(),timeoutMs:M(),retries:M(),recordVideo:N(),artifactsDir:A(),shardAll:M(),shardSplit:M(),testIme:N(`Activate the headless Android test IME for the sessions each suite attempt opens (default on for emulators; opt-in on real devices).`)}),Ip={replay:S({replayed:E(),healed:E(),session:T(),sessionActive:D(`True iff the session is still active — the script had no terminal close.`),artifactPaths:Lr(),snapshotDiagnostics:O(),message:T()},[`replayed`,`healed`,`session`,`sessionActive`,`artifactPaths`,`message`]),test:S({total:E(),executed:E(),passed:E(),failed:E(),skipped:E(),notRun:E(),durationMs:E(),failures:{type:`array`,items:O()},tests:{type:`array`,items:O()},snapshotDiagnostics:O()},[`total`,`executed`,`passed`,`failed`,`skipped`,`notRun`,`durationMs`,`failures`,`tests`])},Lp={usageOverride:`replay <path> | replay export <file.ad> [--out <path>]`,usageFlags:[],positionalArgs:[`path`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...sa,...ra,`replayFrom`,`replayPlanDigest`,`replayKeepSession`,`timeoutMs`,`out`,`saveScript`,`force`,`testIme`],flagDescriptionOverrides:{saveScript:`Arm a repair transaction from this replay (ADR 0012): recording starts at step 1, and the healed script commits when the repair-armed session tears down (close, close --save-script, or idle-reap). Independent of the open/close authoring arm-on-open. Optional custom output path.`}},Rp={usageOverride:`test <path-or-glob>...`,usageFlags:[],listUsageOverride:`test <path-or-glob>...`,positionalArgs:[`pathOrGlob`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...sa,...ra,`failFast`,`timeoutMs`,`retries`,`recordVideo`,`artifactsDir`,`reporter`,`reportJunit`,`shardAll`,`shardSplit`,`testIme`]},zp=z({name:`replay`,commands:[R({name:Mp,text:{summary:`Replay a recorded session or Maestro flow`,cliDetail:`Replay has a 60-second work budget inside a 90-second client timeout; --timeout <ms> sets a work budget of X and client timeout of X + 30000 ms. The running step receives ordinary request cancellation at the budget. When it settles, failure returns details.reason daemon_request_timeout and details.timeoutMs, preserving the failing script path and line. The daemon and other sessions stay available if it responds; an authored close may already have ended its session. A completed replay returns success even if it settles just after the deadline. Cancellation does not prove native device work stopped. A step that ignores cancellation beyond the 30-second margin may cause a transport timeout; an unresponsive daemon retains the client liveness-based reset. Direct test keeps its own timeout behavior. For Maestro YAML compatibility flows, use replay <flow.yaml> --maestro and keep the target binding such as --platform ios on the replay command. A script with no terminal close leaves its session (and daemon) running until you close it or it idle-reaps — no different from a session opened interactively. For native .ad scripts, --keep-session suppresses exactly an authored terminal close so you can continue interactively. replay export <file.ad> converts compatible actions to Maestro YAML locally, including app switches with explicit launchApp.appId targets, deep links (including tel: and mailto:) as openLink, and home as pressKey: Home.`},metadata:Pp,run:(e,t)=>e.replay.run(dl(t)),cliSchema:Lp,cliReader:(e,t)=>({..._(t),path:b(e[0],`replay requires path`),update:t.replayUpdate,backend:t.replayMaestro?`maestro`:void 0,env:t.replayEnv,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,resumeFrom:t.replayFrom,resumePlanDigest:t.replayPlanDigest,keepSession:t.replayKeepSession,timeoutMs:t.timeoutMs,saveScript:t.saveScript,force:t.force,testIme:t.testIme}),daemonWriter:async(e,t)=>{let n=x(e.path,`replay requires path`),r=Hp(e),i=Wp(t.env);return g(Mp,[n],{...e,replayUpdate:e.update,replayBackend:r,replayEnv:e.env,replayShellEnv:i,replayScriptSource:await _p({inputPath:n,cwd:Vp(e,t.cwd),replayBackend:r,env:Bp(e,i)}),replayFrom:e.resumeFrom,replayPlanDigest:e.resumePlanDigest,replayKeepSession:e.keepSession,saveScript:e.saveScript})},cliOutputFormatter:V}),R({name:Np,text:{summary:`Run replay test suites`,cliDetail:`Relative globs are expanded on the caller from its working directory, whose name is treated literally. Quote glob inputs to defer expansion to test. Copied diagnostic artifacts receive numbered filenames when needed to preserve other artifacts, replay sources, timing traces, and attempt manifests. JUnit reports (--reporter junit:<path>) replace characters forbidden by XML 1.0 with U+FFFD and preserve legal Unicode and whitespace. JSON and other reporters retain the original suite values. Custom reporter getExitCode hooks must return an integer from 0 to 255 or undefined; the highest valid code wins and cannot lower a failing suite's exit code. A nested test stops after a bounded resource refusal even with --retries; other failures keep their configured retries.`},metadata:Fp,run:(e,t)=>e.replay.test(dl(t)),cliSchema:Rp,cliReader:(e,t)=>({..._(t),paths:e,update:t.replayUpdate,backend:t.replayMaestro?`maestro`:void 0,env:t.replayEnv,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,failFast:t.failFast,timeoutMs:t.timeoutMs,retries:t.retries,recordVideo:t.recordVideo,artifactsDir:t.artifactsDir,shardAll:t.shardAll,shardSplit:t.shardSplit,testIme:t.testIme}),daemonWriter:async(e,t)=>{let n=e.paths??[],r=Hp(e),i=Vp(e,t.cwd),a=Wp(t.env),o=Bp(e,a);return g(Np,n,{...Up(e),replayUpdate:e.update,replayBackend:r,replayEnv:e.env,replayShellEnv:a,replayScriptSources:await Promise.all(Cp({inputs:n,cwd:i,replayBackend:r}).map(async e=>await _p({inputPath:e,cwd:i,replayBackend:r,env:o})))})}})]});function Bp(e,t){return{...Wt(t),...Ut(Ht(e.env))}}function Vp(e,t){return typeof e.cwd==`string`&&e.cwd.length>0?e.cwd:t}function Hp(e){return e.backend??(e.maestro===!0?`maestro`:void 0)}function Up(e){let t={...e};return delete t.reporter,delete t.reportJunit,t}function Wp(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&n.startsWith(`AD_VAR_`)&&(t[n]=r);return t}function Gp(e){return{data:e,text:Jp(e)}}function Kp(e){if(e.platform===`android`&&e.action===`status`){let t=[`Keyboard visible: ${e.visible===!0?`yes`:`no`}`,`Input type: ${e.type??e.inputType??`unknown`}`,`Input owner: ${e.inputOwner??`unknown`}`];return e.inputMethodPackage&&t.push(`Input method: ${e.inputMethodPackage}`),e.focusedPackage&&t.push(`Focused package: ${e.focusedPackage}`),e.focusedResourceId&&t.push(`Focused resource: ${e.focusedResourceId}`),t.push(`Next action: ${Xp(e.visible,e.inputOwner)}`),{data:e,text:t.join(`
55
+ `)}}return bi(e)}function qp(e){return e.action===`read`?{data:e,text:e.text}:bi(e)}const $=$s({appstate:B(Gp),back:V,home:V,orientation:V,fold:V,"app-switcher":V,"action-button":V,keyboard:B(Kp),clipboard:B(qp),"tv-remote":V,"hardware-button":V,telephony:V});function Jp(e){switch(e.platform){case`ios`:case`macos`:return Yp(e);case`android`:case`harmonyos`:{let t=[`Foreground app: ${e.package??`unknown`}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join(`
56
+ `)}}}function Yp(e){let t=[`Session app: ${e.appName??e.appBundleId??`unknown`}`];return e.appBundleId&&t.push(`Bundle: ${e.appBundleId}`),e.state&&t.push(`State: ${e.state}`),e.source&&t.push(`Source: ${e.source}`),t.join(`
57
+ `)}function Xp(e,t){return t===`ime`?`Focused input appears to be owned by the keyboard/IME; dismiss or change the IME before retrying text entry.`:e===!0?`Keyboard is visible and focused input appears app-owned; fill/type can proceed.`:`Keyboard is hidden; focus an app field before type, or use fill with a concrete target.`}const Zp=`back`,Qp=`orientation`,$p=`fold`,em=`hardware-button`,tm=`keyboard`,nm=`clipboard`,rm=`tv-remote`,im=`telephony`,am=[`read`,`write`],om=[`status`,`dismiss`,`enter`,`return`],sm={description:`TV remote button. Android TV also accepts android-keycode:<n> with n from 1 to 2147483647.`,oneOf:[C(we),{type:`string`,pattern:je.source}]},cm={back:S({action:w(`back`),mode:C(dt),message:T()},[`action`,`mode`,`message`]),home:S({action:w(`home`),message:T()},[`action`,`message`]),orientation:S({action:w(`orientation`),orientation:C(le),message:T(),confirmed:D(),warning:T()},[`action`,`orientation`,`message`]),"app-switcher":S({action:w(`app-switcher`),message:T()},[`action`,`message`]),fold:S({action:w(`fold`),pose:C(Fe),hingeAngleDegrees:E(`Hinge angle read back after the pose settled: from CoreMotion inside the simulator on iOS, from the emulator hinge sensor on Android.`),screen:S({display:T(`CoreDevice name of the panel the device now lights.`),coordinateSpace:w(te),widthPt:E(`Panel width in native panel points (pixels divided by point scale), NOT snapshot coordinates; take a fresh snapshot to place a tap.`),heightPt:E(`Panel height in native panel points (pixels divided by point scale), NOT snapshot coordinates; take a fresh snapshot to place a tap.`)},[`display`,`coordinateSpace`,`widthPt`,`heightPt`]),message:T()},[`action`,`pose`,`hingeAngleDegrees`,`message`]),"action-button":S({action:w(`action-button`),message:T()},[`action`,`message`]),"tv-remote":S({action:w(`tv-remote`),button:sm,durationMs:E(),message:T()},[`action`,`button`,`message`]),"hardware-button":S({action:w(`hardware-button`),button:C(Pe),message:T()},[`action`,`button`,`message`]),telephony:{type:`object`,oneOf:[S({action:C(Ce),number:T(),message:T()},[`action`,`number`,`message`]),S({action:w(`sms`),number:T(),textLength:E(`Length of the delivered message text.`),message:T()},[`action`,`number`,`textLength`,`message`])]},clipboard:{type:`object`,oneOf:[S({action:w(`read`),text:T()},[`action`,`text`]),S({action:w(`write`),textLength:E(),message:T()},[`action`,`textLength`,`message`])]},appstate:{type:`object`,oneOf:[S({platform:C([`ios`,`macos`]),appName:T(),appBundleId:T(),source:C([`session`,`runner`],`runner when a live runner read the session app state; session when the record alone answered.`),state:C(r,`The session app XCUIApplication state as a live runner reads it; absent with source session.`),surface:C(Gt),device_udid:T(`iOS only — the session device UDID.`),ios_simulator_device_set:{type:[`string`,`null`],description:`iOS only — the simulator set path, or null when unknown.`}},[`platform`,`appName`,`source`,`surface`]),S({platform:C([`android`,`harmonyos`]),package:T(),activity:T()},[`platform`,`package`,`activity`])]},keyboard:S({platform:C([`android`,`ios`]),action:C([`status`,`dismiss`,`enter`]),visible:D(),wasVisible:D(),dismissed:D(),attempts:E(),inputType:T(),type:C([`text`,`number`,`email`,`phone`,`password`,`datetime`,`unknown`]),inputMethodPackage:T(),focusedPackage:T(),focusedResourceId:T(),inputOwner:C([`app`,`ime`,`unknown`]),message:T()},[`platform`,`action`])},lm={hingeEvent:`simulator HID hinge event`,permissions:`Device Hub and host Accessibility permission are not required.`},um=`Fold or unfold a foldable iPhone simulator (iPhone Duo) or a foldable Android emulator into the closed, half-open, or open pose. iOS sends a ${lm.hingeEvent}, then reads the hinge angle back inside the simulator to confirm it, and can follow timestamped angle keyframes; Android sets the emulator console posture, then confirms the device state the guest commits and reports the hinge angle the AVD profile defines for that posture, and dismisses the lock screen a fold to the cover display can raise. On iOS a pose change moves the app to a different panel with a different point size; on Android a fold to or from closed moves the app between the cover and inner displays, and any pose change can reshape the app window, whose size the next snapshot reports. Either way every ref and coordinate from before it is stale: re-snapshot after this command. Taps, long presses, and scrolling target the app window on its current panel in closed, half-open, and open poses. Simulator and emulator only; iOS requires the iOS simulator SDK; ${lm.permissions} An iOS simulator in a scoped simulator set folds the same way as one in the default set.`,dm={summary:`Foldable devices: panels, pose, and which screen you are on`,body:`agent-device help foldable
58
58
 
59
59
  A foldable Apple device (iPhone Duo) carries two integrated panels, which Apple calls the outer display and the inner display. Only one is lit at a time, and which one is lit is the device pose.
60
60
 
@@ -69,6 +69,6 @@ Changing the pose:
69
69
  Expect a fold to take 2-4 seconds: half-open waits for two agreeing hinge reads one second apart, and the first fold after a boot can take longer while the hinge settles. Re-snapshot after every fold; refs and coordinates from before it are stale, and the command's message says so.
70
70
  Timed motion: fold --keyframes '[{"atMs":0,"angle":0},{"atMs":5000,"angle":180}]'. Use 2–64 frames starting at 0ms, increasing integer timestamps up to 60000ms, and angles from 0 to 180. The last timestamp sets motion duration, excluding setup and verification. Equal angles hold; cancellation stops motion. See the fold examples in the command and Node API documentation for trajectories.
71
71
 
72
- Requirements: an iOS simulator session on a foldable device and an Xcode toolchain with the iOS simulator SDK and foldable HID support (verified on Xcode 27.1). ${sm.permissions} The command runs a small helper through simctl spawn for the session UDID; the helper is built once per Fold.m source hash and Xcode toolchain, cached under ~/.agent-device/fold-helper, and rebuilt only when the source or the toolchain changes. The same helper reads the hinge and, in a scoped set, the panels. Build or dispatch failures are reported without a UI fallback. The app under test reads the resulting pose as UIHinge.status.
72
+ Requirements: an iOS simulator session on a foldable device and an Xcode toolchain with the iOS simulator SDK and foldable HID support (verified on Xcode 27.1). ${lm.permissions} The command runs a small helper through simctl spawn for the session UDID; the helper is built once per Fold.m source hash and Xcode toolchain, cached under ~/.agent-device/fold-helper, and rebuilt only when the source or the toolchain changes. The same helper reads the hinge and, in a scoped set, the panels. Build or dispatch failures are reported without a UI fallback. The app under test reads the resulting pose as UIHinge.status.
73
73
  Android emulators: fold sets the posture through the emulator console (adb emu posture 1|2|3), then reads adb shell cmd device_state print-state until the guest commits CLOSED, HALF_OPENED, or OPENED, and reports the hinge sensor's angle, which the AVD profile defines per posture: 0, 90 and 180 degrees on the Pixel folds, 15, 90 and 165 on the generic 7.6in Foldable. Folding to the cover display can raise Android's "Swipe up to continue" lock screen; fold dismisses it so the app stays reachable. An emulator profile without those device states (a phone) fails with UNSUPPORTED_OPERATION and reason single-panel-device, and a physical device is refused. Keyframes are not supported on Android, and the response carries no panel geometry: re-snapshot after every fold.
74
- If a task asserts behavior for more than one pose, fold to each pose and re-snapshot, and report which poses the run covered.`},um=R(Yp,`Navigate back in the app or through system navigation. Use in-app for the app navigation stack and system when the platform back behavior is required. On iOS, a single-screen iPhone or an iPad whose app provably fills its screen can use a top-leading tap when the app tree is unreadable, with before/after visual verification. A capture failure reports an unknown outcome.`,{mode:F(dt),...ys(Yp)}),dm=R(Xp,`Set device orientation on iOS and Android. auto hands rotation back to the sensor on ADB-backed Android (local and Limrun); other backends refuse it. A foldable iPhone simulator (iPhone Duo) refuses portrait-upside-down, and refuses every rotation in a scoped simulator set.`,{orientation:A(F(le))}),fm={pose:F(Fe,`Instant preset; mutually exclusive with keyframes.`),keyframes:I({type:`array`,minItems:2,maxItems:64,description:`Piecewise-linear hinge motion. Start at 0ms; strictly increasing timestamps, up to 60000ms. Repeated angles create holds. Mutually exclusive with pose.`,items:{type:`object`,required:[`atMs`,`angle`],additionalProperties:!1,properties:{atMs:{type:`integer`,minimum:0,maximum:re},angle:{type:`number`,minimum:0,maximum:180}}}})},pm=R(Zp,cm,fm,{readInput:e=>{let{pose:t,keyframes:n,...r}=ti(e,fm);return{...r,...de({pose:t,keyframes:n})}}}),mm={...pm,inputSchema:{...pm.inputSchema,oneOf:[{required:[`pose`],not:{required:[`keyframes`]}},{required:[`keyframes`],not:{required:[`pose`]}}]}},hm=R($p,`Inspect Android keyboard visibility/type or press/dismiss the device keyboard. To hide the keyboard, use keyboard dismiss. It taps the keyboard dismiss/hide key when one is exposed, verifies the keyboard closed, and reports UNSUPPORTED_OPERATION when no dismiss key exists — background taps are never attempted.`,{action:F(im)}),gm=R(em,`Read the current device clipboard text, or replace its contents with the given text. Android runs both through the clipboard service shell command, and a build that implements none (Android 16 does not) refuses with UNSUPPORTED_OPERATION rather than reporting an empty clipboard.`,{action:A(F(rm)),text:j()},{parseableOutput:!0}),_m=R(tm,`Press or long-press a TV remote button on Android TV, tvOS, or Vega OS. Android TV also supports volume, power, media, channel, guide, captions, input, color keys, and android-keycode:N. tvOS and Vega OS support up, down, left, right, select, menu, home, and back. Phones and WebDriver sessions are unsupported. The aliases ok, center, and enter map to select.`,{button:A(Wr(am,(e,t)=>ge(typeof e[t]==`string`?e[t]:void 0))),durationMs:N(`Press duration in milliseconds. tvOS and Vega OS use the exact hold duration; Android TV maps any positive value to an ADB longpress (${Me(`android`)}).`,{min:0})}),vm=R(Qp,`Press a phone hardware button once: volume-up, volume-down, power, mute, sleep, wake, media-play-pause, media-next, media-previous, media-rewind, or media-fast-forward. The press is dispatched without activating the session app and nothing is re-observed afterwards, so the OS decides what the key does — which audio stream a volume press moves, which media session a media key reaches, and whether the HUD shows, is device behavior this command does not claim. Power toggles the Android screen; sleep and wake are the explicit Android events that turn it off or on without toggling, and after a press that turns it off, later commands may hit a locked screen. Android (ADB-backed and Appium) presses all eleven on phones and tablets; a physical iPhone or iPad presses volume only through the local runner or Appium, never power, mute, sleep, wake, or media. iOS Simulators, Android TV and tvOS targets refuse: on TV targets use tv-remote.`,{button:A(F(Pe,`One press each. volume-up and volume-down move the system volume stream the OS selects; power toggles the screen on Android; sleep and wake are the explicit Android events that turn the screen off or on without toggling; mute, media-play-pause, media-next, media-previous, media-rewind, and media-fast-forward are Android keys the OS routes to its own streams and media sessions. All of these except volume are refused on every Apple leaf.`))}),ym={action:A(F(De,`call starts an incoming call, accept answers it, cancel ends it, sms delivers a text message.`)),number:A(j(`Caller or sender phone number: digits with an optional leading +.`)),text:j(`Message text for sms; required for sms and refused for the call actions. The emulator drops characters outside the Basic Multilingual Plane, such as emoji.`)},bm=R(nm,`Simulate an incoming phone call or SMS on an Android emulator through its console over adb: call rings from the number, accept answers, cancel ends the call, and sms delivers a text message. The call screen or notification can cover the app, so re-snapshot afterwards.`,ym,{readInput:e=>{let{action:t,number:n,text:r,...i}=ti(e,ym);return{...i,...ye({action:t,number:n,text:r})}}}),xm={...bm,inputSchema:{...bm.inputSchema,oneOf:[{properties:{action:T(`sms`)},required:[`text`]},{properties:{action:w(Ce)},not:{required:[`text`]}}]}},Sm={usageOverride:`back [--in-app|--system] [--settle]`,usageFlags:[],allowedFlags:[`backMode`,...bs(Yp)]},Cm={usageOverride:`orientation <${le.join(`|`)}>`,positionalArgs:[`orientation`]},wm={usageOverride:`fold [${pe}]`,positionalArgs:[`pose?`],allowedFlags:Qi},Tm={usageOverride:`keyboard [status|get|dismiss|enter|return]`,positionalArgs:[`action?`]},Em={usageOverride:`clipboard read | clipboard write <text>`,listUsageOverride:`clipboard read | clipboard write <text>`,positionalArgs:[`read|write`,`text?`],allowsExtraPositionals:!0},Dm={usageOverride:`tv-remote [press|longpress] ${Oe}`,listUsageOverride:`tv-remote press|longpress <button> [--duration-ms <ms>]`,positionalArgs:[`press|longpress?`,`button`],allowedFlags:[`durationMs`]},Om={usageOverride:`hardware-button ${ie}`,positionalArgs:[`button`]},km={usageOverride:be,listUsageOverride:`telephony call|accept|cancel|sms <number> [text]`,positionalArgs:[`call|accept|cancel|sms`,`number`,`text?`],allowsExtraPositionals:!0},Am=(e,t)=>({...v(t),mode:t.backMode}),jm=(e,t)=>({...v(t),orientation:fe(e[0])}),Mm=(e,t)=>({...v(t),...de({pose:e[0],keyframes:t.keyframes===void 0?void 0:ae(t.keyframes)})}),Nm=(e,t)=>({...v(t),...rh(e)}),Pm=(e,t)=>({...v(t),...ih(e)}),Fm=(e,t)=>({...v(t),...ah(e,t.durationMs)}),Im=(e,t)=>({...v(t),...oh(e)}),Lm=(e,t)=>({...v(t),...he(e)}),Rm=e=>_(Yp,[],{...e,backMode:th(e.mode)}),zm=g(Xp,e=>[S(e.orientation,`orientation requires orientation`)]),Bm=e=>{let t=de(e);return _(Zp,t.pose?[t.pose]:[],{...e,keyframes:t.keyframes?JSON.stringify(t.keyframes):void 0})},Vm=g($p,e=>y(e.action)),Hm=g(em,e=>nh(e)),Um=g(tm,e=>[S(e.button,`tv-remote requires button`)]),Wm=g(Qp,e=>[S(e.button,`hardware-button requires button`)]),Gm=g(nm,e=>Ne(ye(e))),Km=gi({name:`appstate`,description:`Show foreground app/activity (Android and HarmonyOS; iOS and macOS answer per session)`,text:{summary:`Show the foreground app and activity`},run:(e,t)=>e.command.appState(t),cliOutputFormatter:$.appstate}),qm=z({name:Yp,text:{summary:`Navigate back in the app or system`},metadata:um,run:(e,t)=>e.command.back(t),cliSchema:Sm,cliReader:Am,daemonWriter:Rm,cliOutputFormatter:$.back}),Jm=gi({name:`home`,description:`Send the selected device to its home screen. This leaves the app session open but moves the foreground away from the app.`,text:{summary:`Go to the device home screen`},run:(e,t)=>e.command.home(t),cliOutputFormatter:$.home}),Ym=z({name:Xp,text:{summary:`Set device orientation`},metadata:dm,run:(e,t)=>e.command.orientation(t),cliSchema:Cm,cliReader:jm,daemonWriter:zm,cliOutputFormatter:$.orientation}),Xm=z({name:Zp,text:{summary:`Fold or unfold a foldable iPhone simulator or Android emulator`,cliDetail:`iPhone Duo simulators and foldable Android emulators. iOS sends a ${sm.hingeEvent} and confirms the hinge angle inside the simulator; Android sets the emulator console posture and confirms the device state. Refs and coordinates do not survive a pose change.`},metadata:mm,run:(e,t)=>e.command.fold(t),cliSchema:wm,cliReader:Mm,daemonWriter:Bm,cliOutputFormatter:$.fold}),Zm=gi({name:`app-switcher`,description:`Open the device app switcher to inspect or change foreground apps. This changes the visible system UI and may move focus away from the current app.`,text:{summary:`Open the device app switcher`},run:(e,t)=>e.command.appSwitcher(t),cliOutputFormatter:$[`app-switcher`]}),Qm=z({name:$p,text:{summary:`Inspect, press, or dismiss the device keyboard`},metadata:hm,run:(e,t)=>e.command.keyboard(t),cliSchema:Tm,cliReader:Nm,daemonWriter:Vm,cliOutputFormatter:$.keyboard}),$m=z({name:em,text:{summary:`Read or write device clipboard text`},metadata:gm,run:(e,t)=>e.command.clipboard(t),cliSchema:Em,cliReader:Pm,daemonWriter:Hm,cliOutputFormatter:$.clipboard}),eh=B({name:`system`,commands:[Km,qm,Jm,Ym,Xm,Zm,gi({name:`action-button`,description:`Press the iPhone or iPad Action Button once. The press is dispatched without activating the session app and nothing is re-observed afterwards, so the app keeps the state the press found. What the system does with the press is not observed by this command: Simulators run no Shortcuts or App Intents, so delivery to an assigned Shortcut is verifiable only on a physical iPhone.`,text:{summary:`Press the iPhone or iPad Action Button`,cliDetail:`iPhone and iPad only. The runner asks the device for the button and reports unsupported when that model has none.`},run:(e,t)=>e.command.actionButton(t),cliOutputFormatter:$[`action-button`]}),Qm,$m,z({name:tm,text:{summary:`Press a TV remote navigation, media, or hardware button`,cliDetail:`longpress selects the 500ms preset; --duration-ms overrides it. Android TV uses the system long-press duration.`},metadata:_m,run:(e,t)=>e.command.tvRemote(t),cliSchema:Dm,cliReader:Fm,daemonWriter:Um,cliOutputFormatter:$[`tv-remote`]}),z({name:Qp,text:{summary:`Press a phone hardware button once`,cliDetail:`Single press; no hold. Android presses all eleven named keys on phones and tablets: volume-up, volume-down, power, mute, sleep, wake, and the five media keys. A physical iPhone or iPad presses volume only; the other keys are never supported on Apple targets. iOS Simulators, Android TV, and tvOS refuse — use tv-remote on TV targets.`},metadata:vm,run:(e,t)=>e.command.hardwareButton(t),cliSchema:Om,cliReader:Im,daemonWriter:Wm,cliOutputFormatter:$[`hardware-button`]}),z({name:nm,text:{summary:`Simulate an incoming call or SMS on an Android emulator over adb`,cliDetail:`Android emulators through the local adb executor; WebDriver (Appium) and Limrun sessions refuse it. Quote the SMS text, or pass it as the remaining words. Re-snapshot after the event: the call screen or notification can cover the app.`},metadata:xm,run:(e,t)=>e.command.telephony(t),cliSchema:km,cliReader:Lm,daemonWriter:Gm,cliOutputFormatter:$.telephony})]});function th(e){return e===`in-app`||e===`system`?e:void 0}function nh(e){return e.action===`read`?[`read`]:[`write`,e.text]}function rh(e){if(e.length>1)throw new n(`INVALID_ARGS`,`keyboard accepts at most one action argument.`);return m({action:sh(e[0])})}function ih(e){let t=e[0]?.toLowerCase();if(t!==`read`&&t!==`write`)throw new n(`INVALID_ARGS`,`clipboard requires a subcommand: read or write.`);if(t===`read`){if(e.length!==1)throw new n(`INVALID_ARGS`,`clipboard read does not accept additional arguments.`);return{action:t}}if(e.length<2)throw new n(`INVALID_ARGS`,`clipboard write requires text.`);return{action:t,text:e.slice(1).join(` `)}}function ah(e,t){let r=e[0]?.toLowerCase(),i=r===`press`||r===`longpress`?e.slice(1):e;if(i.length!==1)throw new n(`INVALID_ARGS`,`tv-remote requires exactly one button: ${we.join(`, `)}, or android-keycode:<n>.`);let a=t??(r===`longpress`?500:void 0);return m({button:ge(i[0]),durationMs:a})}function oh(e){return{button:me[se(e)]}}function sh(e){let t=e?.toLowerCase();if(t===`get`)return`status`;if(t===void 0||t===`status`||t===`dismiss`||t===`enter`||t===`return`)return t;throw new n(`INVALID_ARGS`,`keyboard action must be status, get, dismiss, enter, or return.`)}const ch=[Pc,qu,us,eh,Kf,Lp,Wd,Ff,hs,dp,$u,Gi];function lh(){return ch.flatMap(e=>[...e.metadata])}function uh(){return ch.flatMap(e=>[...e.definitions])}function dh(){return hh(`cliSchemas`)}function fh(){return hh(`cliReaders`)}function ph(){return hh(`daemonWriters`)}function mh(){return hh(`cliOutputFormatters`)}function hh(e){let t={};for(let n of ch){let r=n[e];if(r)for(let[n,i]of Object.entries(r)){if(Object.hasOwn(t,n))throw Error(`Duplicate ${String(e)} command family entry: ${n}`);t[n]=i}}return t}const gh=lh(),_h=new Map(gh.map(e=>[e.name,e]));function vh(){return[...gh]}function yh(){return Ot().map(e=>{let t=xh(e);if(!t)throw Error(`Missing command metadata for MCP-exposed command: ${e}`);return t})}function bh(e){return _h.has(e)}function xh(e){return _h.get(e)}export{ra as A,C as B,xs as C,sa as D,da as E,O as F,Zn as G,Tr as H,T as I,Nn as J,Gn as K,w as L,Fi as M,Si as N,ca as O,xi as P,k as R,Sc as S,Fo as T,Er as U,E as V,Xn as W,kn as X,On as Y,Du as _,mh as a,jl as b,ph as c,om as d,lm as f,ku as g,Gu as h,yh as i,ta as j,la as k,uh as l,Zu as m,bh as n,fh as o,Pp as p,Mn as q,vh as r,dh as s,xh as t,lh as u,Xl as v,es as w,jc as x,ql as y,D as z};
74
+ If a task asserts behavior for more than one pose, fold to each pose and re-snapshot, and report which poses the run covered.`},fm=L(Zp,`Navigate back in the app or through system navigation. Use in-app for the app navigation stack and system when the platform back behavior is required. On iOS, a single-screen iPhone or an iPad whose app provably fills its screen can use a top-leading tap when the app tree is unreadable, with before/after visual verification. A capture failure reports an unknown outcome.`,{mode:P(dt),...bs(Zp)}),pm=L(Qp,`Set device orientation on iOS and Android. auto hands rotation back to the sensor on ADB-backed Android (local and Limrun); other backends refuse it. A foldable iPhone simulator (iPhone Duo) refuses portrait-upside-down, and refuses every rotation in a scoped simulator set.`,{orientation:k(P(le))}),mm={pose:P(Fe,`Instant preset; mutually exclusive with keyframes.`),keyframes:F({type:`array`,minItems:2,maxItems:64,description:`Piecewise-linear hinge motion. Start at 0ms; strictly increasing timestamps, up to 60000ms. Repeated angles create holds. Mutually exclusive with pose.`,items:{type:`object`,required:[`atMs`,`angle`],additionalProperties:!1,properties:{atMs:{type:`integer`,minimum:0,maximum:re},angle:{type:`number`,minimum:0,maximum:180}}}})},hm=L($p,um,mm,{readInput:e=>{let{pose:t,keyframes:n,...r}=ri(e,mm);return{...r,...de({pose:t,keyframes:n})}}}),gm={...hm,inputSchema:{...hm.inputSchema,oneOf:[{required:[`pose`],not:{required:[`keyframes`]}},{required:[`keyframes`],not:{required:[`pose`]}}]}},_m=L(tm,`Inspect Android keyboard visibility/type or press/dismiss the device keyboard. To hide the keyboard, use keyboard dismiss. It taps the keyboard dismiss/hide key when one is exposed, verifies the keyboard closed, and reports UNSUPPORTED_OPERATION when no dismiss key exists — background taps are never attempted.`,{action:P(om)}),vm=L(nm,`Read the current device clipboard text, or replace its contents with the given text. Android runs both through the clipboard service shell command, and a build that implements none (Android 16 does not) refuses with UNSUPPORTED_OPERATION rather than reporting an empty clipboard.`,{action:k(P(am)),text:A()},{parseableOutput:!0}),ym=L(rm,`Press or long-press a TV remote button on Android TV, tvOS, or Vega OS. Android TV also supports volume, power, media, channel, guide, captions, input, color keys, and android-keycode:N. tvOS and Vega OS support up, down, left, right, select, menu, home, and back. Phones and WebDriver sessions are unsupported. The aliases ok, center, and enter map to select.`,{button:k(Kr(sm,(e,t)=>ge(typeof e[t]==`string`?e[t]:void 0))),durationMs:M(`Press duration in milliseconds. tvOS and Vega OS use the exact hold duration; Android TV maps any positive value to an ADB longpress (${Me(`android`)}).`,{min:0})}),bm=L(em,`Press a phone hardware button once: volume-up, volume-down, power, mute, sleep, wake, media-play-pause, media-next, media-previous, media-rewind, or media-fast-forward. The press is dispatched without activating the session app and nothing is re-observed afterwards, so the OS decides what the key does — which audio stream a volume press moves, which media session a media key reaches, and whether the HUD shows, is device behavior this command does not claim. Power toggles the Android screen; sleep and wake are the explicit Android events that turn it off or on without toggling, and after a press that turns it off, later commands may hit a locked screen. Android (ADB-backed and Appium) presses all eleven on phones and tablets; a physical iPhone or iPad presses volume only through the local runner or Appium, never power, mute, sleep, wake, or media. iOS Simulators, Android TV and tvOS targets refuse: on TV targets use tv-remote.`,{button:k(P(Pe,`One press each. volume-up and volume-down move the system volume stream the OS selects; power toggles the screen on Android; sleep and wake are the explicit Android events that turn the screen off or on without toggling; mute, media-play-pause, media-next, media-previous, media-rewind, and media-fast-forward are Android keys the OS routes to its own streams and media sessions. All of these except volume are refused on every Apple leaf.`))}),xm={action:k(P(De,`call starts an incoming call, accept answers it, cancel ends it, sms delivers a text message.`)),number:k(A(`Caller or sender phone number: digits with an optional leading +.`)),text:A(`Message text for sms; required for sms and refused for the call actions. The emulator drops characters outside the Basic Multilingual Plane, such as emoji.`)},Sm=L(im,`Simulate an incoming phone call or SMS on an Android emulator through its console over adb: call rings from the number, accept answers, cancel ends the call, and sms delivers a text message. The call screen or notification can cover the app, so re-snapshot afterwards.`,xm,{readInput:e=>{let{action:t,number:n,text:r,...i}=ri(e,xm);return{...i,...ye({action:t,number:n,text:r})}}}),Cm={...Sm,inputSchema:{...Sm.inputSchema,oneOf:[{properties:{action:w(`sms`)},required:[`text`]},{properties:{action:C(Ce)},not:{required:[`text`]}}]}},wm={usageOverride:`back [--in-app|--system] [--settle]`,usageFlags:[],allowedFlags:[`backMode`,...xs(Zp)]},Tm={usageOverride:`orientation <${le.join(`|`)}>`,positionalArgs:[`orientation`]},Em={usageOverride:`fold [${pe}]`,positionalArgs:[`pose?`],allowedFlags:ea},Dm={usageOverride:`keyboard [status|get|dismiss|enter|return]`,positionalArgs:[`action?`]},Om={usageOverride:`clipboard read | clipboard write <text>`,listUsageOverride:`clipboard read | clipboard write <text>`,positionalArgs:[`read|write`,`text?`],allowsExtraPositionals:!0},km={usageOverride:`tv-remote [press|longpress] ${Oe}`,listUsageOverride:`tv-remote press|longpress <button> [--duration-ms <ms>]`,positionalArgs:[`press|longpress?`,`button`],allowedFlags:[`durationMs`]},Am={usageOverride:`hardware-button ${ie}`,positionalArgs:[`button`]},jm={usageOverride:be,listUsageOverride:`telephony call|accept|cancel|sms <number> [text]`,positionalArgs:[`call|accept|cancel|sms`,`number`,`text?`],allowsExtraPositionals:!0},Mm=(e,t)=>({..._(t),mode:t.backMode}),Nm=(e,t)=>({..._(t),orientation:fe(e[0])}),Pm=(e,t)=>({..._(t),...de({pose:e[0],keyframes:t.keyframes===void 0?void 0:ae(t.keyframes)})}),Fm=(e,t)=>({..._(t),...ah(e)}),Im=(e,t)=>({..._(t),...oh(e)}),Lm=(e,t)=>({..._(t),...sh(e,t.durationMs)}),Rm=(e,t)=>({..._(t),...ch(e)}),zm=(e,t)=>({..._(t),...he(e)}),Bm=e=>g(Zp,[],{...e,backMode:rh(e.mode)}),Vm=h(Qp,e=>[x(e.orientation,`orientation requires orientation`)]),Hm=e=>{let t=de(e);return g($p,t.pose?[t.pose]:[],{...e,keyframes:t.keyframes?JSON.stringify(t.keyframes):void 0})},Um=h(tm,e=>v(e.action)),Wm=h(nm,e=>ih(e)),Gm=h(rm,e=>[x(e.button,`tv-remote requires button`)]),Km=h(em,e=>[x(e.button,`hardware-button requires button`)]),qm=h(im,e=>Ne(ye(e))),Jm=vi({name:`appstate`,description:`Show foreground app/activity (Android and HarmonyOS; iOS and macOS answer per session)`,text:{summary:`Show the foreground app and activity`},run:(e,t)=>e.command.appState(t),cliOutputFormatter:$.appstate}),Ym=R({name:Zp,text:{summary:`Navigate back in the app or system`},metadata:fm,run:(e,t)=>e.command.back(t),cliSchema:wm,cliReader:Mm,daemonWriter:Bm,cliOutputFormatter:$.back}),Xm=vi({name:`home`,description:`Send the selected device to its home screen. This leaves the app session open but moves the foreground away from the app.`,text:{summary:`Go to the device home screen`},run:(e,t)=>e.command.home(t),cliOutputFormatter:$.home}),Zm=R({name:Qp,text:{summary:`Set device orientation`},metadata:pm,run:(e,t)=>e.command.orientation(t),cliSchema:Tm,cliReader:Nm,daemonWriter:Vm,cliOutputFormatter:$.orientation}),Qm=R({name:$p,text:{summary:`Fold or unfold a foldable iPhone simulator or Android emulator`,cliDetail:`iPhone Duo simulators and foldable Android emulators. iOS sends a ${lm.hingeEvent} and confirms the hinge angle inside the simulator; Android sets the emulator console posture and confirms the device state. Refs and coordinates do not survive a pose change.`},metadata:gm,run:(e,t)=>e.command.fold(t),cliSchema:Em,cliReader:Pm,daemonWriter:Hm,cliOutputFormatter:$.fold}),$m=vi({name:`app-switcher`,description:`Open the device app switcher to inspect or change foreground apps. This changes the visible system UI and may move focus away from the current app.`,text:{summary:`Open the device app switcher`},run:(e,t)=>e.command.appSwitcher(t),cliOutputFormatter:$[`app-switcher`]}),eh=R({name:tm,text:{summary:`Inspect, press, or dismiss the device keyboard`},metadata:_m,run:(e,t)=>e.command.keyboard(t),cliSchema:Dm,cliReader:Fm,daemonWriter:Um,cliOutputFormatter:$.keyboard}),th=R({name:nm,text:{summary:`Read or write device clipboard text`},metadata:vm,run:(e,t)=>e.command.clipboard(t),cliSchema:Om,cliReader:Im,daemonWriter:Wm,cliOutputFormatter:$.clipboard}),nh=z({name:`system`,commands:[Jm,Ym,Xm,Zm,Qm,$m,vi({name:`action-button`,description:`Press the iPhone or iPad Action Button once. The press is dispatched without activating the session app and nothing is re-observed afterwards, so the app keeps the state the press found. What the system does with the press is not observed by this command: Simulators run no Shortcuts or App Intents, so delivery to an assigned Shortcut is verifiable only on a physical iPhone.`,text:{summary:`Press the iPhone or iPad Action Button`,cliDetail:`iPhone and iPad only. The runner asks the device for the button and reports unsupported when that model has none.`},run:(e,t)=>e.command.actionButton(t),cliOutputFormatter:$[`action-button`]}),eh,th,R({name:rm,text:{summary:`Press a TV remote navigation, media, or hardware button`,cliDetail:`longpress selects the 500ms preset; --duration-ms overrides it. Android TV uses the system long-press duration.`},metadata:ym,run:(e,t)=>e.command.tvRemote(t),cliSchema:km,cliReader:Lm,daemonWriter:Gm,cliOutputFormatter:$[`tv-remote`]}),R({name:em,text:{summary:`Press a phone hardware button once`,cliDetail:`Single press; no hold. Android presses all eleven named keys on phones and tablets: volume-up, volume-down, power, mute, sleep, wake, and the five media keys. A physical iPhone or iPad presses volume only; the other keys are never supported on Apple targets. iOS Simulators, Android TV, and tvOS refuse — use tv-remote on TV targets.`},metadata:bm,run:(e,t)=>e.command.hardwareButton(t),cliSchema:Am,cliReader:Rm,daemonWriter:Km,cliOutputFormatter:$[`hardware-button`]}),R({name:im,text:{summary:`Simulate an incoming call or SMS on an Android emulator over adb`,cliDetail:`Android emulators through the local adb executor; WebDriver (Appium) and Limrun sessions refuse it. Quote the SMS text, or pass it as the remaining words. Re-snapshot after the event: the call screen or notification can cover the app.`},metadata:Cm,run:(e,t)=>e.command.telephony(t),cliSchema:jm,cliReader:zm,daemonWriter:qm,cliOutputFormatter:$.telephony})]});function rh(e){return e===`in-app`||e===`system`?e:void 0}function ih(e){return e.action===`read`?[`read`]:[`write`,e.text]}function ah(e){if(e.length>1)throw new n(`INVALID_ARGS`,`keyboard accepts at most one action argument.`);return m({action:lh(e[0])})}function oh(e){let t=e[0]?.toLowerCase();if(t!==`read`&&t!==`write`)throw new n(`INVALID_ARGS`,`clipboard requires a subcommand: read or write.`);if(t===`read`){if(e.length!==1)throw new n(`INVALID_ARGS`,`clipboard read does not accept additional arguments.`);return{action:t}}if(e.length<2)throw new n(`INVALID_ARGS`,`clipboard write requires text.`);return{action:t,text:e.slice(1).join(` `)}}function sh(e,t){let r=e[0]?.toLowerCase(),i=r===`press`||r===`longpress`?e.slice(1):e;if(i.length!==1)throw new n(`INVALID_ARGS`,`tv-remote requires exactly one button: ${we.join(`, `)}, or android-keycode:<n>.`);let a=t??(r===`longpress`?500:void 0);return m({button:ge(i[0]),durationMs:a})}function ch(e){return{button:me[se(e)]}}function lh(e){let t=e?.toLowerCase();if(t===`get`)return`status`;if(t===void 0||t===`status`||t===`dismiss`||t===`enter`||t===`return`)return t;throw new n(`INVALID_ARGS`,`keyboard action must be status, get, dismiss, enter, or return.`)}const uh=[Fc,Yu,ds,nh,Jf,zp,Kd,Lf,gs,pp,td,qi];function dh(){return uh.flatMap(e=>[...e.metadata])}function fh(){return uh.flatMap(e=>[...e.definitions])}function ph(){return _h(`cliSchemas`)}function mh(){return _h(`cliReaders`)}function hh(){return _h(`daemonWriters`)}function gh(){return _h(`cliOutputFormatters`)}function _h(e){let t={};for(let n of uh){let r=n[e];if(r)for(let[n,i]of Object.entries(r)){if(Object.hasOwn(t,n))throw Error(`Duplicate ${String(e)} command family entry: ${n}`);t[n]=i}}return t}const vh=dh(),yh=new Map(vh.map(e=>[e.name,e]));function bh(){return[...vh]}function xh(){return kt().map(e=>{let t=Ch(e);if(!t)throw Error(`Missing command metadata for MCP-exposed command: ${e}`);return t})}function Sh(e){return yh.has(e)}function Ch(e){return yh.get(e)}export{ia as A,S as B,Ss as C,ca as D,fa as E,D as F,Qn as G,Dr as H,w as I,Pn as J,Kn as K,C as L,Li as M,wi as N,la as O,Ci as P,O as R,Cc as S,Io as T,Or as U,T as V,Zn as W,An as X,kn as Y,ku as _,gh as a,Nl as b,hh as c,cm as d,dm as f,ju as g,qu as h,xh as i,na as j,ua as k,fh as l,$u as m,Sh as n,mh as o,Ip as p,Nn as q,bh as r,ph as s,Ch as t,dh as u,Ql as v,ts as w,Mc as x,Yl as y,E as z};