agent-device 0.21.29 → 0.21.30

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 (177) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.29.apk → agent-device-android-ime-helper-0.21.30.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.30.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.29.manifest.json → agent-device-android-ime-helper-0.21.30.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.29.manifest.json → agent-device-android-snapshot-helper-0.21.30.manifest.json} +7 -7
  7. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift +4 -2
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift +2 -1
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +12 -0
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +25 -0
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +8 -1
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +9 -6
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +3 -0
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +35 -9
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +44 -26
  16. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +20 -1
  17. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentation.swift +4 -3
  18. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationProjection.swift +4 -2
  19. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFold.swift +20 -2
  20. package/dist/src/adapter.js +1 -1
  21. package/dist/src/agent-browser-lifecycle.js +1 -1
  22. package/dist/src/agent-browser-process-record.js +1 -1
  23. package/dist/src/agent-browser-provider.js +1 -1
  24. package/dist/src/agent-device-client.js +1 -1
  25. package/dist/src/alert2.js +1 -1
  26. package/dist/src/android.js +1 -1
  27. package/dist/src/app-lifecycle.js +1 -1
  28. package/dist/src/app-log-runtime2.js +3 -3
  29. package/dist/src/auth.js +1 -1
  30. package/dist/src/automation-helper.js +1 -1
  31. package/dist/src/back-mode.js +1 -1
  32. package/dist/src/cli-config.js +1 -1
  33. package/dist/src/cli-help.js +13 -10
  34. package/dist/src/cli.js +3 -3
  35. package/dist/src/client-types.d.ts +82 -13
  36. package/dist/src/cloud-artifacts.d.ts +99 -3
  37. package/dist/src/command-metadata.js +42 -42
  38. package/dist/src/composed-inventory-gateways.js +1 -1
  39. package/dist/src/connection-runtime.js +1 -1
  40. package/dist/src/connection.js +1 -1
  41. package/dist/src/contract.d.ts +2 -2
  42. package/dist/src/contracts.d.ts +1 -1
  43. package/dist/src/daemon-client-ensure.js +1 -1
  44. package/dist/src/daemon-client-ensuring.js +1 -1
  45. package/dist/src/daemon-client-lease-beat.js +1 -1
  46. package/dist/src/daemon-client-lifecycle.js +1 -1
  47. package/dist/src/daemon-client.js +2 -2
  48. package/dist/src/daemon-lifecycle-errors.js +1 -1
  49. package/dist/src/daemon-registration-owner.js +3 -3
  50. package/dist/src/daemon-registration.js +1 -1
  51. package/dist/src/daemon-resolution.js +1 -1
  52. package/dist/src/daemon-shutdown-report.js +1 -1
  53. package/dist/src/daemon-startup-diagnostics.js +1 -1
  54. package/dist/src/daemon.js +3 -3
  55. package/dist/src/device-claim-recovery.js +1 -1
  56. package/dist/src/durable-capture-resource.js +1 -1
  57. package/dist/src/durable-resource.js +1 -1
  58. package/dist/src/ended-lease.js +1 -1
  59. package/dist/src/find.js +1 -1
  60. package/dist/src/finders.js +1 -1
  61. package/dist/src/gesture-plan-types.d.ts +14 -4
  62. package/dist/src/gesture-plan.js +1 -1
  63. package/dist/src/gesture-runtime.js +1 -1
  64. package/dist/src/host4.js +1 -1
  65. package/dist/src/index.d.ts +3 -3
  66. package/dist/src/input-actions.js +1 -1
  67. package/dist/src/input-actions2.js +1 -1
  68. package/dist/src/interaction-positionals.js +1 -1
  69. package/dist/src/interaction.js +1 -1
  70. package/dist/src/interaction2.js +1 -1
  71. package/dist/src/interactor-operation-catalog.js +1 -1
  72. package/dist/src/interactor.js +5 -5
  73. package/dist/src/interactor3.js +1 -1
  74. package/dist/src/interactor4.js +1 -1
  75. package/dist/src/internal/bin.js +1 -1
  76. package/dist/src/internal/daemon.js +1 -1
  77. package/dist/src/internal/png-worker.js +1 -1
  78. package/dist/src/inventory6.js +1 -1
  79. package/dist/src/ios-node-interpretation.js +1 -1
  80. package/dist/src/ios-snapshot-acquisition.js +1 -1
  81. package/dist/src/ios-snapshot-engine.js +1 -1
  82. package/dist/src/ios-snapshot-runtime.js +1 -1
  83. package/dist/src/keyboard-occlusion.js +1 -1
  84. package/dist/src/launch-confirmation.js +1 -1
  85. package/dist/src/lease-context.js +1 -1
  86. package/dist/src/lease-registry-scope.js +1 -1
  87. package/dist/src/lease.js +1 -1
  88. package/dist/src/local-interactor-operation-set.js +1 -1
  89. package/dist/src/mechanics.js +12 -12
  90. package/dist/src/metro-session-hints.js +1 -1
  91. package/dist/src/mobile-snapshot-semantics.js +1 -1
  92. package/dist/src/observability.js +1 -1
  93. package/dist/src/observation.js +1 -1
  94. package/dist/src/parameterized-recorded-fill.js +1 -1
  95. package/dist/src/perf-facade.js +1 -1
  96. package/dist/src/platform-runtime-operation-host.js +1 -1
  97. package/dist/src/platform-runtime-unavailable.js +1 -1
  98. package/dist/src/platform-runtime.js +1 -1
  99. package/dist/src/platform-runtime2.js +1 -1
  100. package/dist/src/plugins2.js +1 -1
  101. package/dist/src/png-resize.js +1 -1
  102. package/dist/src/png-worker-client.js +1 -1
  103. package/dist/src/png-worker-contract.js +1 -1
  104. package/dist/src/provider-device-runtime.d.ts +20 -1
  105. package/dist/src/provider-plugin.d.ts +1 -1
  106. package/dist/src/react-native-overlay2.js +1 -1
  107. package/dist/src/record-runtime.js +1 -1
  108. package/dist/src/replay-maestro-backend.js +3 -3
  109. package/dist/src/replay-script-selection.js +1 -1
  110. package/dist/src/replay.d.ts +1 -1
  111. package/dist/src/request-runtime-binding.js +1 -1
  112. package/dist/src/result-serialization.js +1 -1
  113. package/dist/src/runner-error-classification.js +1 -1
  114. package/dist/src/runtime-admission.js +1 -1
  115. package/dist/src/runtime-deployment.js +1 -1
  116. package/dist/src/runtime-factory.js +1 -1
  117. package/dist/src/runtime-session.js +1 -1
  118. package/dist/src/runtime.js +5 -5
  119. package/dist/src/runtime10.js +2 -2
  120. package/dist/src/runtime3.js +5 -5
  121. package/dist/src/runtime5.js +1 -1
  122. package/dist/src/runtime6.js +1 -1
  123. package/dist/src/runtime7.js +1 -1
  124. package/dist/src/runtime8.js +1 -1
  125. package/dist/src/runtime9.js +2 -2
  126. package/dist/src/screenshot-image-size.js +1 -0
  127. package/dist/src/screenshot-image.js +1 -1
  128. package/dist/src/screenshot-runtime.js +1 -1
  129. package/dist/src/screenshot3.js +2 -2
  130. package/dist/src/sdk-batch.js +1 -1
  131. package/dist/src/sdk-contracts.d.ts +7 -1
  132. package/dist/src/sdk-finders.js +1 -1
  133. package/dist/src/sdk-selectors.d.ts +1 -1
  134. package/dist/src/sdk-selectors.js +1 -1
  135. package/dist/src/selection.js +0 -0
  136. package/dist/src/selector-pipeline-policy.js +1 -1
  137. package/dist/src/selector-runtime.js +1 -1
  138. package/dist/src/selectors.js +1 -1
  139. package/dist/src/server-startup.js +1 -1
  140. package/dist/src/session-replay-vars.js +1 -1
  141. package/dist/src/session-store.js +2 -2
  142. package/dist/src/session.js +1 -1
  143. package/dist/src/session2.js +5 -5
  144. package/dist/src/settle-observation-capture.js +1 -1
  145. package/dist/src/snapshot-capture-annotations.js +1 -1
  146. package/dist/src/snapshot-chrome.js +1 -1
  147. package/dist/src/snapshot-desktop-projection.js +1 -1
  148. package/dist/src/snapshot-helper-install.js +7 -5
  149. package/dist/src/snapshot-node-lookup.js +1 -1
  150. package/dist/src/snapshot-occlusion.js +1 -1
  151. package/dist/src/snapshot-runtime-binding.js +1 -1
  152. package/dist/src/snapshot-runtime-capture-input.js +1 -1
  153. package/dist/src/snapshot-runtime.js +1 -1
  154. package/dist/src/snapshot-state.js +1 -1
  155. package/dist/src/snapshot.js +1 -1
  156. package/dist/src/src.js +1 -1
  157. package/dist/src/src3.js +1 -1
  158. package/dist/src/src4.js +1 -1
  159. package/dist/src/tap-keyboard-occlusion.js +1 -1
  160. package/dist/src/target-evidence-tree.js +1 -1
  161. package/dist/src/target-evidence.js +1 -1
  162. package/dist/src/telephony-runtime.js +1 -1
  163. package/dist/src/text-entry-focus.js +1 -1
  164. package/dist/src/touch-reference-frame.js +1 -1
  165. package/dist/src/touch-runtime2.js +1 -1
  166. package/dist/src/tree.js +1 -1
  167. package/dist/src/tv-remote-runtime.js +1 -1
  168. package/dist/src/tv-remote.js +2 -2
  169. package/dist/src/type-text-runtime.js +1 -1
  170. package/dist/src/video.js +1 -1
  171. package/dist/src/webdriver-source.js +1 -1
  172. package/package.json +1 -1
  173. package/server.json +2 -2
  174. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.29.apk.sha256 +0 -1
  175. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.29.apk +0 -0
  176. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.29.apk.sha256 +0 -1
  177. package/dist/src/daemon-client-lifecycle-request.js +0 -1
@@ -1,43 +1,43 @@
1
- import{A as e,C as t,L as n,O as r,R as i,h as a,j as o,n as s,v as c}from"./sdk-contracts.js";import{$ as l,Ct as ee,D as te,E as ne,L as re,Q as ie,St as ae,Tt as oe,X as se,Y as ce,_ as le,b as ue,c as de,d as fe,et as pe,f as me,ft as he,g as ge,gt as _e,k as ve,l as ye,n as be,p as xe,pt as Se,r as Ce,s as we,t as Te,u as Ee,v as De,wt as Oe,xt as ke,y as Ae}from"./tv-remote.js";import{c as je,d as Me,f as Ne,h as Pe,j as Fe,l as Ie,m as Le,s as Re,u as ze,v as u}from"./sdk-batch-runner.js";import{$ as Be,E as d,M as Ve,S as He,T as Ue,Tt as We,Z as Ge,at as Ke,c as qe,g as Je,gt as Ye,it as Xe,j as Ze,k as Qe,m as $e,n as et,p as tt,pt as nt,rt,t as it,x as at}from"./back-mode.js";import{ut as ot}from"./sdk-io.js";import{a as st,i as ct,n as lt,t as ut}from"./sdk-device.js";import{Bt as dt,Er as ft,Hr as pt,Lr as mt,Mn as ht,Pn as gt,Rn as _t,_ as vt,br as yt,dn as bt,hr as xt,i as St,ln as Ct,m as wt,mr as Tt,p as Et,pr as Dt,s as Ot,si as kt,vr as At}from"./sdk-batch.js";import{n as jt}from"./recording-export-quality.js";import{t as Mt}from"./recording-scope.js";import{a as Nt,i as Pt,r as Ft}from"./vars.js";import{t as It}from"./session.js";import{a as Lt,c as Rt,d as zt,f as Bt,g as Vt,h as Ht,i as Ut,l as Wt,n as Gt,o as Kt,p as qt,s as Jt,t as Yt,u as Xt}from"./observability.js";import{n as Zt,t as Qt}from"./success-text.js";import{t as $t}from"./alert-contract.js";import{h as en,l as tn,n as nn,v as rn,x as an,y as on}from"./settings.js";import{t as sn}from"./location-coordinates.js";import{t as cn}from"./snapshot-quality-backend-capabilities.js";import{t as ln}from"./mobile-snapshot-semantics.js";import{t as un}from"./absence-observation-errors.js";import{n as dn,t as fn}from"./interaction-positionals.js";import{t as pn}from"./app-inventory.js";import{c as mn,o as hn}from"./file.js";import gn from"node:fs";import f from"node:path";const _n=[`path`,`start`,`stop`,`doctor`,`mark`,`clear`],vn=new Set(at().map(e=>e.key));function yn(t){let n=nt(t);return Fe({stateDir:t.stateDir,daemonBaseUrl:t.daemonBaseUrl,daemonTransport:t.daemonTransport,daemonServerMode:t.daemonServerMode,...Ye(n),provider:t.provider,providerSessionId:t.providerSessionId,providerApp:t.providerApp,providerOsVersion:t.providerOsVersion,providerDeviceType:t.providerDeviceType,providerProject:t.providerProject,providerBuild:t.providerBuild,providerSessionName:t.providerSessionName,providerDeviceOrientation:t.providerDeviceOrientation,providerGeoLocation:t.providerGeoLocation,providerTimezone:t.providerTimezone,providerAppiumVersion:t.providerAppiumVersion,providerLanguage:t.providerLanguage,providerLocale:t.providerLocale,providerNetworkProfile:t.providerNetworkProfile,providerCustomNetwork:t.providerCustomNetwork,providerNoResignApp:t.providerNoResignApp,awsProjectArn:t.awsProjectArn,awsDeviceArn:t.awsDeviceArn,awsAppArn:t.awsAppArn,awsRegion:t.awsRegion,awsInteractionMode:t.awsInteractionMode,sessionIsolation:t.sessionIsolation,platform:t.platform,target:t.target,device:t.device,udid:t.udid,serial:t.serial,iosSimulatorDeviceSet:t.iosSimulatorDeviceSet,iosXctestrunFile:t.iosXctestrunFile,iosXctestDerivedDataPath:t.iosXctestDerivedDataPath,iosXctestEnvDir:t.iosXctestEnvDir,androidDeviceAllowlist:t.androidDeviceAllowlist,surface:t.surface,activity:t.activity,launchConsole:t.launchConsole,launchArgs:t.launchArgs,relaunch:t.relaunch,shutdown:t.shutdown,saveScript:t.saveScript,testIme:t.testIme,noRecord:t.noRecord,recordAs:t.recordAs,record:t.record,backMode:t.backMode,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,launchUrl:t.launchUrl,...e(t,c),...ke(t),appsFilter:t.appsFilter,kind:t.kind,out:t.out,count:t.count,fps:t.fps,quality:t.quality,hideTouches:t.hideTouches,recordingScope:t.recordingScope,intervalMs:t.intervalMs,delayMs:t.delayMs,durationMs:t.durationMs,holdMs:t.holdMs,jitterPx:t.jitterPx,pixels:t.pixels,until:t.until,maxPasses:t.maxPasses,doubleTap:t.doubleTap,verify:t.verify,settle:t.settle,settleQuietMs:t.settleQuietMs,clickButton:t.clickButton,pauseMs:t.pauseMs,pattern:t.pattern,headless:t.headless,restart:t.restart,replayUpdate:t.replayUpdate,replayBackend:t.replayBackend,replayEnv:t.replayEnv,replayShellEnv:t.replayShellEnv,replayScriptSource:t.replayScriptSource,replayScriptSources:t.replayScriptSources,replayFrom:t.replayFrom,replayPlanDigest:t.replayPlanDigest,replayKeepSession:t.replayKeepSession,failFast:t.failFast,timeoutMs:t.timeoutMs,retries:t.retries,recordVideo:t.recordVideo,artifactsDir:t.artifactsDir,shardAll:t.shardAll,shardSplit:t.shardSplit,findFirst:t.findFirst,findLast:t.findLast,networkInclude:t.networkInclude,batchOnError:t.batchOnError,batchMaxSteps:t.batchMaxSteps,batchSteps:t.batchSteps,verbose:t.debug})}function bn(e,t){return{...yn(e),...t}}function xn(e,t){let n=e.inputSchema.properties;if(!n)return{};let r={},i=t;for(let e of Object.keys(n)){if(!vn.has(e))continue;let t=i[e];Sn(t)&&(r[e]=t)}return r}function Sn(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`}function Cn(e,t,n){if(Object.hasOwn(e,t))throw new i(`INVALID_ARGS`,n)}function wn(e){return{kind:`operator`,source:e}}function Tn(e,t){return`${e} is not accepted as a tool argument. ${En(e,t)}`}function En(e,t){if(`operatorPath`in t)return t.operatorPath;let n=`for the process serving these tools.`,r=(t.envFlagKeys??[e]).map(ot).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 Dn(e){if(e==null)return{};if(!e||typeof e!=`object`||Array.isArray(e))throw new i(`INVALID_ARGS`,`Expected object arguments.`);return e}function On(e,t){let n=e[t];if(!n||typeof n!=`object`||Array.isArray(n))throw new i(`INVALID_ARGS`,`Expected ${t} to be an object.`);return n}function kn(e,t){let n=e[t];if(typeof n!=`string`||n.length===0)throw new i(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return n}function An(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new i(`INVALID_ARGS`,`Expected ${t} to be a string.`);return n}}function p(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`||n.length===0)throw new i(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return n}}function jn(e,t){let n=e[t];if(typeof n!=`number`||!Number.isFinite(n))throw new i(`INVALID_ARGS`,`Expected ${t} to be a finite number.`);return n}function Mn(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw new i(`INVALID_ARGS`,`Expected ${t} to be a boolean.`);return n}}function Nn(e,t,n){let r=e[t];if(typeof r!=`string`||!n.includes(r))throw new i(`INVALID_ARGS`,`Expected ${t} to be one of: ${n.join(`, `)}.`);return r}function Pn(e,t,n){let r=e[t];if(r!==void 0){if(typeof r!=`string`||!n.includes(r))throw new i(`INVALID_ARGS`,`Expected ${t} to be one of: ${n.join(`, `)}.`);return r}}function Fn(e,t){let n=e[t];if(n!==void 0){if(!n||typeof n!=`object`||Array.isArray(n))throw new i(`INVALID_ARGS`,`Expected ${t} to be an object.`);return n}}function In(e,t){let n=e[t];if(n!==void 0){if(!Array.isArray(n)||n.some(e=>typeof e!=`string`))throw new i(`INVALID_ARGS`,`Expected ${t} to be an array of strings.`);return n}}function Ln(e,t,n,r){let a=new Set(t),o=Object.keys(e).filter(e=>!a.has(e));if(o.length>0)throw new i(`INVALID_ARGS`,`${n} has unknown field(s): ${o.join(`, `)}.`,r===void 0?void 0:{hint:r})}function m(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}const Rn=wn({operatorConfig:!0}),zn=`readinessTimeoutMs was removed; add an explicit wait for the target before the interaction.`,Bn={session:{schema:{type:`string`,description:`Agent-device session name.`},read:e=>p(e,`session`),flagKey:`session`,flagIn:[`input`]},platform:{schema:{type:`string`,enum:ct,description:`Platform selector used to resolve a device.`},read:e=>Pn(e,`platform`,ct),flagKey:`platform`,flagIn:[`input`,`selection`]},deviceTarget:{schema:{type:`string`,enum:lt,description:`Device target form. Maps to the CLI --target flag.`},read:qn,clientKey:`target`,flagKey:`target`,flagIn:[`input`,`selection`]},target:{schema:{type:`string`,enum:lt,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:wn({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:Rn,flagKey:`iosXctestrunFile`,flagIn:[`input`]},iosXctestDerivedDataPath:{schema:{type:`string`,description:`Derived data path for external iOS XCTest runner execution.`},read:e=>p(e,`iosXctestDerivedDataPath`),audience:Rn,flagKey:`iosXctestDerivedDataPath`,flagIn:[`input`]},iosXctestEnvDir:{schema:{type:`string`,description:`Writable directory for iOS XCTest runner env overlays.`},read:e=>p(e,`iosXctestEnvDir`),audience:Rn,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=>Mn(e,`noRecord`),flagKey:`noRecord`,flagIn:[`input`,`selection`]},readinessTimeoutMs:{audience:{kind:`retired`,message:zn},read:e=>Cn(e,`readinessTimeoutMs`,zn)},daemonBaseUrl:{schema:{type:`string`,description:`Remote daemon base URL.`},read:e=>p(e,`daemonBaseUrl`),audience:Rn},daemonAuthToken:{schema:{type:`string`,description:`Remote daemon auth token.`},read:e=>p(e,`daemonAuthToken`),audience:Rn},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:wn({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=>Mn(e,`debug`)}},Vn=Object.entries(Bn),Hn=Object.fromEntries(Vn.flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]));function Un(e){for(let[t,n]of Object.entries(Hn))n.kind===`retired`&&Cn(e,t,n.message)}function Wn(){return Object.fromEntries(Vn.flatMap(([e,t])=>t.schema?[[e,t.schema]]:[]))}function Gn(e,t={}){let n={};for(let[r,i]of Vn)i.read&&(n[r]=i.read(e,t));return n}function h(e){let t={};for(let[n,r]of Vn)r.read&&(t[r.clientKey??n]=e[n]);return m(t)}function Kn(e,t){let n={};for(let[r,i]of Vn){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 qn(e,t){let n=Pn(e,`deviceTarget`,lt);if(t.readTargetAlias===!1||e.target===void 0)return n;let r=Pn(e,`target`,lt);if(n!==void 0&&r!==n)throw new i(`INVALID_ARGS`,`Expected target alias to match deviceTarget when both are set.`);return n??r}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:Jn(n)}}function Jn(e){let t=Yn(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 Yn(e){return e===`mobile`||e===`tv`||e===`desktop`?e:void 0}function v(e){return m(Kn(e,`input`))}function Xn(e){return m({record:e.record})}function Zn(e){return Kn(e,`selection`)}function Qn(e){return m({depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw})}function $n(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function er(e){return m({settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs})}function tr(e){return m({count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap})}function nr(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 rr(e){let t=ar(e);if(typeof t.ref==`string`)return[t.ref,...sr(t.label)];if(typeof t.selector==`string`)return[t.selector];if(t.kind===`point`||t.x!==void 0||t.y!==void 0)return[String(or(t.x,`x`)),String(or(t.y,`y`))];throw new i(`INVALID_ARGS`,`interaction requires @ref, selector, or point target`)}function ir(e){let t=ar(e);if(typeof t.ref==`string`)return[t.ref,...sr(t.label)];if(typeof t.selector==`string`)return[t.selector];throw new i(`INVALID_ARGS`,`element command requires @ref or selector target`)}function ar(e){if(!e||typeof e!=`object`||Array.isArray(e))throw new i(`INVALID_ARGS`,`Expected target object.`);let t=e,n=t.target;return n&&typeof n==`object`&&!Array.isArray(n)?n:t}function or(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw new i(`INVALID_ARGS`,`point target requires numeric ${t}.`);return e}function sr(e){return typeof e==`string`&&e.length>0?[e]:[]}function cr(e){let t=Tt(e);if(!t.ok)throw new i(t.code,t.message);return`ref`in t?{ref:t.ref,label:fr(e.slice(1))}:{selector:t.selector}}function lr(e){let t=xt(e);if(!t.ok)throw new i(t.code,t.message);return t.format}function ur(e,t={}){let n=ft(e,t);if(!n)throw new i(`INVALID_ARGS`,Dt);return n}function dr(e,t){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}throw new i(`INVALID_ARGS`,`${t} must be a JSON object`)}function fr(e){return e.join(` `).trim()||void 0}function pr(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function mr(e,t){if(e===void 0)return;let n=Number(e);if(Number.isFinite(n))return n;throw new i(`INVALID_ARGS`,`${t} must be a finite number.`)}function hr(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 i(`INVALID_ARGS`,t);return e}function S(e,t){if(typeof e!=`string`||e.length===0)throw new i(`INVALID_ARGS`,t);return e}function gr(e){return yr(e.description,e.cliDetail)}function _r(e){return yr(e.description,e.mcpDetail)}function vr(e,t){return{...e,description:t}}function yr(e,t){return t?`${e} ${t}`:e}function br(e){return e}const xr=[`ref`,`selector`,`point`];function Sr(e,t=[]){return{type:`object`,properties:{...Wn(),...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 Cr(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 wr(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 Tr(e){return{type:`integer`,...e?{description:e}:{}}}function O(e){return{type:`boolean`,...e?{description:e}:{}}}function Er(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?An:p)}function Dr(e){return{schema:{type:`null`},required:!1,audience:{kind:`retired`,message:e},read:(t,n)=>Cn(t,n,e)}}function Or(e,t){return{...e,audience:{kind:`operator`,source:t}}}function M(e,t={}){return L(D(e,t),(e,n)=>Pe(e,n,t))}function N(e,t={}){return L(Xr(e,t),(e,n)=>Le(e,n,t))}function P(e){return L(O(e),Mn)}function kr(e){return jr(Ar(e))}function Ar(e){let[t,...n]=He(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 jr(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(Mr(e),t);case`booleanOrString`:throw Error(`Flag ${e.key} is booleanOrString; declare its field shape explicitly with jsonSchemaField`)}}function Mr(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)=>Pn(t,n,e))}function Nr(e){return L(k(e),Fn)}function Pr(e){return L(Er(e),In)}function I(e){return L(e,(e,t)=>e[t])}function Fr(e,t){return L(e,t)}function Ir(){return L(ei(),(e,t)=>e[t]===void 0?void 0:Ur(e,t))}function Lr(){return L(ti(),(e,t)=>e[t]===void 0?void 0:Wr(e,t))}function Rr(e){return L(Cr(e),(e,t)=>e[t]===void 0?void 0:Gr(e,t))}function zr(){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 Br(){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 Vr(e){return Sr(Zr(e),Qr(e))}function Hr(e,t){let n=Dn(e),r=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{let r=t.read(n,e);if(t.required&&r===void 0)throw new i(`INVALID_ARGS`,`Expected ${e} to be set.`);return r===void 0?[]:[[e,r]]})),a=Gn(n,{readTargetAlias:!Object.hasOwn(t,`target`)});return m({...a,...h(a),...r})}function Ur(e,t){let n=On(e,t),r=Nn(n,`kind`,xr);switch(r){case`ref`:return{kind:r,ref:kn(n,`ref`),label:p(n,`label`)};case`selector`:return{kind:r,selector:kn(n,`selector`)};case`point`:return{kind:r,x:jn(n,`x`),y:jn(n,`y`)}}}function Wr(e,t){let n=On(e,t),r=Nn(n,`kind`,[`ref`,`selector`]);return r===`ref`?{kind:r,ref:kn(n,`ref`),label:p(n,`label`)}:{kind:r,selector:kn(n,`selector`)}}function Gr(e,t){let n=On(e,t);return{x:jn(n,`x`),y:jn(n,`y`)}}function Kr(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 qr(e){switch(e.kind){case`ref`:return{ref:e.ref,label:e.label};case`selector`:return{selector:e.selector}}}function Jr(e){return{count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap}}function Yr(e){return{depth:e.depth,scope:e.scope,raw:e.raw}}function L(e,t){return{schema:e,required:!1,read:t}}function Xr(e,t){return{...Tr(e),...t.min===void 0?{}:{minimum:t.min},...t.max===void 0?{}:{maximum:t.max}}}function Zr(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.audience?.kind!==`retired`).map(([e,t])=>[e,t.schema]))}function Qr(e){return Object.entries(e).flatMap(([e,t])=>t.required?[e]:[])}function $r(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]))}function ei(){return{oneOf:[...ni(),{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 ti(){return{oneOf:ni(),description:`UI element target by snapshot ref or selector expression.`}}function ni(){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 br({name:e,description:t,inputSchema:Vr(n),readInput:r?.readInput??(e=>Hr(e,n)),inputAudience:$r(n),...r?.parseableOutput?{parseableOutput:!0}:{}})}function z(e){let t=vr(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 ri(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)ii(t,`CLI schema`,a.name,a.cliSchema),ii(n,`CLI reader`,a.name,a.cliReader),a.daemonWriter&&ii(r,`daemon writer`,a.name,a.daemonWriter),a.cliOutputFormatter&&ii(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 ii(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(U);function U(e){return{data:e,text:Qt(e)}}function ai(e){return[...typeof e.warning==`string`&&e.warning.trim()!==``?[e.warning]:[],...Zt(e)].map(e=>ci(e)).filter(e=>e.length>0)}function oi(e,t){let n=e??``,r=ai(t).filter(e=>!n.includes(e)).map(e=>`Warning: ${e}`);return r.length===0?e??null:[...n===``?[]:[n],...r].join(`
2
- `)}function si(e,t,n){let r=t??{};if(n===`text`)return{...e,text:oi(e.text,r)};let i=`${e.text??``}\n${e.stderr??``}`,a=ai(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{A as e,C as t,L as n,O as r,R as i,h as a,j as o,n as s,v as c}from"./sdk-contracts.js";import{$ as l,C as ee,Dt as te,E as ne,Et as re,F as ie,I as ae,M as oe,N as se,Ot as ce,S as le,T as ue,Tt as de,W as fe,Z as pe,_t as me,a as he,b as ge,bt as _e,d as ve,et as ye,f as be,g as xe,gt as Se,h as Ce,it as we,kt as Te,m as Ee,n as De,nt as Oe,p as ke,r as Ae,rt as je,t as Me,u as Ne,w as Pe,x as Fe,y 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{Dt as Ke,E as d,M as qe,Q as Je,S as Ye,T as Xe,Z as Ze,at as Qe,c as $e,g as et,ht as tt,j as nt,k as rt,m as it,n as at,ot,p as st,st as ct,t as lt,tt as ut,vt as dt,x as ft}from"./back-mode.js";import{ut as pt}from"./sdk-io.js";import{a as mt,i as ht,n as gt,t as _t}from"./sdk-device.js";import{Br as vt,Cr as yt,Fn as bt,Gr as xt,Ln as St,Vn as Ct,Vt as wt,_ as Tt,_r as Et,fn as Dt,gr as Ot,i as kt,kr as At,m as jt,mn as Mt,p as Nt,s as Pt,ui as Ft,vr as It,xr as Lt}from"./sdk-batch.js";import{n as Rt}from"./recording-export-quality.js";import{t as zt}from"./recording-scope.js";import{a as Bt,i as Vt,r as Ht}from"./vars.js";import{t as Ut}from"./session.js";import{a as Wt,c as Gt,d as Kt,f as qt,g as Jt,h as Yt,i as Xt,l as Zt,n as Qt,o as $t,p as en,s as tn,t as nn,u as rn}from"./observability.js";import{n as an,t as on}from"./success-text.js";import{t as sn}from"./alert-contract.js";import{h as cn,l as ln,n as un,v as dn,x as fn,y as pn}from"./settings.js";import{t as mn}from"./location-coordinates.js";import{t as hn}from"./snapshot-quality-backend-capabilities.js";import{t as gn}from"./mobile-snapshot-semantics.js";import{t as _n}from"./absence-observation-errors.js";import{n as vn,t as yn}from"./interaction-positionals.js";import{t as bn}from"./app-inventory.js";import{c as xn,o as Sn}from"./file.js";import Cn from"node:fs";import f from"node:path";const wn=[`path`,`start`,`stop`,`doctor`,`mark`,`clear`],Tn=new Set(ft().map(e=>e.key));function En(t){let n=tt(t);return Ve({stateDir:t.stateDir,daemonBaseUrl:t.daemonBaseUrl,daemonTransport:t.daemonTransport,daemonServerMode:t.daemonServerMode,...dt(n),provider:t.provider,providerSessionId:t.providerSessionId,providerApp:t.providerApp,providerOsVersion:t.providerOsVersion,providerDeviceType:t.providerDeviceType,providerProject:t.providerProject,providerBuild:t.providerBuild,providerSessionName:t.providerSessionName,providerDeviceOrientation:t.providerDeviceOrientation,providerGeoLocation:t.providerGeoLocation,providerTimezone:t.providerTimezone,providerAppiumVersion:t.providerAppiumVersion,providerLanguage:t.providerLanguage,providerLocale:t.providerLocale,providerNetworkProfile:t.providerNetworkProfile,providerCustomNetwork:t.providerCustomNetwork,providerNoResignApp:t.providerNoResignApp,awsProjectArn:t.awsProjectArn,awsDeviceArn:t.awsDeviceArn,awsAppArn:t.awsAppArn,awsRegion:t.awsRegion,awsInteractionMode:t.awsInteractionMode,sessionIsolation:t.sessionIsolation,platform:t.platform,target:t.target,device:t.device,udid:t.udid,serial:t.serial,iosSimulatorDeviceSet:t.iosSimulatorDeviceSet,iosXctestrunFile:t.iosXctestrunFile,iosXctestDerivedDataPath:t.iosXctestDerivedDataPath,iosXctestEnvDir:t.iosXctestEnvDir,androidDeviceAllowlist:t.androidDeviceAllowlist,surface:t.surface,activity:t.activity,launchConsole:t.launchConsole,launchArgs:t.launchArgs,relaunch:t.relaunch,shutdown:t.shutdown,saveScript:t.saveScript,testIme:t.testIme,noRecord:t.noRecord,recordAs:t.recordAs,record:t.record,backMode:t.backMode,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,launchUrl:t.launchUrl,...e(t,c),...de(t),appsFilter:t.appsFilter,kind:t.kind,out:t.out,count:t.count,fps:t.fps,quality:t.quality,hideTouches:t.hideTouches,recordingScope:t.recordingScope,intervalMs:t.intervalMs,delayMs:t.delayMs,durationMs:t.durationMs,holdMs:t.holdMs,jitterPx:t.jitterPx,pixels:t.pixels,until:t.until,maxPasses:t.maxPasses,doubleTap:t.doubleTap,verify:t.verify,settle:t.settle,settleQuietMs:t.settleQuietMs,clickButton:t.clickButton,pauseMs:t.pauseMs,pattern:t.pattern,headless:t.headless,restart:t.restart,replayUpdate:t.replayUpdate,replayBackend:t.replayBackend,replayEnv:t.replayEnv,replayShellEnv:t.replayShellEnv,replayScriptSource:t.replayScriptSource,replayScriptSources:t.replayScriptSources,replayFrom:t.replayFrom,replayPlanDigest:t.replayPlanDigest,replayKeepSession:t.replayKeepSession,failFast:t.failFast,timeoutMs:t.timeoutMs,retries:t.retries,recordVideo:t.recordVideo,artifactsDir:t.artifactsDir,shardAll:t.shardAll,shardSplit:t.shardSplit,findFirst:t.findFirst,findLast:t.findLast,networkInclude:t.networkInclude,batchOnError:t.batchOnError,batchMaxSteps:t.batchMaxSteps,batchSteps:t.batchSteps,verbose:t.debug})}function Dn(e,t){return{...En(e),...t}}function On(e,t){let n=e.inputSchema.properties;if(!n)return{};let r={},i=t;for(let e of Object.keys(n)){if(!Tn.has(e))continue;let t=i[e];kn(t)&&(r[e]=t)}return r}function kn(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`}function An(e,t,n){if(Object.hasOwn(e,t))throw new i(`INVALID_ARGS`,n)}function jn(e){return{kind:`operator`,source:e}}function Mn(e,t){return`${e} is not accepted as a tool argument. ${Nn(e,t)}`}function Nn(e,t){if(`operatorPath`in t)return t.operatorPath;let n=`for the process serving these tools.`,r=(t.envFlagKeys??[e]).map(pt).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 Pn(e){if(e==null)return{};if(!e||typeof e!=`object`||Array.isArray(e))throw new i(`INVALID_ARGS`,`Expected object arguments.`);return e}function Fn(e,t){let n=e[t];if(!n||typeof n!=`object`||Array.isArray(n))throw new i(`INVALID_ARGS`,`Expected ${t} to be an object.`);return n}function In(e,t){let n=e[t];if(typeof n!=`string`||n.length===0)throw new i(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return n}function Ln(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new i(`INVALID_ARGS`,`Expected ${t} to be a string.`);return n}}function p(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`||n.length===0)throw new i(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return n}}function Rn(e,t){let n=e[t];if(typeof n!=`number`||!Number.isFinite(n))throw new i(`INVALID_ARGS`,`Expected ${t} to be a finite number.`);return n}function zn(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw new i(`INVALID_ARGS`,`Expected ${t} to be a boolean.`);return n}}function Bn(e,t,n){let r=e[t];if(typeof r!=`string`||!n.includes(r))throw new i(`INVALID_ARGS`,`Expected ${t} to be one of: ${n.join(`, `)}.`);return r}function Vn(e,t,n){let r=e[t];if(r!==void 0){if(typeof r!=`string`||!n.includes(r))throw new i(`INVALID_ARGS`,`Expected ${t} to be one of: ${n.join(`, `)}.`);return r}}function Hn(e,t){let n=e[t];if(n!==void 0){if(!n||typeof n!=`object`||Array.isArray(n))throw new i(`INVALID_ARGS`,`Expected ${t} to be an object.`);return n}}function Un(e,t){let n=e[t];if(n!==void 0){if(!Array.isArray(n)||n.some(e=>typeof e!=`string`))throw new i(`INVALID_ARGS`,`Expected ${t} to be an array of strings.`);return n}}function Wn(e,t,n,r){let a=new Set(t),o=Object.keys(e).filter(e=>!a.has(e));if(o.length>0)throw new i(`INVALID_ARGS`,`${n} has unknown field(s): ${o.join(`, `)}.`,r===void 0?void 0:{hint:r})}function m(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}const Gn=jn({operatorConfig:!0}),Kn=`readinessTimeoutMs was removed; add an explicit wait for the target before the interaction.`,qn={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=>Vn(e,`platform`,ht),flagKey:`platform`,flagIn:[`input`,`selection`]},deviceTarget:{schema:{type:`string`,enum:gt,description:`Device target form. Maps to the CLI --target flag.`},read:er,clientKey:`target`,flagKey:`target`,flagIn:[`input`,`selection`]},target:{schema:{type:`string`,enum:gt,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:jn({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:Gn,flagKey:`iosXctestrunFile`,flagIn:[`input`]},iosXctestDerivedDataPath:{schema:{type:`string`,description:`Derived data path for external iOS XCTest runner execution.`},read:e=>p(e,`iosXctestDerivedDataPath`),audience:Gn,flagKey:`iosXctestDerivedDataPath`,flagIn:[`input`]},iosXctestEnvDir:{schema:{type:`string`,description:`Writable directory for iOS XCTest runner env overlays.`},read:e=>p(e,`iosXctestEnvDir`),audience:Gn,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=>zn(e,`noRecord`),flagKey:`noRecord`,flagIn:[`input`,`selection`]},readinessTimeoutMs:{audience:{kind:`retired`,message:Kn},read:e=>An(e,`readinessTimeoutMs`,Kn)},daemonBaseUrl:{schema:{type:`string`,description:`Remote daemon base URL.`},read:e=>p(e,`daemonBaseUrl`),audience:Gn},daemonAuthToken:{schema:{type:`string`,description:`Remote daemon auth token.`},read:e=>p(e,`daemonAuthToken`),audience:Gn},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:jn({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=>zn(e,`debug`)}},Jn=Object.entries(qn),Yn=Object.fromEntries(Jn.flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]));function Xn(e){for(let[t,n]of Object.entries(Yn))n.kind===`retired`&&An(e,t,n.message)}function Zn(){return Object.fromEntries(Jn.flatMap(([e,t])=>t.schema?[[e,t.schema]]:[]))}function Qn(e,t={}){let n={};for(let[r,i]of Jn)i.read&&(n[r]=i.read(e,t));return n}function h(e){let t={};for(let[n,r]of Jn)r.read&&(t[r.clientKey??n]=e[n]);return m(t)}function $n(e,t){let n={};for(let[r,i]of Jn){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 er(e,t){let n=Vn(e,`deviceTarget`,gt);if(t.readTargetAlias===!1||e.target===void 0)return n;let r=Vn(e,`target`,gt);if(n!==void 0&&r!==n)throw new i(`INVALID_ARGS`,`Expected target alias to match deviceTarget when both are set.`);return n??r}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:tr(n)}}function tr(e){let t=nr(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 nr(e){return e===`mobile`||e===`tv`||e===`desktop`?e:void 0}function v(e){return m($n(e,`input`))}function rr(e){return m({record:e.record})}function ir(e){return $n(e,`selection`)}function ar(e){return m({depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw})}function or(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function sr(e){return m({settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs})}function cr(e){return m({count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap})}function lr(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 ur(e){let t=fr(e);if(typeof t.ref==`string`)return[t.ref,...mr(t.label)];if(typeof t.selector==`string`)return[t.selector];if(t.kind===`point`||t.x!==void 0||t.y!==void 0)return[String(pr(t.x,`x`)),String(pr(t.y,`y`))];throw new i(`INVALID_ARGS`,`interaction requires @ref, selector, or point target`)}function dr(e){let t=fr(e);if(typeof t.ref==`string`)return[t.ref,...mr(t.label)];if(typeof t.selector==`string`)return[t.selector];throw new i(`INVALID_ARGS`,`element command requires @ref or selector target`)}function fr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw new i(`INVALID_ARGS`,`Expected target object.`);let t=e,n=t.target;return n&&typeof n==`object`&&!Array.isArray(n)?n:t}function pr(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw new i(`INVALID_ARGS`,`point target requires numeric ${t}.`);return e}function mr(e){return typeof e==`string`&&e.length>0?[e]:[]}function hr(e){let t=Et(e);if(!t.ok)throw new i(t.code,t.message);return`ref`in t?{ref:t.ref,label:yr(e.slice(1))}:{selector:t.selector}}function gr(e){let t=It(e);if(!t.ok)throw new i(t.code,t.message);return t.format}function _r(e,t={}){let n=At(e,t);if(!n)throw new i(`INVALID_ARGS`,Ot);return n}function vr(e,t){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}throw new i(`INVALID_ARGS`,`${t} must be a JSON object`)}function yr(e){return e.join(` `).trim()||void 0}function br(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function xr(e,t){if(e===void 0)return;let n=Number(e);if(Number.isFinite(n))return n;throw new i(`INVALID_ARGS`,`${t} must be a finite number.`)}function Sr(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 i(`INVALID_ARGS`,t);return e}function S(e,t){if(typeof e!=`string`||e.length===0)throw new i(`INVALID_ARGS`,t);return e}function Cr(e){return Er(e.description,e.cliDetail)}function wr(e){return Er(e.description,e.mcpDetail)}function Tr(e,t){return{...e,description:t}}function Er(e,t){return t?`${e} ${t}`:e}function Dr(e){return e}const Or=[`ref`,`selector`,`point`];function kr(e,t=[]){return{type:`object`,properties:{...Zn(),...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 Ar(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 jr(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 Mr(e){return{type:`integer`,...e?{description:e}:{}}}function O(e){return{type:`boolean`,...e?{description:e}:{}}}function Nr(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?Ln:p)}function Pr(e){return{schema:{type:`null`},required:!1,audience:{kind:`retired`,message:e},read:(t,n)=>An(t,n,e)}}function Fr(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(ai(e,t),(e,n)=>Ue(e,n,t))}function P(e){return L(O(e),zn)}function Ir(e){return Rr(Lr(e))}function Lr(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 Rr(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(zr(e),t);case`booleanOrString`:throw Error(`Flag ${e.key} is booleanOrString; declare its field shape explicitly with jsonSchemaField`)}}function zr(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)=>Vn(t,n,e))}function Br(e){return L(k(e),Hn)}function Vr(e){return L(Nr(e),Un)}function I(e){return L(e,(e,t)=>e[t])}function Hr(e,t){return L(e,t)}function Ur(){return L(li(),(e,t)=>e[t]===void 0?void 0:Qr(e,t))}function Wr(){return L(ui(),(e,t)=>e[t]===void 0?void 0:$r(e,t))}function Gr(e){return L(Ar(e),(e,t)=>e[t]===void 0?void 0:ei(e,t))}function Kr(e,t){return L({type:`array`,description:e,items:Ar(`One contact point.`),minItems:t.min,maxItems:t.max},(e,t)=>e[t]===void 0?void 0:qr(e,t))}function qr(e,t){let n=e[t];if(!Array.isArray(n))throw new i(`INVALID_ARGS`,`Expected ${t} to be an array of points.`);return n.map((e,n)=>{let r=`${t}[${n}]`;return ei({[r]:e},r)})}function Jr(){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 Yr(){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 Xr(e){return kr(oi(e),si(e))}function Zr(e,t){let n=Pn(e),r=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{let r=t.read(n,e);if(t.required&&r===void 0)throw new i(`INVALID_ARGS`,`Expected ${e} to be set.`);return r===void 0?[]:[[e,r]]})),a=Qn(n,{readTargetAlias:!Object.hasOwn(t,`target`)});return m({...a,...h(a),...r})}function Qr(e,t){let n=Fn(e,t),r=Bn(n,`kind`,Or);switch(r){case`ref`:return{kind:r,ref:In(n,`ref`),label:p(n,`label`)};case`selector`:return{kind:r,selector:In(n,`selector`)};case`point`:return{kind:r,x:Rn(n,`x`),y:Rn(n,`y`)}}}function $r(e,t){let n=Fn(e,t),r=Bn(n,`kind`,[`ref`,`selector`]);return r===`ref`?{kind:r,ref:In(n,`ref`),label:p(n,`label`)}:{kind:r,selector:In(n,`selector`)}}function ei(e,t){let n=Fn(e,t);return{x:Rn(n,`x`),y:Rn(n,`y`)}}function ti(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 ni(e){switch(e.kind){case`ref`:return{ref:e.ref,label:e.label};case`selector`:return{selector:e.selector}}}function ri(e){return{count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap}}function ii(e){return{depth:e.depth,scope:e.scope,raw:e.raw}}function L(e,t){return{schema:e,required:!1,read:t}}function ai(e,t){return{...Mr(e),...t.min===void 0?{}:{minimum:t.min},...t.max===void 0?{}:{maximum:t.max}}}function oi(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.audience?.kind!==`retired`).map(([e,t])=>[e,t.schema]))}function si(e){return Object.entries(e).flatMap(([e,t])=>t.required?[e]:[])}function ci(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]))}function li(){return{oneOf:[...di(),{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 ui(){return{oneOf:di(),description:`UI element target by snapshot ref or selector expression.`}}function di(){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 Dr({name:e,description:t,inputSchema:Xr(n),readInput:r?.readInput??(e=>Zr(e,n)),inputAudience:ci(n),...r?.parseableOutput?{parseableOutput:!0}:{}})}function z(e){let t=Tr(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 fi(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)pi(t,`CLI schema`,a.name,a.cliSchema),pi(n,`CLI reader`,a.name,a.cliReader),a.daemonWriter&&pi(r,`daemon writer`,a.name,a.daemonWriter),a.cliOutputFormatter&&pi(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 pi(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(U);function U(e){return{data:e,text:on(e)}}function mi(e){return[...typeof e.warning==`string`&&e.warning.trim()!==``?[e.warning]:[],...an(e)].map(e=>_i(e)).filter(e=>e.length>0)}function hi(e,t){let n=e??``,r=mi(t).filter(e=>!n.includes(e)).map(e=>`Warning: ${e}`);return r.length===0?e??null:[...n===``?[]:[n],...r].join(`
2
+ `)}function gi(e,t,n){let r=t??{};if(n===`text`)return{...e,text:hi(e.text,r)};let i=`${e.text??``}\n${e.stderr??``}`,a=mi(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 ci(e){return e.replaceAll(/\s*\n\s*/g,` `)}function li(e,t){if(typeof e==`string`&&e.length!==0&&typeof t==`number`)return`@${e.startsWith(`@`)?e.slice(1):e}~s${t}`}function ui(e){let t=[`Batch completed: ${e.executed}/${e.total} steps in ${e.totalDurationMs}ms`];for(let n of e.results)t.push(fi(n));return{data:e,text:t.join(`
6
- `)}}const di={batch:V(ui)};function fi(e){let t=Qt(e.data)??e.command;return`${e.step}. OK ${t} (${e.durationMs}ms)`}function pi(e=St){let t=mi(e);return R(`batch`,`Execute multiple commands in one daemon request.`,t,{readInput:e=>gi(e,t)})}function mi(e){return{steps:A(Fr({type:`array`,description:`Structured batch steps. Each step uses a command name and the same input object as that command tool.`,items:hi(e)},(t,n)=>_i(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 hi(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 gi(e,t){let n=Hr(e,t),r=n.maxSteps??100;if(!Ie(r))throw new i(`INVALID_ARGS`,`Invalid batch maxSteps: ${String(n.maxSteps)}`);return je(n.steps.length,r),{...n}}function _i(e,t){if(!Array.isArray(e))throw new i(`INVALID_ARGS`,`Expected steps to be an array.`);return e.map((e,n)=>vi(e,n+1,t))}function vi(e,t,n){let r=Ne(e,t);return Ln(r,[`command`,`input`,`runtime`],`Batch step ${t}`,Re),{command:yi(r,t,n),input:Me(r,t),...bi(r,t)}}function yi(e,t,n){if(n===St)return Ot(e.command,t);let r=e.command;if(typeof r!=`string`||!n.includes(r))throw new i(`INVALID_ARGS`,`Expected command to be one of: ${n.join(`, `)}.`);return r}function bi(e,t){let n=ze(e.runtime,t);return n===void 0?{}:{runtime:n}}function xi(e){return async(t,n)=>_(d.batch,[],{...t,batchSteps:await Si(t.steps,(t,r,i)=>e(t,r,i,n)),batchOnError:t.onError,batchMaxSteps:t.maxSteps})}async function Si(e,t){if(!Array.isArray(e)||e.length===0)throw new i(`INVALID_ARGS`,`batch requires a non-empty steps array.`);let n=[];for(let[r,i]of e.entries())n.push(await Ci(i,r+1,t));return n}async function Ci(e,t,n){let r=Ne(e,t),i=Ti(r,t),a=Me(r,t);wi(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:bn(s.options,s.metadataFlags),runtime:o??s.options.runtime}}function wi(e,t,n){if(e===d.fill&&t.textStdin===!0)throw new i(`INVALID_ARGS`,`Batch step ${n}: 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 Ti(e,t){return Ot(e.command,t)}const Ei=pi(),Di={usageOverride:`batch [--steps <json> | --steps-file <path>]`,usageFlags:[],listUsageOverride:`batch --steps <json> | --steps-file <path>`,allowedFlags:[`steps`,`stepsFile`,`batchOnError`,`batchMaxSteps`,`out`]},Oi=(e,t)=>({...v(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out}),ki=[{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 Ai(){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.`,`Available through batch: ${[...St].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(ki)}'`,` agent-device batch --steps-file ./steps.json --json`].join(`
7
- `)}`}const ji=B({name:`batch`,clientSurface:!1,commands:[z({name:`batch`,text:{summary:`Run multiple commands`,cliDetail:Ai()},metadata:Ei,run:(e,t)=>e.batch.run(Mi(t)),cliSchema:Di,cliReader:Oi,cliOutputFormatter:di.batch})]});function Mi(e){return{...h(e),steps:e.steps,onError:e.onError,maxSteps:e.maxSteps,out:e.out}}const Ni=`alert`,Pi=z({name:Ni,text:{summary:`Inspect, accept, or dismiss a platform alert`},metadata:R(Ni,`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); 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($t),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),...Ii(e)}),daemonWriter:g(d.alert,e=>Fi(e)),cliOutputFormatter:H});function Fi(e){return[e.action??`get`,...b(e.timeoutMs)]}function Ii(e){if(e.length>2)throw new i(`INVALID_ARGS`,`alert accepts at most action and timeout arguments.`);return m({action:Li(e[0]),timeoutMs:mr(e[1],`alert timeout`)})}function Li(e){let t=e?.toLowerCase();if(t===void 0||t===`get`||t===`accept`||t===`dismiss`||t===`wait`)return t;throw new i(`INVALID_ARGS`,`alert action must be get, accept, dismiss, or wait.`)}function W(...e){return e}const Ri=W(`keyframes`),zi=W(`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`),Bi=W(`snapshotDepth`,`snapshotScope`,`snapshotRaw`),Vi=W(`metroProjectRoot`,`kind`,`metroKind`,`metroPublicBaseUrl`,`metroProxyBaseUrl`,`metroBearerToken`,`metroPreparePort`,`metroListenHost`,`metroStatusHost`,`metroStartupTimeoutMs`,`metroProbeTimeoutMs`,`metroRuntimeFile`,`metroNoReuseExisting`,`metroNoInstallDeps`),Hi=W(`metroHost`,`metroPort`,`bundleUrl`),Ui=W(`count`,`intervalMs`,`holdMs`,`jitterPx`,`doubleTap`),Wi=W(`settle`,`settleQuietMs`,`timeoutMs`),Gi=W(`replayUpdate`,`replayEnv`),Ki=W(`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`),qi=new Set([`platform`,`device`,`udid`,`serial`,`session`]),Ji=new Set([`json`,`config`,`help`,`version`,`verbose`,`cost`,`responseLevel`]),Yi=`diff`,Xi={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:Er()},[`mode`,`baselineInitialized`,`summary`,`lines`])},Zi=z({name:Yi,text:{summary:`Diff snapshot or screenshot`,cliDetail:`Screenshot --threshold is a per-pixel RGB tolerance: 0 requires exact colors and 1 ignores color differences; image dimensions must still match. 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(Yi,`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:[...zi,`baseline`,`threshold`,`out`,`overlayRefs`]},cliReader:(e,t)=>{if(e[0]!==`snapshot`)throw new i(`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`)])}),Qi=`screenshot`,$i=z({name:Qi,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(Qi,`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.`,_e),maxSize:Dr(he.migration.screenshot),stabilize:P(),normalizeStatusBar:P(),surface:F(It)}),run:(e,t)=>e.capture.screenshot(t),cliSchema:{positionalArgs:[`path?`],allowedFlags:Se},cliReader:(e,t)=>({...v(t),path:e[0]??t.out,...ee(t)}),daemonWriter:e=>(Oe(`screenshot`,e),oe(e),_(d.screenshot,y(e.path),{...e,...ae(e)}))}),ea=`settings`,ta=R(ea,`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(on)),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([...rn])}),na={usageOverride:nn,listUsageOverride:`settings [area] [options]`,positionalArgs:[`setting`,`state?`,`target?`,`mode?`],allowedFlags:[`targetApp`],explicitOnlyFlags:[`targetApp`]},ra=(e,t)=>{let n=Zn(t),r=dt(e);if(r.kind===`read`)return{...n,setting:r.setting};let i=tn(e),a=an(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:sn(i.latitude,`latitude`),longitude:sn(i.longitude,`longitude`)},...a===void 0?{}:{app:a}}},ia=e=>{let t=e,n=m({app:aa(t)});return _(d.settings,ca(t),e,Object.keys(n).length===0?void 0:n)};function aa(e){return an(e.setting)?.app===`input`&&`app`in e?e.app:void 0}const oa=z({name:ea,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:`,...en().map(e=>` ${e}`)].join(`
8
- `)},metadata:ta,run:(e,t)=>e.settings.update(t),cliSchema:na,cliReader:ra,daemonWriter:ia,cliOutputFormatter:H});function sa(e,t,n){let r=n.targetApp;if(t!==void 0&&r!==void 0&&t!==r)throw new i(`INVALID_ARGS`,`settings ${e} names two apps: ${t} and ${r}. Name one.`);return t??r}function ca(e){return an(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 la(e){if(!Array.isArray(e)||e.length===0)return e;let t=pt(e);return e.map(e=>{let n=ua(e,t,e=>e.label),r=ua(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 ua(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 fa(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 pa(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 ma(e){return typeof e.parentIndex!=`number`}function ha(e){let t=(e.type??``).toLowerCase(),n=(e.identifier??``).trim().toLowerCase();return t.includes(`edittext`)||t.includes(`textfield`)||n===`composer`}function ga(e){let t=(e.type??``).toLowerCase();return t.includes(`scroll`)||t.includes(`list`)||t.includes(`recyclerview`)}function _a(e){let t=mt(e);if(!t||t!==e.identifier?.trim()||!ya(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 va(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||/^(true|false|\d+)$/.test(t)?null:t}function ya(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function ba(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 xa(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 Sa(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 Ca=[`button`,`switch`,`checkbox`,`radio`],wa=[`button`,`image`,`textview`,`view`];function Ta(e,t,n){for(let r of e){if(t.has(r.index)||!Oa(r))continue;let i=ka(xa(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)Sa(e,n,t)}}}function Ea(e,t,n){let r=new Map;for(let i of e){if(t.has(i.index)||!La(i))continue;let a=va(_a(i));if(!a)continue;let o=r.get(a);if(o&&Pa(o,i,t)){let s=Fa(e,o,i,t,n);r.set(a,s);continue}r.set(a,i)}}function Da(e,t){for(let n of e){if(t.has(n.index)||!Ma(n))continue;let r=va(_a(n));if(!r)continue;let i=xa(e,n.index).filter(e=>!t.has(e.index)&&Na(n,e,r));for(let n of i.filter(ja))Sa(e,n.index,t);let a=i.filter(e=>!ja(e)),o=new Set(a.map(e=>va(_a(e))).filter(e=>!!e));if(!(a.length<2||o.size<2))for(let n of a)Sa(e,n.index,t)}}function Oa(e){return e.hittable===!0&&!ha(e)&&!!(e.rect&&da(e.rect))&&_a(e).trim().length===0}function ka(e,t,n){let r=[],i=[],a=new Set;for(let o of e){if(n.has(o.index)||!Aa(o,e)||!fa(o.rect,t.rect))continue;let s=_a(o).trim().replaceAll(/\s+/g,` `),c=va(s);i.push(o.index),!(!s||!c||a.has(c))&&(a.add(c),r.push(s))}return{label:r.join(`, `),removableIndexes:i}}function Aa(e,t){if(ja(e))return!0;let n=(e.type??``).toLowerCase();return e.hittable!==!0&&!ha(e)&&n.includes(`view`)&&_a(e).trim().length>0&&!t.some(t=>t.parentIndex===e.index)}function ja(e){if(e.hittable===!0||ha(e))return!1;let t=(e.type??``).toLowerCase();return t.includes(`text`)||t.includes(`image`)||t.includes(`icon`)}function Ma(e){return e.hittable===!0&&!ha(e)&&!!(e.rect&&da(e.rect))&&!!va(_a(e))}function Na(e,t,n){if(!La(t)||!fa(t.rect,e.rect))return!1;let r=va(_a(t));return!!(r&&n!==r&&n.includes(r))}function Pa(e,t,n){return!n.has(e.index)&&pa(e.rect,t.rect)&&(Ha(e,t)||Va(e,t))}function Fa(e,t,n,r,i){let a=Ra(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:Ia(c.presentationHints,l,s)}),Sa(e,o.index,r),i.get(a.index)??a}function Ia(e,t,n){return[...new Set([...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...n?[n]:[]])]}function La(e){if(!e.rect||!da(e.rect)||ma(e)||ha(e))return!1;let t=(e.type??``).toLowerCase();return t===`text`||Ba(t,wa)}function Ra(e,t){let n=za(e);return za(t)>n?t:e}function za(e){let t=(e.type??``).toLowerCase(),n=0;return Ba(t,Ca)?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 Ba(e,t){return t.some(t=>e.includes(t))}function Va(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:Ra(n,r).index===n.index}function Ha(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 Ua(e,t,n){if(n.raw||!Wa(e))return{nodes:t,filteredCount:0};let r=Ga(t);return{nodes:r,filteredCount:t.length-r.length}}function Wa(e){let t=e.androidSnapshot;return!t||typeof t!=`object`?!1:t.backend===`android-helper`}function Ga(e){if(e.length===0)return e;let t=new Set,n=new Map,r=new Map(e.map(e=>[e.index,e]));return Ka(e,t),qa(e,r,t,n),Ta(e,t,n),Da(e,t),Ea(e,t,n),e.filter(e=>!t.has(e.index)).map(e=>n.get(e.index)??e)}function Ka(e,t){for(let n of e)!n.rect||da(n.rect)||ma(n)||Sa(e,n.index,t)}function qa(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||ma(i))continue;let a=ba(i,t,ga);a&&Ya(r,a,Ja(i,e)),Sa(e,i.index,n)}}function Ja(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 Ya(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 Xa(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??``).toLowerCase(),r=Za(mt(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||!eo(e)||(n+=e.length);return n>=8}function Za(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||Qa(t)?null:t}function Qa(e){return e.split(` `).some($a)}function $a(e){let t=e.indexOf(`@`,1);return t!==-1&&e.lastIndexOf(`.`,e.length-2)>t+1}function eo(e){for(let t=0;t<e.length;t+=1)for(let n=t+1;n<e.length;n+=1)if(to(e[t]?.rect,e[n]?.rect))return!0;return!1}function to(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 no(e,t={}){let i=e.nodes,a=Array.isArray(i)?i:[],o=r(e.backend)?e.backend:void 0,s=n(o),c=Ua(e,a,t),l=oo(e),ee=go(e,a,t,c),te=ee.length>0?`${ee.join(`
9
- `)}\n`:``,ne=t.raw?null:ro(e);if(ne)return`${l}${te}${io(ne)}\n`;let re=t.raw||!s?null:ln(c.nodes),ie=!!e.truncated,ae=re?.nodes??a,oe=t.raw||!s?null:po(e,re,ae.length,a.length,c.filteredCount),se=so(a.length,oe,ie);return a.length===0?`${l}${se}\n${te}`:t.raw?`${l}${se}\n${te}${co(a)}\n`:t.flatten?`${l}${se}\n${te}${lo(ae)}${fo(re)}\n`:`${l}${se}\n${te}${uo(ae)}${fo(re)}\n`}function ro(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 io(e){let t=ao(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 _i(e){return e.replaceAll(/\s*\n\s*/g,` `)}function vi(e,t){if(typeof e==`string`&&e.length!==0&&typeof t==`number`)return`@${e.startsWith(`@`)?e.slice(1):e}~s${t}`}function yi(e){let t=[`Batch completed: ${e.executed}/${e.total} steps in ${e.totalDurationMs}ms`];for(let n of e.results)t.push(xi(n));return{data:e,text:t.join(`
6
+ `)}}const bi={batch:V(yi)};function xi(e){let t=on(e.data)??e.command;return`${e.step}. OK ${t} (${e.durationMs}ms)`}function Si(e=kt){let t=Ci(e);return R(`batch`,`Execute multiple commands in one daemon request.`,t,{readInput:e=>Ti(e,t)})}function Ci(e){return{steps:A(Hr({type:`array`,description:`Structured batch steps. Each step uses a command name and the same input object as that command tool.`,items:wi(e)},(t,n)=>Ei(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 wi(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 Ti(e,t){let n=Zr(e,t),r=n.maxSteps??100;if(!He(r))throw new i(`INVALID_ARGS`,`Invalid batch maxSteps: ${String(n.maxSteps)}`);return Le(n.steps.length,r),{...n}}function Ei(e,t){if(!Array.isArray(e))throw new i(`INVALID_ARGS`,`Expected steps to be an array.`);return e.map((e,n)=>Di(e,n+1,t))}function Di(e,t,n){let r=ze(e,t);return Wn(r,[`command`,`input`,`runtime`],`Batch step ${t}`,We),{command:Oi(r,t,n),input:Re(r,t),...ki(r,t)}}function Oi(e,t,n){if(n===kt)return Pt(e.command,t);let r=e.command;if(typeof r!=`string`||!n.includes(r))throw new i(`INVALID_ARGS`,`Expected command to be one of: ${n.join(`, `)}.`);return r}function ki(e,t){let n=Ge(e.runtime,t);return n===void 0?{}:{runtime:n}}function Ai(e){return async(t,n)=>_(d.batch,[],{...t,batchSteps:await ji(t.steps,(t,r,i)=>e(t,r,i,n)),batchOnError:t.onError,batchMaxSteps:t.maxSteps})}async function ji(e,t){if(!Array.isArray(e)||e.length===0)throw new i(`INVALID_ARGS`,`batch requires a non-empty steps array.`);let n=[];for(let[r,i]of e.entries())n.push(await Mi(i,r+1,t));return n}async function Mi(e,t,n){let r=ze(e,t),i=Pi(r,t),a=Re(r,t);Ni(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:Dn(s.options,s.metadataFlags),runtime:o??s.options.runtime}}function Ni(e,t,n){if(e===d.fill&&t.textStdin===!0)throw new i(`INVALID_ARGS`,`Batch step ${n}: 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 Pi(e,t){return Pt(e.command,t)}const Fi=Si(),Ii={usageOverride:`batch [--steps <json> | --steps-file <path>]`,usageFlags:[],listUsageOverride:`batch --steps <json> | --steps-file <path>`,allowedFlags:[`steps`,`stepsFile`,`batchOnError`,`batchMaxSteps`,`out`]},Li=(e,t)=>({...v(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out}),Ri=[{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 zi(){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.`,`Available through batch: ${[...kt].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(Ri)}'`,` agent-device batch --steps-file ./steps.json --json`].join(`
7
+ `)}`}const Bi=B({name:`batch`,clientSurface:!1,commands:[z({name:`batch`,text:{summary:`Run multiple commands`,cliDetail:zi()},metadata:Fi,run:(e,t)=>e.batch.run(Vi(t)),cliSchema:Ii,cliReader:Li,cliOutputFormatter:bi.batch})]});function Vi(e){return{...h(e),steps:e.steps,onError:e.onError,maxSteps:e.maxSteps,out:e.out}}const Hi=`alert`,Ui=z({name:Hi,text:{summary:`Inspect, accept, or dismiss a platform alert`},metadata:R(Hi,`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); 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(sn),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),...Gi(e)}),daemonWriter:g(d.alert,e=>Wi(e)),cliOutputFormatter:H});function Wi(e){return[e.action??`get`,...b(e.timeoutMs)]}function Gi(e){if(e.length>2)throw new i(`INVALID_ARGS`,`alert accepts at most action and timeout arguments.`);return m({action:Ki(e[0]),timeoutMs:xr(e[1],`alert timeout`)})}function Ki(e){let t=e?.toLowerCase();if(t===void 0||t===`get`||t===`accept`||t===`dismiss`||t===`wait`)return t;throw new i(`INVALID_ARGS`,`alert action must be get, accept, dismiss, or wait.`)}function W(...e){return e}const qi=W(`keyframes`),Ji=W(`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`),Yi=W(`snapshotDepth`,`snapshotScope`,`snapshotRaw`),Xi=W(`metroProjectRoot`,`kind`,`metroKind`,`metroPublicBaseUrl`,`metroProxyBaseUrl`,`metroBearerToken`,`metroPreparePort`,`metroListenHost`,`metroStatusHost`,`metroStartupTimeoutMs`,`metroProbeTimeoutMs`,`metroRuntimeFile`,`metroNoReuseExisting`,`metroNoInstallDeps`),Zi=W(`metroHost`,`metroPort`,`bundleUrl`),Qi=W(`count`,`intervalMs`,`holdMs`,`jitterPx`,`doubleTap`),$i=W(`settle`,`settleQuietMs`,`timeoutMs`),ea=W(`replayUpdate`,`replayEnv`),ta=W(`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`),na=new Set([`platform`,`device`,`udid`,`serial`,`session`]),ra=new Set([`json`,`config`,`help`,`version`,`verbose`,`cost`,`responseLevel`]),ia=`diff`,aa={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:Nr()},[`mode`,`baselineInitialized`,`summary`,`lines`])},oa=z({name:ia,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(ia,`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:[...Ji,`baseline`,`threshold`,`out`,`overlayRefs`]},cliReader:(e,t)=>{if(e[0]!==`snapshot`)throw new i(`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`)])}),sa=`screenshot`,ca=z({name:sa,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(sa,`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.`,_e),maxSize:Pr(Se.migration.screenshot),stabilize:P(),normalizeStatusBar:P(),surface:F(Ut)}),run:(e,t)=>e.capture.screenshot(t),cliSchema:{positionalArgs:[`path?`],allowedFlags:me},cliReader:(e,t)=>({...v(t),path:e[0]??t.out,...te(t)}),daemonWriter:e=>(ce(`screenshot`,e),Te(e),_(d.screenshot,y(e.path),{...e,...re(e)}))}),la=`settings`,ua=R(la,`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(pn)),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([...dn])}),da={usageOverride:un,listUsageOverride:`settings [area] [options]`,positionalArgs:[`setting`,`state?`,`target?`,`mode?`],allowedFlags:[`targetApp`],explicitOnlyFlags:[`targetApp`]},fa=(e,t)=>{let n=ir(t),r=wt(e);if(r.kind===`read`)return{...n,setting:r.setting};let i=ln(e),a=fn(i.setting)?.app===`positional`?ga(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:mn(i.latitude,`latitude`),longitude:mn(i.longitude,`longitude`)},...a===void 0?{}:{app:a}}},pa=e=>{let t=e,n=m({app:ma(t)});return _(d.settings,_a(t),e,Object.keys(n).length===0?void 0:n)};function ma(e){return fn(e.setting)?.app===`input`&&`app`in e?e.app:void 0}const ha=z({name:la,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:`,...cn().map(e=>` ${e}`)].join(`
8
+ `)},metadata:ua,run:(e,t)=>e.settings.update(t),cliSchema:da,cliReader:fa,daemonWriter:pa,cliOutputFormatter:H});function ga(e,t,n){let r=n.targetApp;if(t!==void 0&&r!==void 0&&t!==r)throw new i(`INVALID_ARGS`,`settings ${e} names two apps: ${t} and ${r}. Name one.`);return t??r}function _a(e){return fn(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 va(e){if(!Array.isArray(e)||e.length===0)return e;let t=xt(e);return e.map(e=>{let n=ya(e,t,e=>e.label),r=ya(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 ya(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 ba(e){return e.width>0&&e.height>0}function xa(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 Sa(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 Ca(e){return typeof e.parentIndex!=`number`}function wa(e){let t=(e.type??``).toLowerCase(),n=(e.identifier??``).trim().toLowerCase();return t.includes(`edittext`)||t.includes(`textfield`)||n===`composer`}function Ta(e){let t=(e.type??``).toLowerCase();return t.includes(`scroll`)||t.includes(`list`)||t.includes(`recyclerview`)}function Ea(e){let t=vt(e);if(!t||t!==e.identifier?.trim()||!Oa(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 Da(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||/^(true|false|\d+)$/.test(t)?null:t}function Oa(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function ka(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 Aa(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 ja(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 Ma=[`button`,`switch`,`checkbox`,`radio`],Na=[`button`,`image`,`textview`,`view`];function Pa(e,t,n){for(let r of e){if(t.has(r.index)||!La(r))continue;let i=Ra(Aa(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)ja(e,n,t)}}}function Fa(e,t,n){let r=new Map;for(let i of e){if(t.has(i.index)||!Ka(i))continue;let a=Da(Ea(i));if(!a)continue;let o=r.get(a);if(o&&Ua(o,i,t)){let s=Wa(e,o,i,t,n);r.set(a,s);continue}r.set(a,i)}}function Ia(e,t){for(let n of e){if(t.has(n.index)||!Va(n))continue;let r=Da(Ea(n));if(!r)continue;let i=Aa(e,n.index).filter(e=>!t.has(e.index)&&Ha(n,e,r));for(let n of i.filter(Ba))ja(e,n.index,t);let a=i.filter(e=>!Ba(e)),o=new Set(a.map(e=>Da(Ea(e))).filter(e=>!!e));if(!(a.length<2||o.size<2))for(let n of a)ja(e,n.index,t)}}function La(e){return e.hittable===!0&&!wa(e)&&!!(e.rect&&ba(e.rect))&&Ea(e).trim().length===0}function Ra(e,t,n){let r=[],i=[],a=new Set;for(let o of e){if(n.has(o.index)||!za(o,e)||!xa(o.rect,t.rect))continue;let s=Ea(o).trim().replaceAll(/\s+/g,` `),c=Da(s);i.push(o.index),!(!s||!c||a.has(c))&&(a.add(c),r.push(s))}return{label:r.join(`, `),removableIndexes:i}}function za(e,t){if(Ba(e))return!0;let n=(e.type??``).toLowerCase();return e.hittable!==!0&&!wa(e)&&n.includes(`view`)&&Ea(e).trim().length>0&&!t.some(t=>t.parentIndex===e.index)}function Ba(e){if(e.hittable===!0||wa(e))return!1;let t=(e.type??``).toLowerCase();return t.includes(`text`)||t.includes(`image`)||t.includes(`icon`)}function Va(e){return e.hittable===!0&&!wa(e)&&!!(e.rect&&ba(e.rect))&&!!Da(Ea(e))}function Ha(e,t,n){if(!Ka(t)||!xa(t.rect,e.rect))return!1;let r=Da(Ea(t));return!!(r&&n!==r&&n.includes(r))}function Ua(e,t,n){return!n.has(e.index)&&Sa(e.rect,t.rect)&&(Za(e,t)||Xa(e,t))}function Wa(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:Ga(c.presentationHints,l,s)}),ja(e,o.index,r),i.get(a.index)??a}function Ga(e,t,n){return[...new Set([...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...n?[n]:[]])]}function Ka(e){if(!e.rect||!ba(e.rect)||Ca(e)||wa(e))return!1;let t=(e.type??``).toLowerCase();return t===`text`||Ya(t,Na)}function qa(e,t){let n=Ja(e);return Ja(t)>n?t:e}function Ja(e){let t=(e.type??``).toLowerCase(),n=0;return Ya(t,Ma)?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 Ya(e,t){return t.some(t=>e.includes(t))}function Xa(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 Za(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 Qa(e,t,n){if(n.raw||!$a(e))return{nodes:t,filteredCount:0};let r=eo(t);return{nodes:r,filteredCount:t.length-r.length}}function $a(e){let t=e.androidSnapshot;return!t||typeof t!=`object`?!1:t.backend===`android-helper`}function eo(e){if(e.length===0)return e;let t=new Set,n=new Map,r=new Map(e.map(e=>[e.index,e]));return to(e,t),no(e,r,t,n),Pa(e,t,n),Ia(e,t),Fa(e,t,n),e.filter(e=>!t.has(e.index)).map(e=>n.get(e.index)??e)}function to(e,t){for(let n of e)!n.rect||ba(n.rect)||Ca(n)||ja(e,n.index,t)}function no(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||Ca(i))continue;let a=ka(i,t,Ta);a&&io(r,a,ro(i,e)),ja(e,i.index,n)}}function ro(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&ba(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 io(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 ao(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??``).toLowerCase(),r=oo(vt(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||!lo(e)||(n+=e.length);return n>=8}function oo(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||so(t)?null:t}function so(e){return e.split(` `).some(co)}function co(e){let t=e.indexOf(`@`,1);return t!==-1&&e.lastIndexOf(`.`,e.length-2)>t+1}function lo(e){for(let t=0;t<e.length;t+=1)for(let n=t+1;n<e.length;n+=1)if(uo(e[t]?.rect,e[n]?.rect))return!0;return!1}function uo(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 fo(e,t={}){let i=e.nodes,a=Array.isArray(i)?i:[],o=r(e.backend)?e.backend:void 0,s=n(o),c=Qa(e,a,t),l=go(e),ee=To(e,a,t,c),te=ee.length>0?`${ee.join(`
9
+ `)}\n`:``,ne=t.raw?null:po(e);if(ne)return`${l}${te}${mo(ne)}\n`;let re=t.raw||!s?null:gn(c.nodes),ie=!!e.truncated,ae=re?.nodes??a,oe=t.raw||!s?null:So(e,re,ae.length,a.length,c.filteredCount),se=_o(a.length,oe,ie);return a.length===0?`${l}${se}\n${te}`:t.raw?`${l}${se}\n${te}${vo(a)}\n`:t.flatten?`${l}${se}\n${te}${yo(ae)}${xo(re)}\n`:`${l}${se}\n${te}${bo(ae)}${xo(re)}\n`}function po(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 mo(e){let t=ho(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 ao(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 oo(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 lo(e){return To(e).join(`
15
- `)}function uo(e){return So(tt(e,{summarizeTextSurfaces:!0})).join(`
16
- `)}function fo(e){return e&&e.summaryLines.length>0?`\n${e.summaryLines.join(`
17
- `)}`:``}function po(e,t,n,r,i=0){let a=mo(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:ho([...a?.reasons??[],`offscreen-nodes`])}:a||(s?{partial:!0,visibleNodeCount:n,totalNodeCount:n,reasons:[]}:null)}function mo(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 ho(e){return[...new Set(e)]}function go(e,t,n,r={nodes:t,filteredCount:0}){let i=[...xo(e),..._o(e)];if(vo(e)){let e=bo(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&&Xa(a)&&i.push(`Warning: possible repeated nav subtree detected.`),i}function _o(e){let t=e.fallbackScreenshotPath;return typeof t==`string`&&t.length>0?[`Captured a screenshot of this screen automatically as visual truth: ${t}`]:[]}function vo(e){return!e.snapshotQuality&&!yo(e)}function yo(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 bo(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 xo(e){return Zt(e).filter(e=>e.length>0)}function So(e){let t=[],n=[],r=new Map(e.map(e=>[e.node.index,e.node])),i=e=>{for(;n.length>0&&(!e||Co(e,n.at(-1),r));)t.push(...Eo(n.pop(),`below`))};for(let r of e)i(r),t.push(r.text),t.push(...Eo(r,`above`)),r.node.hiddenContentBelow&&n.push(r);return i(),t}function Co(e,t,n){return!wo(e.node,t.node,n)&&e.depth<=t.depth}function wo(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 To(e){return tt(e,{summarizeTextSurfaces:!0}).flatMap(e=>[Je(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...Eo({...e,depth:0})])}function Eo(e,t){let n=Do(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 Do(e){return e===`scroll-area`||e===`list`||e===`collection`||e===`table`?e:null}async function Oo(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:la(e.result.nodes)});return{data:n,jsonData:Ao(n),stderr:e.result.snapshotDiagnostics?.warning?`${e.result.snapshotDiagnostics.warning}\n`:void 0,text:no(n,{raw:e.raw,flatten:e.interactiveOnly,scoped:typeof e.scope==`string`&&e.scope.trim().length>0,depthLimited:typeof e.depth==`number`})}}const ko={snapshot:async({input:e,result:t})=>await Oo({result:t,raw:e.raw,interactiveOnly:e.interactiveOnly,scope:e.scope,depth:e.depth}),wait:H,alert:H};function Ao(e){let{unchanged:t,...n}=e;return n}const jo=`snapshot`,Mo=Object.entries(cn).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(`; `),No=R(jo,`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:kr(`snapshotCustomActions`),observeOnly:kr(`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.`)}),Po={allowedFlags:[`snapshotDiff`,...zi,`snapshotCustomActions`,`snapshotObserveOnly`,`snapshotForceFull`,`timeoutMs`,`record`]},Fo=(e,t)=>({...v(t),...Xn(t),...o(t,c),timeoutMs:t.timeoutMs}),Io=g(d.snapshot),Lo=z({name:jo,text:{summary:`Capture or diff the accessibility tree`,cliDetail:`--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: ${Mo}.`},metadata:No,run:(e,t)=>e.capture.snapshot(t),cliSchema:Po,cliReader:Fo,daemonWriter:Io,cliOutputFormatter:ko.snapshot}),Ro=[`duration`,`text`,`ref`,`selector`,`absent`,`stable`],zo=`wait`,Bo={wait:C({waitedMs:D(),kind:T(`selector`),text:E(),selector:E(),captures:D(),nodeCount:D(),hint:E(),warning:E()},[`waitedMs`])},Vo=z({name:zo,text:{summary:`Wait for a duration, text, selector, strict absence, or stable UI`},metadata:R(zo,`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(Ro),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(Ho(t)),cliSchema:{usageOverride:`wait <ms>|text <text>|@ref|<selector>|absent <selector> [timeoutMs]|stable [quietMs] [timeoutMs]`,usageFlags:[],positionalArgs:[`durationOrSelector`,`timeoutMs?`],allowsExtraPositionals:!0,allowedFlags:[...Bi]},cliReader:(e,t)=>Uo(e,t),daemonWriter:g(d.wait,e=>Ko(e)),cliOutputFormatter:H});function Ho(e){Pn(e,`kind`,Ro);let t={...e};return delete t.kind,t}function Uo(e,t){let n=Ct(e);if(!n)throw new i(`INVALID_ARGS`,`wait requires <ms>, text <text>, @ref, <selector> [timeoutMs], absent <selector> [timeoutMs], or stable [quietMs] [timeoutMs].`);let r={...Zn(t),...$n(t)};switch(n.kind){case`absent`:return Wo(r,n);case`sleep`:return{...r,durationMs:n.durationMs};case`text`:return Go(r,n);case`ref`:return{...r,ref:n.rawRef,...qo(n.timeoutMs)};case`stable`:return{...r,stable:!0,...Jo(n.quietMs),...qo(n.timeoutMs)};case`invalid`:throw new i(`INVALID_ARGS`,n.message);case`selector`:return{...r,selector:n.selectorExpression,...qo(n.timeoutMs)};default:return Yo(n)}}function Wo(e,t){let n=qe(e);if(n)throw un(n,`wait`);return{...e,absent:t.selectorExpression,...qo(t.timeoutMs)}}function Go(e,t){if(!t.text)throw new i(`INVALID_ARGS`,`wait requires text.`);return{...e,text:t.text,...qo(t.timeoutMs)}}function Ko(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 i(`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 n=qe(e);if(n)throw un(n,`wait`);if(!bt(e.absent))throw new i(`INVALID_ARGS`,`Invalid wait absent selector: ${e.absent}`);return[`absent`,e.absent,...t]}if(e.stable!==void 0){let n=b(e.quietMs);if(n.length===0&&t.length>0)throw new i(`INVALID_ARGS`,`wait stable requires quietMs before timeoutMs.`);return[`stable`,...n,...t]}let n=e.selector;if(!bt(n))throw new i(`INVALID_ARGS`,`Invalid wait selector: ${n}`);return[n,...t]}function qo(e){return e===null?{}:{timeoutMs:e}}function Jo(e){return e===null?{}:{quietMs:e}}function Yo(e){throw Error(`Unsupported wait positional target: ${String(e)}`)}const Xo=B({name:`capture`,commands:[Lo,$i,Zi,Vo,Pi,oa]});function Zo(e){let t=[e.outPath,e.message];t.push(...$o(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 Qo={debug:V(Zo)};function $o(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 es=`debug`,ts=B({name:`debugging`,commands:[z({name:es,text:{summary:`Symbolicate Apple crash artifacts`},metadata:R(es,`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:ns(e[0]),artifact:t.artifact,dsym:t.dsym,searchPath:t.searchPath,out:t.out}),cliOutputFormatter:Qo.debug})]});function ns(e){if(e===`symbols`)return e;throw new i(`INVALID_ARGS`,`debug supports only symbols; use logs, network, perf, record, trace, or react-devtools for other diagnostics`)}const rs=()=>P(`Capture cheap post-action evidence (AX digest, node counts, changedFromBefore) instead of a follow-up snapshot.`),is=()=>({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 as(e){return{...wt(e)?{verify:rs()}:{},...Et(e)?is():{}}}function os(e){let t=[];return wt(e)&&t.push(`verify`),Et(e)&&t.push(...Wi),t}function ss(e,t){return Et(e)?er(t):{}}const cs=[`click`,`focus`,`exists`,`list`,`getText`,`getAttrs`,`wait`,`fill`,`type`],ls={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, or drag gesture. Select the gesture kind, then provide only the inputs that apply to that kind.`},us={target:A(Ir()),button:F(et,`Pointer button for platforms that support mouse buttons.`),...zr(),...Br(),...as(`click`)},ds={target:A(Ir()),...zr(),...Br(),...as(`press`)},fs={target:A(Ir()),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:Or(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.`}),...zr(),...as(`fill`)},ps={target:A(Ir()),durationMs:N(`Long press duration in milliseconds.`,{min:0}),...zr(),...as(`longpress`)},ms={target:A(Ir()),...zr(),...as(`hover`)},hs={from:A(Rr(`Swipe start point.`)),to:A(Rr(`Swipe end point.`)),count:N(`Number of swipe repetitions.`,{min:1,max:200}),pauseMs:N(`Pause between repeated swipes.`,{min:0,max:l}),pattern:F(ie)},gs={x:A(M(`X coordinate.`)),y:A(M(`Y coordinate.`))},_s={text:A(j(`Text to type.`)),delayMs:N(`Delay between typed characters.`,{min:0})},vs={direction:A(F(se)),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:re}),...as(`scroll`)},ys=()=>({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.`)}),bs={format:A(F([`text`,`attrs`])),target:A(Lr()),...zr(),...ys()},xs={predicate:A(F(kt)),selector:A(j()),value:j(),...zr(),...ys()},Ss={locator:F(ht),query:A(j()),action:F(cs),value:j(void 0,{allowEmpty:!0}),timeoutMs:N(),first:P(),last:P(),depth:N(),raw:P(),...ys()},Cs={kind:A(F(Xe,`Gesture variant.`)),direction:F(ce,`Fling direction.`),preset:F(pe,`Swipe preset.`),origin:Rr(`Gesture origin point.`),delta:Rr(`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}),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})},ws=[G(`click`,us),G(`press`,ds),G(`fill`,fs),G(`longpress`,ps),G(`hover`,ms),G(`swipe`,hs),G(`focus`,gs),G(`type`,_s),G(`scroll`,vs),G(`get`,bs,{parseableOutput:!0}),G(`is`,xs),G(`find`,Ss,{parseableOutput:!0}),R(`gesture`,ls.gesture,Cs,{readInput:Ts})];function Ts(e){let t=Dn(e);return{...Gn(t),...Ke(t)}}function G(e,t,n){return R(e,ls[e],t,n)}const Es={gesture:Os},Ds={gesture:e=>{let t=Ts(e);return _(d.gesture,[],e,m(t))}};function Os(e,t){return{...v(t),...Be(e,t.pointerCount)}}const K={click:(e,t)=>({...v(t),...Qn(t),...tr(t),target:nr(dn(e)),button:t.clickButton,verify:t.verify}),press:(e,t)=>({...v(t),...Qn(t),...tr(t),target:nr(dn(e)),verify:t.verify}),longpress:(e,t)=>{let n=As(e);return{...v(t),...Qn(t),target:nr(n),durationMs:n.durationMs}},hover:(e,t)=>({...v(t),...Qn(t),target:nr(dn(e))}),swipe:(e,t)=>({...v(t),...rt(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?ks(e):fn(e);return{...v(t),...Qn(t),target:nr(n.target),text:n.text,delayMs:t.delayMs,recordAs:t.recordAs,textStdin:t.textStdin,verify:t.verify}},scroll:(e,t)=>({...v(t),direction:Ps(e[0]),amount:hr(e[1]),pixels:t.pixels,durationMs:t.durationMs,until:t.until,maxPasses:t.maxPasses}),get:(e,t)=>({...v(t),...Xn(t),...Qn(t),format:lr(e[0]),target:nr(cr(e.slice(1)))})},q={click:e=>_(d.click,rr(e),{...e,clickButton:e.button}),press:g(d.press,e=>rr(e)),longpress:g(d.longPress,e=>js(e)),hover:g(d.hover,e=>rr(e)),swipe:e=>(Ge(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=>Ms(e)),fill:g(d.fill,e=>Ns(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`),...ir(e)])};function ks(e){let t;try{t=fn(e)}catch(e){throw e instanceof i?new i(`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 i(`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 As(e){let t=Fs(e);return{...dn(t.target),...t.durationMs===void 0?{}:{durationMs:t.durationMs}}}function js(e){return[...rr(e),...b(e.durationMs)]}function Ms(e){return[e.text]}function Ns(e){return[...rr(e),e.text]}function Ps(e){if(e===`up`||e===`down`||e===`left`||e===`right`||e===`top`||e===`bottom`)return e;throw new i(`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 Fs(e){if(pr(e[0])&&pr(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&&pr(t)?{target:e.slice(0,-1),durationMs:Number(t)}:{target:e}}function Is(e){return t=>{let n=e(t);return n instanceof Promise?n.then(Ls):Ls(n)}}function Ls(e){return{data:e.data,text:zs(e.text,e.data)}}function Rs(e){let t={...e};for(let[n,r]of Object.entries(e))Et(n)&&(t[n]=Is(r));return t}function zs(e,t){return`${e??``}${Bs(t.settle)}`}function Bs(e){if(!e||typeof e!=`object`)return``;let t=e,n=[Ws(t),...Vs(t),...Us(t)];return t.hint&&n.push(`hint: ${t.hint}`),`\n${n.join(`
19
- `)}`}function Vs(e){let t=e.diff,n=(t?.lines??[]).map(t=>`${t.kind===`removed`?`-`:`+`} ${Hs(t,e.refsGeneration)}`);return t?.truncated&&n.push(`… changed lines truncated`),n}function Hs(e,t){let n=e.text??``,r=li(e.ref,t);if(!r||!e.ref)return n;let i=`@${e.ref}`;return n.startsWith(`${i} `)?`${r}${n.slice(i.length)}`:n}function Us(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=li(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 Ws(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 Gs(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 Ks(e){let t=e,n=Qt(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:qs(t.matches,t.refsGeneration)};let r=li(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)}:U(t)}function qs(e,t){return[`${e.length} match${e.length===1?``:`es`}:`,...e.map(e=>Js(e,t))].join(`
20
- `)}function Js(e,n){let r=e.ref===void 0?`(no ref)`:li(e.ref,n)??e.ref,i=t(e.node?.type??`Element`),a=e.node?$e(e.node,i):``;return`= ${r} [${i}]${a?` "${a}"`:``}`}function Ys(e){let t=e;return{data:t,text:`Passed: is ${t.predicate??`assertion`}`}}function Xs(e){let t=e,n=t.ref??``,r=t.x,i=t.y;return!n||typeof r!=`number`||typeof i!=`number`?U(t):{data:t,text:`Tapped @${n} (${r}, ${i})`}}const J=Rs({click:V(Xs),press:V(Xs),fill:H,longpress:H,hover:H,scroll:H,get:({input:e,result:t})=>Gs({result:t,format:e.format===`attrs`?`attrs`:`text`}),is:V(Ys),find:V(Ks)}),Zs={find:(e,t)=>tc(e,t),is:(e,t)=>nc(e,t)},Qs={is:g(d.is,e=>$s(e)),find:e=>_(d.find,ec(e),{...e,findFirst:e.first,findLast:e.last})};function $s(e){return[e.predicate,e.selector,...e.predicate===`text`?[e.value]:[]]}function ec(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 tc(e,t){let n={...oc(t),...Zn(t),...Xn(t),first:t.findFirst,last:t.findLast},r=ac(e[0]),a=r!==void 0,o=a?e[1]:e[0],s=a?2:1,c=_t(e[s]);if(c===void 0)return{...n,locator:r,query:sc(o)};if(c===`get`){let t=e[s+1];if(t===`text`)return{...n,locator:r,query:sc(o),action:`getText`};if(t===`attrs`)return{...n,locator:r,query:sc(o),action:`getAttrs`};throw new i(`INVALID_ARGS`,`find get only supports text or attrs`)}if(c===`wait`)return{...n,locator:r,query:sc(o),action:`wait`,timeoutMs:hr(e[s+1])};if(c===`fill`||c===`type`){let t=e.slice(s+1);if(t.length===0)throw new i(`INVALID_ARGS`,c===`fill`?`find fill requires text (use "" to clear the field)`:`find type requires text`);return{...n,locator:r,query:sc(o),action:c,value:t.join(` `)}}if(c===`click`||c===`focus`||c===`exists`||c===`list`)return{...n,locator:r,query:sc(o),action:c};throw new i(`INVALID_ARGS`,`Unsupported find action: ${e[s]}`,{hint:gt})}function nc(e,t){let n={...$n(t),...Zn(t),...Xn(t)},r=yt(e),a=At(r[0]??``);if(!a.ok)throw new i(a.code,a.message,{hint:a.hint});let o=a.predicate;if(o===`absent`){let e=rc(n);if(e)throw ic(e)}let s=ur(r.slice(1),{preferTrailingValue:o===`text`});return o===`text`?{...n,predicate:o,selector:s.selectorExpression,value:s.rest.join(` `)}:{...n,predicate:o,selector:s.selectorExpression}}function rc(e){if(e.scope!==void 0)return`scope`;if(e.depth!==void 0)return`depth`}function ic(e){return new i(`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 ac(e){if(e===`text`||e===`label`||e===`value`||e===`role`||e===`id`)return e}function oc(e){return{depth:e.snapshotDepth,raw:e.snapshotRaw}}function sc(e){if(e===void 0||e===``)throw new i(`INVALID_ARGS`,`find requires query`);return e}const cc=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.`),lc=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:cc},[`nodeCount`,`interactiveNodeCount`,`digest`,`changedFromBefore`]),uc=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`]),dc=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`]),fc={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:dc,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:dc}},[`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 pc(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:Er(),refLabel:E(),targetHittable:O(),hint:E(),warning:E(),message:E(),evidence:lc,resolution:fc,cost:uc,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 mc=pc({properties:{evidence:lc,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.`)}}),hc={text:E(`Text submitted to the field.`),delayMs:D(`Delay between typed characters in milliseconds.`),evidence:lc},gc=C({resourceId:wr(`Identifier of the exact field that changed: Android resource id or Apple accessibility identifier.`),className:wr(`Type of the exact field that changed: Android class name or Apple element type.`),packageName:wr(`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.`),_c={press:mc,click:mc,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:[{...pc({properties:hc,required:[`text`]}),not:C({},[`verification`])},pc({properties:{...hc,verification:T(`unconfirmed`),requested:E(`Literal text requested by the fill command.`),before:wr(`Raw target text captured before the fill.`),after:wr(`Raw target text captured after the fill.`),target:gc},required:[`text`,`verification`,`requested`,`before`,`after`,`target`]})]},longpress:pc({properties:{durationMs:D(),gesture:T(`longpress`)}}),hover:pc({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:uc},[],`Daemon response data for the find command.`)},Y={get:{usageOverride:`get text|attrs <@ref|selector>`,usageFlags:[],positionalArgs:[`subcommand`,`target`],allowsExtraPositionals:!0,allowedFlags:[...Bi,`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:[...Bi,`record`]},click:{usageOverride:`click <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`target`],allowsExtraPositionals:!0,allowedFlags:[...Ui,`clickButton`,...os(`click`),...Bi]},press:{usageOverride:`press <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...Ui,...os(`press`),...Bi]},longpress:{usageOverride:`longpress <x y|@ref|selector> [durationMs]`,usageFlags:[],positionalArgs:[`targetOrX`,`yOrDurationMs?`,`durationMs?`],allowsExtraPositionals:!0,allowedFlags:[...os(`longpress`),...Bi]},hover:{usageOverride:`hover <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...os(`hover`),...Bi]},swipe:{positionalArgs:[`x1`,`y1`,`x2`,`y2`],allowsExtraPositionals:!0,allowedFlags:[`count`,`pauseMs`,`pattern`]},gesture:{usageOverride:`gesture <pan|fling|swipe|pinch|rotate|transform|drag> ...`,usageFlags:[],listUsageOverride:`gesture <pan|fling|swipe|pinch|rotate|transform|drag> ...`,positionalArgs:[`pan|fling|swipe|pinch|rotate|transform|drag`,`args?`],allowsExtraPositionals:!0,allowedFlags:[`pointerCount`]},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:[...Bi,`delayMs`,`recordAs`,`textStdin`,...os(`fill`)]},scroll:{usageOverride:`scroll <direction|top|bottom> [amount]`,usageFlags:[`until`,`maxPasses`,`pixels`,`durationMs`,`settle`],positionalArgs:[`directionOrEdge`,`amount?`],allowedFlags:[`pixels`,`durationMs`,`until`,`maxPasses`,...os(`scroll`)]}},vc=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(yc(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(bc(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).`},metadata:X(`fill`),run:(e,t)=>e.interactions.fill(xc(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(Sc(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(Cc(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(Tc(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:Zs.is,daemonWriter:Qs.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:Zs.find,daemonWriter:Qs.find,cliOutputFormatter:J.find}),z({name:`gesture`,text:{summary:`Run pan, fling, swipe, pinch, rotate, transform, 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], 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:async(e,t)=>{switch(t.kind){case`pan`:return await e.interactions.pan(Ec(t));case`fling`:return await e.interactions.fling(Oc(t));case`swipe`:return await e.interactions.swipeGesture(kc(t));case`pinch`:return await e.interactions.pinch(Ac(t));case`rotate`:return await e.interactions.rotateGesture(jc(t));case`transform`:return await e.interactions.transformGesture(Mc(t));case`drag`:return await e.interactions.drag(Dc(t))}},cliSchema:Y.gesture,cliReader:Es.gesture,daemonWriter:Ds.gesture})]});function X(e){let t=ws.find(t=>t.name===e);if(!t)throw Error(`Missing interaction command metadata for ${e}`);return t}function yc(e){return{...bc(e),button:e.button}}function bc(e){return{...h(e),...Kr(e.target),...Yr(e),...Jr(e),verify:e.verify,...wc(e)}}function xc(e){return{...h(e),...Kr(e.target),...Yr(e),text:e.text,delayMs:e.delayMs,recordAs:e.recordAs,textStdin:e.textStdin,verify:e.verify,...wc(e)}}function Sc(e){return{...h(e),...Kr(e.target),...Yr(e),durationMs:e.durationMs,...wc(e)}}function Cc(e){return{...h(e),...Kr(e.target),...Yr(e),...wc(e)}}function wc(e){return{settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs}}function Tc(e){return{...h(e),...qr(e.target),...Yr(e),format:e.format,record:e.record}}function Ec(e){return{...h(e),x:e.origin.x,y:e.origin.y,dx:e.delta.x,dy:e.delta.y,pointerCount:e.pointerCount,durationMs:e.durationMs}}function Dc(e){return{...h(e),source:e.source,destination:e.destination,sourceHoldMs:e.sourceHoldMs,moveMs:e.moveMs,destinationHoldMs:e.destinationHoldMs}}function Oc(e){return{...h(e),direction:e.direction,x:e.origin.x,y:e.origin.y,distance:e.distance}}function kc(e){return{...h(e),preset:e.preset}}function Ac(e){return{...h(e),scale:e.scale,x:e.origin?.x,y:e.origin?.y}}function jc(e){return{...h(e),degrees:e.degrees,x:e.origin?.x,y:e.origin?.y}}function Mc(e){return{...h(e),x:e.origin.x,y:e.origin.y,dx:e.delta.x,dy:e.delta.y,scale:e.scale,degrees:e.degrees,durationMs:e.durationMs}}async function Nc(e){let{serializeDevice:t}=await import(`./result-serialization.js`).then(e=>e.t);return{data:{devices:e.map(t)},text:e.map(qc).join(`
21
- `)}}async function Pc(e){let{serializeDevice:t}=await import(`./result-serialization.js`).then(e=>e.t);return{data:{device:t(e.device),availableCommands:e.availableCommands},text:[`${qc(e.device)} supports ${e.availableCommands.length} commands:`,e.availableCommands.join(` `)].join(`
22
- `)}}function Fc(e){return{data:{apps:e.result},stderr:e.appsFilter===`all`?`Showing all apps, including system apps.
12
+ `)}function ho(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 go(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 _o(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 vo(e){return e.map(e=>JSON.stringify(e)).join(`
14
+ `)}function yo(e){return Po(e).join(`
15
+ `)}function bo(e){return jo(st(e,{summarizeTextSurfaces:!0})).join(`
16
+ `)}function xo(e){return e&&e.summaryLines.length>0?`\n${e.summaryLines.join(`
17
+ `)}`:``}function So(e,t,n,r,i=0){let a=Co(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:wo([...a?.reasons??[],`offscreen-nodes`])}:a||(s?{partial:!0,visibleNodeCount:n,totalNodeCount:n,reasons:[]}:null)}function Co(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 wo(e){return[...new Set(e)]}function To(e,t,n,r={nodes:t,filteredCount:0}){let i=[...Ao(e),...Eo(e)];if(Do(e)){let e=ko(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&&ao(a)&&i.push(`Warning: possible repeated nav subtree detected.`),i}function Eo(e){let t=e.fallbackScreenshotPath;return typeof t==`string`&&t.length>0?[`Captured a screenshot of this screen automatically as visual truth: ${t}`]:[]}function Do(e){return!e.snapshotQuality&&!Oo(e)}function Oo(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 ko(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 Ao(e){return an(e).filter(e=>e.length>0)}function jo(e){let t=[],n=[],r=new Map(e.map(e=>[e.node.index,e.node])),i=e=>{for(;n.length>0&&(!e||Mo(e,n.at(-1),r));)t.push(...Fo(n.pop(),`below`))};for(let r of e)i(r),t.push(r.text),t.push(...Fo(r,`above`)),r.node.hiddenContentBelow&&n.push(r);return i(),t}function Mo(e,t,n){return!No(e.node,t.node,n)&&e.depth<=t.depth}function No(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 Po(e){return st(e,{summarizeTextSurfaces:!0}).flatMap(e=>[et(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...Fo({...e,depth:0})])}function Fo(e,t){let n=Io(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 Io(e){return e===`scroll-area`||e===`list`||e===`collection`||e===`table`?e:null}async function Lo(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:va(e.result.nodes)});return{data:n,jsonData:zo(n),stderr:e.result.snapshotDiagnostics?.warning?`${e.result.snapshotDiagnostics.warning}\n`:void 0,text:fo(n,{raw:e.raw,flatten:e.interactiveOnly,scoped:typeof e.scope==`string`&&e.scope.trim().length>0,depthLimited:typeof e.depth==`number`})}}const Ro={snapshot:async({input:e,result:t})=>await Lo({result:t,raw:e.raw,interactiveOnly:e.interactiveOnly,scope:e.scope,depth:e.depth}),wait:H,alert:H};function zo(e){let{unchanged:t,...n}=e;return n}const Bo=`snapshot`,Vo=Object.entries(hn).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(`; `),Ho=R(Bo,`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:Ir(`snapshotCustomActions`),observeOnly:Ir(`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.`)}),Uo={allowedFlags:[`snapshotDiff`,...Ji,`snapshotCustomActions`,`snapshotObserveOnly`,`snapshotForceFull`,`timeoutMs`,`record`]},Wo=(e,t)=>({...v(t),...rr(t),...o(t,c),timeoutMs:t.timeoutMs}),Go=g(d.snapshot),Ko=z({name:Bo,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: ${Vo}.`},metadata:Ho,run:(e,t)=>e.capture.snapshot(t),cliSchema:Uo,cliReader:Wo,daemonWriter:Go,cliOutputFormatter:Ro.snapshot}),qo=[`duration`,`text`,`ref`,`selector`,`absent`,`stable`],Jo=`wait`,Yo={wait:C({waitedMs:D(),kind:T(`selector`),text:E(),selector:E(),captures:D(),nodeCount:D(),hint:E(),warning:E()},[`waitedMs`])},Xo=z({name:Jo,text:{summary:`Wait for a duration, text, selector, strict absence, or stable UI`},metadata:R(Jo,`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(Zo(t)),cliSchema:{usageOverride:`wait <ms>|text <text>|@ref|<selector>|absent <selector> [timeoutMs]|stable [quietMs] [timeoutMs]`,usageFlags:[],positionalArgs:[`durationOrSelector`,`timeoutMs?`],allowsExtraPositionals:!0,allowedFlags:[...Yi]},cliReader:(e,t)=>Qo(e,t),daemonWriter:g(d.wait,e=>ts(e)),cliOutputFormatter:H});function Zo(e){Vn(e,`kind`,qo);let t={...e};return delete t.kind,t}function Qo(e,t){let n=Dt(e);if(!n)throw new i(`INVALID_ARGS`,`wait requires <ms>, text <text>, @ref, <selector> [timeoutMs], absent <selector> [timeoutMs], or stable [quietMs] [timeoutMs].`);let r={...ir(t),...or(t)};switch(n.kind){case`absent`:return $o(r,n);case`sleep`:return{...r,durationMs:n.durationMs};case`text`:return es(r,n);case`ref`:return{...r,ref:n.rawRef,...ns(n.timeoutMs)};case`stable`:return{...r,stable:!0,...rs(n.quietMs),...ns(n.timeoutMs)};case`invalid`:throw new i(`INVALID_ARGS`,n.message);case`selector`:return{...r,selector:n.selectorExpression,...ns(n.timeoutMs)};default:return is(n)}}function $o(e,t){let n=$e(e);if(n)throw _n(n,`wait`);return{...e,absent:t.selectorExpression,...ns(t.timeoutMs)}}function es(e,t){if(!t.text)throw new i(`INVALID_ARGS`,`wait requires text.`);return{...e,text:t.text,...ns(t.timeoutMs)}}function ts(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 i(`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 n=$e(e);if(n)throw _n(n,`wait`);if(!Mt(e.absent))throw new i(`INVALID_ARGS`,`Invalid wait absent selector: ${e.absent}`);return[`absent`,e.absent,...t]}if(e.stable!==void 0){let n=b(e.quietMs);if(n.length===0&&t.length>0)throw new i(`INVALID_ARGS`,`wait stable requires quietMs before timeoutMs.`);return[`stable`,...n,...t]}let n=e.selector;if(!Mt(n))throw new i(`INVALID_ARGS`,`Invalid wait selector: ${n}`);return[n,...t]}function ns(e){return e===null?{}:{timeoutMs:e}}function rs(e){return e===null?{}:{quietMs:e}}function is(e){throw Error(`Unsupported wait positional target: ${String(e)}`)}const as=B({name:`capture`,commands:[Ko,ca,oa,Xo,Ui,ha]});function os(e){let t=[e.outPath,e.message];t.push(...cs(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 ss={debug:V(os)};function cs(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 ls=`debug`,us=B({name:`debugging`,commands:[z({name:ls,text:{summary:`Symbolicate Apple crash artifacts`},metadata:R(ls,`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:ds(e[0]),artifact:t.artifact,dsym:t.dsym,searchPath:t.searchPath,out:t.out}),cliOutputFormatter:ss.debug})]});function ds(e){if(e===`symbols`)return e;throw new i(`INVALID_ARGS`,`debug supports only symbols; use logs, network, perf, record, trace, or react-devtools for other diagnostics`)}const fs=()=>P(`Capture cheap post-action evidence (AX digest, node counts, changedFromBefore) instead of a follow-up snapshot.`),ps=()=>({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 ms(e){return{...jt(e)?{verify:fs()}:{},...Nt(e)?ps():{}}}function hs(e){let t=[];return jt(e)&&t.push(`verify`),Nt(e)&&t.push(...$i),t}function gs(e,t){return Nt(e)?sr(t):{}}const _s=[`click`,`focus`,`exists`,`list`,`getText`,`getAttrs`,`wait`,`fill`,`type`],vs={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.`},ys={target:A(Ur()),button:F(at,`Pointer button for platforms that support mouse buttons.`),...Jr(),...Yr(),...ms(`click`)},bs={target:A(Ur()),...Jr(),...Yr(),...ms(`press`)},xs={target:A(Ur()),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:Fr(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.`}),...Jr(),...ms(`fill`)},Ss={target:A(Ur()),durationMs:N(`Long press duration in milliseconds.`,{min:0}),...Jr(),...ms(`longpress`)},Cs={target:A(Ur()),...Jr(),...ms(`hover`)},ws={from:A(Gr(`Swipe start point.`)),to:A(Gr(`Swipe end point.`)),count:N(`Number of swipe repetitions.`,{min:1,max:200}),pauseMs:N(`Pause between repeated swipes.`,{min:0,max:je}),pattern:F(Oe)},Ts={x:A(M(`X coordinate.`)),y:A(M(`Y coordinate.`))},Es={text:A(j(`Text to type.`)),delayMs:N(`Delay between typed characters.`,{min:0})},Ds={direction:A(F(ye)),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:fe}),...ms(`scroll`)},Os=()=>({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.`)}),ks={format:A(F([`text`,`attrs`])),target:A(Wr()),...Jr(),...Os()},As={predicate:A(F(Ft)),selector:A(j()),value:j(),...Jr(),...Os()},js={locator:F(bt),query:A(j()),action:F(_s),value:j(void 0,{allowEmpty:!0}),timeoutMs:N(),first:P(),last:P(),depth:N(),raw:P(),...Os()},Ms={kind:A(F(ot,`Gesture variant.`)),direction:F(l,`Fling direction.`),preset:F(we,`Swipe preset.`),origin:Gr(`Gesture origin point.`),delta:Gr(`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:Kr(`Tap contact points, held together for holdMs.`,{min:2,max:5}),holdMs:N(`Tap contact hold duration.`,{min:16,max:pe}),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:je}),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})},Ns=[G(`click`,ys),G(`press`,bs),G(`fill`,xs),G(`longpress`,Ss),G(`hover`,Cs),G(`swipe`,ws),G(`focus`,Ts),G(`type`,Es),G(`scroll`,Ds),G(`get`,ks,{parseableOutput:!0}),G(`is`,As),G(`find`,js,{parseableOutput:!0}),R(`gesture`,vs.gesture,Ms,{readInput:Ps})];function Ps(e){let t=Pn(e);return{...Qn(t),...ct(t)}}function G(e,t,n){return R(e,vs[e],t,n)}const Fs={gesture:Ls},Is={gesture:e=>{let t=Ps(e);return _(d.gesture,[],e,m(t))}};function Ls(e,t){return{...v(t),...ut(e,{pointerCount:t.pointerCount,holdMs:t.holdMs,count:t.count,pauseMs:t.pauseMs})}}const K={click:(e,t)=>({...v(t),...ar(t),...cr(t),target:lr(vn(e)),button:t.clickButton,verify:t.verify}),press:(e,t)=>({...v(t),...ar(t),...cr(t),target:lr(vn(e)),verify:t.verify}),longpress:(e,t)=>{let n=zs(e);return{...v(t),...ar(t),target:lr(n),durationMs:n.durationMs}},hover:(e,t)=>({...v(t),...ar(t),target:lr(vn(e))}),swipe:(e,t)=>({...v(t),...Qe(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?Rs(e):yn(e);return{...v(t),...ar(t),target:lr(n.target),text:n.text,delayMs:t.delayMs,recordAs:t.recordAs,textStdin:t.textStdin,verify:t.verify}},scroll:(e,t)=>({...v(t),direction:Us(e[0]),amount:Sr(e[1]),pixels:t.pixels,durationMs:t.durationMs,until:t.until,maxPasses:t.maxPasses}),get:(e,t)=>({...v(t),...rr(t),...ar(t),format:gr(e[0]),target:lr(hr(e.slice(1)))})},q={click:e=>_(d.click,ur(e),{...e,clickButton:e.button}),press:g(d.press,e=>ur(e)),longpress:g(d.longPress,e=>Bs(e)),hover:g(d.hover,e=>ur(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=>Vs(e)),fill:g(d.fill,e=>Hs(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`),...dr(e)])};function Rs(e){let t;try{t=yn(e)}catch(e){throw e instanceof i?new i(`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 i(`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 zs(e){let t=Ws(e);return{...vn(t.target),...t.durationMs===void 0?{}:{durationMs:t.durationMs}}}function Bs(e){return[...ur(e),...b(e.durationMs)]}function Vs(e){return[e.text]}function Hs(e){return[...ur(e),e.text]}function Us(e){if(e===`up`||e===`down`||e===`left`||e===`right`||e===`top`||e===`bottom`)return e;throw new i(`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 Ws(e){if(br(e[0])&&br(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&&br(t)?{target:e.slice(0,-1),durationMs:Number(t)}:{target:e}}function Gs(e){return t=>{let n=e(t);return n instanceof Promise?n.then(Ks):Ks(n)}}function Ks(e){return{data:e.data,text:Js(e.text,e.data)}}function qs(e){let t={...e};for(let[n,r]of Object.entries(e))Nt(n)&&(t[n]=Gs(r));return t}function Js(e,t){return`${e??``}${Ys(t.settle)}`}function Ys(e){if(!e||typeof e!=`object`)return``;let t=e,n=[$s(t),...Xs(t),...Qs(t)];return t.hint&&n.push(`hint: ${t.hint}`),`\n${n.join(`
19
+ `)}`}function Xs(e){let t=e.diff,n=(t?.lines??[]).map(t=>`${t.kind===`removed`?`-`:`+`} ${Zs(t,e.refsGeneration)}`);return t?.truncated&&n.push(`… changed lines truncated`),n}function Zs(e,t){let n=e.text??``,r=vi(e.ref,t);if(!r||!e.ref)return n;let i=`@${e.ref}`;return n.startsWith(`${i} `)?`${r}${n.slice(i.length)}`:n}function Qs(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=vi(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 $s(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 ec(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 tc(e){let t=e,n=on(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:nc(t.matches,t.refsGeneration)};let r=vi(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)}:U(t)}function nc(e,t){return[`${e.length} match${e.length===1?``:`es`}:`,...e.map(e=>rc(e,t))].join(`
20
+ `)}function rc(e,n){let r=e.ref===void 0?`(no ref)`:vi(e.ref,n)??e.ref,i=t(e.node?.type??`Element`),a=e.node?it(e.node,i):``;return`= ${r} [${i}]${a?` "${a}"`:``}`}function ic(e){let t=e;return{data:t,text:`Passed: is ${t.predicate??`assertion`}`}}function ac(e){let t=e,n=t.ref??``,r=t.x,i=t.y;return!n||typeof r!=`number`||typeof i!=`number`?U(t):{data:t,text:`Tapped @${n} (${r}, ${i})`}}const J=qs({click:V(ac),press:V(ac),fill:H,longpress:H,hover:H,scroll:H,get:({input:e,result:t})=>ec({result:t,format:e.format===`attrs`?`attrs`:`text`}),is:V(ic),find:V(tc)}),oc={find:(e,t)=>uc(e,t),is:(e,t)=>dc(e,t)},sc={is:g(d.is,e=>cc(e)),find:e=>_(d.find,lc(e),{...e,findFirst:e.first,findLast:e.last})};function cc(e){return[e.predicate,e.selector,...e.predicate===`text`?[e.value]:[]]}function lc(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 uc(e,t){let n={...hc(t),...ir(t),...rr(t),first:t.findFirst,last:t.findLast},r=mc(e[0]),a=r!==void 0,o=a?e[1]:e[0],s=a?2:1,c=Ct(e[s]);if(c===void 0)return{...n,locator:r,query:gc(o)};if(c===`get`){let t=e[s+1];if(t===`text`)return{...n,locator:r,query:gc(o),action:`getText`};if(t===`attrs`)return{...n,locator:r,query:gc(o),action:`getAttrs`};throw new i(`INVALID_ARGS`,`find get only supports text or attrs`)}if(c===`wait`)return{...n,locator:r,query:gc(o),action:`wait`,timeoutMs:Sr(e[s+1])};if(c===`fill`||c===`type`){let t=e.slice(s+1);if(t.length===0)throw new i(`INVALID_ARGS`,c===`fill`?`find fill requires text (use "" to clear the field)`:`find type requires text`);return{...n,locator:r,query:gc(o),action:c,value:t.join(` `)}}if(c===`click`||c===`focus`||c===`exists`||c===`list`)return{...n,locator:r,query:gc(o),action:c};throw new i(`INVALID_ARGS`,`Unsupported find action: ${e[s]}`,{hint:St})}function dc(e,t){let n={...or(t),...ir(t),...rr(t)},r=yt(e),a=Lt(r[0]??``);if(!a.ok)throw new i(a.code,a.message,{hint:a.hint});let o=a.predicate;if(o===`absent`){let e=fc(n);if(e)throw pc(e)}let s=_r(r.slice(1),{preferTrailingValue:o===`text`});return o===`text`?{...n,predicate:o,selector:s.selectorExpression,value:s.rest.join(` `)}:{...n,predicate:o,selector:s.selectorExpression}}function fc(e){if(e.scope!==void 0)return`scope`;if(e.depth!==void 0)return`depth`}function pc(e){return new i(`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 mc(e){if(e===`text`||e===`label`||e===`value`||e===`role`||e===`id`)return e}function hc(e){return{depth:e.snapshotDepth,raw:e.snapshotRaw}}function gc(e){if(e===void 0||e===``)throw new i(`INVALID_ARGS`,`find requires query`);return e}const _c=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.`),vc=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:_c},[`nodeCount`,`interactiveNodeCount`,`digest`,`changedFromBefore`]),yc=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`]),bc=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`]),xc={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:bc,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:bc}},[`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 Sc(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:Nr(),refLabel:E(),targetHittable:O(),hint:E(),warning:E(),message:E(),evidence:vc,resolution:xc,cost:yc,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 Cc=Sc({properties:{evidence:vc,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.`)}}),wc={text:E(`Text submitted to the field.`),delayMs:D(`Delay between typed characters in milliseconds.`),evidence:vc},Tc=C({resourceId:jr(`Identifier of the exact field that changed: Android resource id or Apple accessibility identifier.`),className:jr(`Type of the exact field that changed: Android class name or Apple element type.`),packageName:jr(`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.`),Ec={press:Cc,click:Cc,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:[{...Sc({properties:wc,required:[`text`]}),not:C({},[`verification`])},Sc({properties:{...wc,verification:T(`unconfirmed`),requested:E(`Literal text requested by the fill command.`),before:jr(`Raw target text captured before the fill.`),after:jr(`Raw target text captured after the fill.`),target:Tc},required:[`text`,`verification`,`requested`,`before`,`after`,`target`]})]},longpress:Sc({properties:{durationMs:D(),gesture:T(`longpress`)}}),hover:Sc({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:yc},[],`Daemon response data for the find command.`)},Dc=Ze,Oc=[...new Set(Object.values(Dc).flat())],Y={get:{usageOverride:`get text|attrs <@ref|selector>`,usageFlags:[],positionalArgs:[`subcommand`,`target`],allowsExtraPositionals:!0,allowedFlags:[...Yi,`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:[...Yi,`record`]},click:{usageOverride:`click <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`target`],allowsExtraPositionals:!0,allowedFlags:[...Qi,`clickButton`,...hs(`click`),...Yi]},press:{usageOverride:`press <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...Qi,...hs(`press`),...Yi]},longpress:{usageOverride:`longpress <x y|@ref|selector> [durationMs]`,usageFlags:[],positionalArgs:[`targetOrX`,`yOrDurationMs?`,`durationMs?`],allowsExtraPositionals:!0,allowedFlags:[...hs(`longpress`),...Yi]},hover:{usageOverride:`hover <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...hs(`hover`),...Yi]},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:Oc,flagsByAction:Dc},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:[...Yi,`delayMs`,`recordAs`,`textStdin`,...hs(`fill`)]},scroll:{usageOverride:`scroll <direction|top|bottom> [amount]`,usageFlags:[`until`,`maxPasses`,`pixels`,`durationMs`,`settle`],positionalArgs:[`directionOrEdge`,`amount?`],allowedFlags:[`pixels`,`durationMs`,`until`,`maxPasses`,...hs(`scroll`)]}},kc=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(Ac(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(jc(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).`},metadata:X(`fill`),run:(e,t)=>e.interactions.fill(Mc(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(Nc(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(Pc(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(Ic(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:oc.is,daemonWriter:sc.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:oc.find,daemonWriter:sc.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({...ct(t),...h(t)}),cliSchema:Y.gesture,cliReader:Fs.gesture,daemonWriter:Is.gesture})]});function X(e){let t=Ns.find(t=>t.name===e);if(!t)throw Error(`Missing interaction command metadata for ${e}`);return t}function Ac(e){return{...jc(e),button:e.button}}function jc(e){return{...h(e),...ti(e.target),...ii(e),...ri(e),verify:e.verify,...Fc(e)}}function Mc(e){return{...h(e),...ti(e.target),...ii(e),text:e.text,delayMs:e.delayMs,recordAs:e.recordAs,textStdin:e.textStdin,verify:e.verify,...Fc(e)}}function Nc(e){return{...h(e),...ti(e.target),...ii(e),durationMs:e.durationMs,...Fc(e)}}function Pc(e){return{...h(e),...ti(e.target),...ii(e),...Fc(e)}}function Fc(e){return{settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs}}function Ic(e){return{...h(e),...ni(e.target),...ii(e),format:e.format,record:e.record}}async function Lc(e){let{serializeDevice:t}=await import(`./result-serialization.js`).then(e=>e.t);return{data:{devices:e.map(t)},text:e.map(Zc).join(`
21
+ `)}}async function Rc(e){let{serializeDevice:t}=await import(`./result-serialization.js`).then(e=>e.t);return{data:{device:t(e.device),availableCommands:e.availableCommands},text:[`${Zc(e.device)} supports ${e.availableCommands.length} commands:`,e.availableCommands.join(` `)].join(`
22
+ `)}}function zc(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 Ic(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 Lc(e){let{serializeOpenResult:t}=await import(`./result-serialization.js`).then(e=>e.t),n=t(e),r=[Qt(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 Rc(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 Rc(e){return!e||!Array.isArray(e.nodes)?null:await Oo({result:e,interactiveOnly:!0})}async function zc(e){let{serializeCloseResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return U(t(e))}function Bc(e){if(Vc(e))return{data:e,text:e.artifacts.length>0?e.artifacts.map(Yc).join(`
27
- `):e.message??`No daemon artifacts available.`};let t=[e.message??`No cloud artifacts available for ${e.provider}.`],n=Xc(e);return n&&t.push(`Retry: ${n}`),{data:e,text:e.cloudArtifacts.length>0?e.cloudArtifacts.map(Jc).join(`
25
+ `):e.appsFilter===`all`?`No apps found.`:`No user apps or provider app assets found.`}}async function Bc(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 Vc(e){let{serializeOpenResult:t}=await import(`./result-serialization.js`).then(e=>e.t),n=t(e),r=[on(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 Hc(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 Hc(e){return!e||!Array.isArray(e.nodes)?null:await Lo({result:e,interactiveOnly:!0})}async function Uc(e){let{serializeCloseResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return U(t(e))}function Wc(e){if(Gc(e))return{data:e,text:e.artifacts.length>0?e.artifacts.map($c).join(`
27
+ `):e.message??`No daemon artifacts available.`};let t=[e.message??`No cloud artifacts available for ${e.provider}.`],n=el(e);return n&&t.push(`Retry: ${n}`),{data:e,text:e.cloudArtifacts.length>0?e.cloudArtifacts.map(Qc).join(`
28
28
  `):t.join(`
29
- `)}}function Vc(e){return`source`in e&&e.source===`daemon`}async function Hc(e){let{serializeDeployResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return U(t(e))}async function Uc(e){let{serializeInstallFromSourceResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return U(t(e))}function Wc(e){let t=e,n=t.platform??`unknown`;return{data:t,text:`Boot ready: ${t.device??t.id??`unknown`} (${n})`}}function Gc(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 Kc(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=Zc(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(Wc),shutdown:V(Gc),devices:V(Nc),capabilities:V(Pc),doctor:({result:e,env:t,progress:n})=>Kc(e,t,n),apps:({input:e,result:t})=>Fc({result:t,appsFilter:e.appsFilter}),session:V(Ic),artifacts:V(Bc),open:V(Lc),close:V(zc),install:V(Hc),reinstall:V(Hc),"install-from-source":V(Uc),prepare:H,viewport:H};function qc(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 Jc(e){let t=e.url?` ${e.url}`:``,n=e.availability?` ${e.availability}`:``;return`${e.kind}: ${e.name}${n}${t}`}function Yc(e){let t=e.artifactType?` (${e.artifactType})`:``;return`${e.filename}${t}: ${e.mimeType} ${e.sizeBytes} bytes id=${e.id}`}function Xc(e){if(e.providerSessionId)return`agent-device artifacts ${e.providerSessionId} --provider ${e.provider} --json`}function Zc(e){return Array.isArray(e)?e.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):[]}const Qc=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 $c(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 el(e){let{metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i,...a}=e,o=$c({metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i});return o?{...a,runtime:o}:a}const tl=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.`)}),nl=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(It,`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. iOS simulator direct app launches only; not for URL opens.`),launchArgs:Pr(`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:kr(`waitMs`),foreground:kr(`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.`)}),rl=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, or its process stays running, past its 2s check window.`,{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 il(e){return el(e)}const al={allowedFlags:[`appsFilter`]},ol={positionalArgs:[`appOrUrl?`,`url?`],allowedFlags:[`activity`,`launchConsole`,`launchArgs`,`testIme`,`saveScript`,`force`,`noRecord`,`relaunch`,`foreground`,`timeoutMs`,`waitMs`,`surface`,...Hi,`launchUrl`]},sl={positionalArgs:[`app?`],allowedFlags:[`saveScript`,`force`,`shutdown`]},cl=(e,t)=>({...v(t),appsFilter:pn(t.appsFilter)}),ll=(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}),ul=(e,t)=>({...v(t),app:e[0],shutdown:t.shutdown,saveScript:t.saveScript,force:t.force}),dl=g(d.apps),fl=g(d.open,vl),pl=g(d.close,e=>y(e.app)),ml=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:tl,run:(e,t)=>e.apps.list(t),cliSchema:al,cliReader:cl,daemonWriter:dl,cliOutputFormatter:Z.apps}),hl=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 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; in both cases inspect the warning and answer with alert get then alert accept; 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. A recognized prompt still visible after a failed accept 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:nl,run:(e,t)=>e.apps.open(il(t)),cliSchema:ol,cliReader:ll,daemonWriter:fl,cliOutputFormatter:Z.open}),gl=z({name:`close`,text:{summary:`Close an app or end the session`},metadata:rl,run:(e,t)=>t.app?e.apps.close(t):e.sessions.close(_l(t)),cliSchema:sl,cliReader:ul,daemonWriter:pl,cliOutputFormatter:Z.close});function _l(e){let{app:t,...n}=e;return n}function vl(e){return e.app?e.url?[e.app,e.url]:[e.app]:[]}const yl={platform:w(st),target:w(lt),device:E(`Human-readable device name.`),id:E(`Stable device id.`),kind:w(ut)},bl=[`platform`,`target`,`device`,`id`,`kind`],xl=C({success:O(),exitCode:D(),stdout:E(),stderr:E(),error:k(`Normalized error detail when shutdown failed.`)},[`success`,`exitCode`,`stdout`,`stderr`]),Sl={boot:C({...yl,booted:{type:`boolean`,const:!0}},[...bl,`booted`]),shutdown:C({...yl,shutdown:xl},[...bl,`shutdown`])},Cl=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.`,{}),wl=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.`,{}),Tl=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})}),El=R(`shutdown`,`Shutdown a selected simulator or emulator.`,{}),Dl={allowedFlags:[`headless`,`timeoutMs`]},Ol={},kl={},Al={},jl=(e,t)=>v(t),Ml=(e,t)=>({...v(t),headless:t.headless,timeoutMs:t.timeoutMs}),Nl=g(d.devices),Pl=g(d.capabilities),Fl=g(d.boot),Il=g(d.shutdown),Ll=[z({name:`devices`,text:{summary:`List available devices and simulators`},metadata:Cl,run:(e,t)=>e.devices.list(t),cliSchema:Ol,cliReader:jl,daemonWriter:Nl,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:wl,run:(e,t)=>e.devices.capabilities(t),cliSchema:kl,cliReader:jl,daemonWriter:Pl,cliOutputFormatter:Z.capabilities}),z({name:`boot`,text:{summary:`Boot target device/simulator`},metadata:Tl,run:(e,t)=>e.devices.boot(t),cliSchema:Dl,cliReader:Ml,daemonWriter:Fl,cliOutputFormatter:Z.boot}),z({name:`shutdown`,text:{summary:`Shutdown target simulator/emulator`},metadata:El,run:(e,t)=>e.devices.shutdown(t),cliSchema:Al,cliReader:jl,daemonWriter:Il,cliOutputFormatter:Z.shutdown})],Rl={doctor:C({status:w([`pass`,`warn`,`fail`,`info`]),summary:E(),kind:w([`auto`,`react-native`,`expo`,`repack`]),platform:E(),target:w(lt),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`])},zl=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 Bl(e,t=`--github-actions-artifact`){let n=e.indexOf(`:`);if(n<=0||n===e.length-1)throw new i(`INVALID_ARGS`,`${t} must use owner/repo:artifact, for example thymikee/RNCLI83:6635342232`);let{owner:r,repo:a}=Ul(e.slice(0,n),t);return Hl(r,a,e.slice(n+1),`${t} artifact`)}function Vl(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new i(`INVALID_ARGS`,`${t} installSource must be an object.`);let n=e;if(Gl(n.type,`${t} installSource.type`)!==`github-actions-artifact`)throw new i(`INVALID_ARGS`,`${t} installSource.type must be "github-actions-artifact".`);let{owner:r,repo:a}=Ul(Gl(n.repo,`${t} installSource.repo`),`${t} installSource.repo`);return Hl(r,a,n.artifact,`${t} installSource.artifact`)}function Hl(e,t,n,r){return typeof n==`number`||ql(n)?{kind:`github-actions-artifact`,owner:e,repo:t,artifactId:Kl(n,r)}:{kind:`github-actions-artifact`,owner:e,repo:t,artifactName:Gl(n,r)}}function Ul(e,t){let n=e.indexOf(`/`);if(n<=0||n===e.length-1||e.indexOf(`/`,n+1)!==-1)throw new i(`INVALID_ARGS`,`${t} must use owner/repo.`);let r={owner:e.slice(0,n).trim(),repo:e.slice(n+1).trim()};if(!r.owner||!r.repo)throw new i(`INVALID_ARGS`,`${t} must use owner/repo.`);return r}function Wl(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Gl(e,t){let n=Wl(e);if(!n)throw new i(`INVALID_ARGS`,`${t} must be a non-empty string.`);return n}function Kl(e,t){let n=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;if(!Number.isInteger(n))throw new i(`INVALID_ARGS`,`${t} must be an integer.`);return n}function ql(e){return typeof e==`string`&&/^\d+$/.test(e.trim())}const Jl=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.`))}),Yl=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.`))}),Xl=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.`))}),Zl=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()}),Ql={usageOverride:`install <path> | install <app> <path>`,listUsageOverride:`install <path>`,positionalArgs:[`appOrPath`,`path?`]},$l={positionalArgs:[`app`,`path`]},eu={positionalArgs:[`app`]},tu={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`]},nu=(e,t)=>uu(e,t),ru=(e,t)=>du(e,t),iu=(e,t)=>({...v(t),app:x(e[0],`uninstall requires app`)}),au=(e,t)=>({...v(t),source:mu(e,t),retainPaths:t.retainPaths,retentionMs:t.retentionMs}),ou=g(d.install,e=>fu(e.app,e.appPath)),su=g(d.reinstall,e=>pu(e.app,e.appPath)),cu=g(d.uninstall,e=>[S(e.app,`missing app`)]),lu=[z({name:`install`,text:{summary:`Install an app binary from a path`},metadata:Jl,run:(e,t)=>e.apps.install(t),cliSchema:Ql,cliReader:nu,daemonWriter:ou,cliOutputFormatter:Z.install}),z({name:`reinstall`,text:{summary:`Replace an installed app with a new build`},metadata:Yl,run:(e,t)=>e.apps.reinstall(t),cliSchema:$l,cliReader:ru,daemonWriter:su,cliOutputFormatter:Z.reinstall}),z({name:`uninstall`,text:{summary:`Remove an installed app`},metadata:Xl,run:(e,t)=>e.apps.uninstall(t),cliSchema:eu,cliReader:iu,daemonWriter:cu}),z({name:`install-from-source`,text:{summary:`Install app builds from URLs or CI artifacts`},metadata:Zl,run:(e,t)=>e.apps.installFromSource(t),cliSchema:tu,cliReader:au,daemonWriter:e=>_(Ue.installSource,[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),cliOutputFormatter:Z[`install-from-source`]})];function uu(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`)}}function du(e,t){return{...v(t),app:x(e[0],`reinstall requires app`),appPath:x(e[1],`reinstall requires path`)}}function fu(e,t){let n=S(t,`missing app path`);return typeof e==`string`&&e.length>0?[e,n]:[n]}function pu(e,t){return[S(e,`missing first positional`),S(t,`missing second positional`)]}function mu(e,t){let n=e[0]?.trim();if(e.length>1)throw new i(`INVALID_ARGS`,`install-from-source accepts either one <url> positional or --github-actions-artifact`);let r=t.githubActionsArtifact?Bl(t.githubActionsArtifact):void 0,a=t.installSource;if(+!!n+ +!!r+ +!!a!=1)throw new i(`INVALID_ARGS`,`install-from-source requires exactly one source: <url>, --github-actions-artifact, or config installSource`);if(!n&&t.header&&t.header.length>0)throw new i(`INVALID_ARGS`,`install-from-source --header is only supported for URL sources`);if(r)return r;if(a)return a;if(!hu(n))throw new i(`INVALID_ARGS`,`install-from-source <url> must be an http(s) URL: ${n}`,{hint:`Install a local build with install <app> <path>.`});return{kind:`url`,url:n,headers:gu(t.header)}}function hu(e){let t=URL.parse(e)?.protocol;return t===`http:`||t===`https:`}function gu(e){if(!e||e.length===0)return;let t={};for(let n of e){let e=n.indexOf(`:`);if(e<=0)throw new i(`INVALID_ARGS`,`Invalid --header value "${n}". Expected "name:value".`);let r=n.slice(0,e).trim(),a=n.slice(e+1).trim();if(!r)throw new i(`INVALID_ARGS`,`Invalid --header value "${n}". Header name cannot be empty.`);t[r]=a}return t}const _u=[`ios-runner`],vu={prepare:C({action:T(`ios-runner`),platform:w(st),deviceId:E(),deviceName:E(),kind:w(ut),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`])},yu=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(_u)),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}),bu={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`])},xu=R(`push`,`Deliver push notification payloads to an installed app.`,{app:A(j()),payload:A(I({oneOf:[E(),k()]}))}),Su=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:Mu(`Structured payload passed to the event, in the shape the app documents for it.`)}),Cu={listUsageOverride:`push`,positionalArgs:[`bundleOrPackage`,`payloadOrJson`]},wu={usageOverride:`trigger-app-event <event> [payloadJson]`,listUsageOverride:`trigger-app-event`,positionalArgs:[`event`,`payloadJson?`]},Tu=(e,t)=>({...v(t),app:x(e[0],`push requires bundleOrPackage`),payload:x(e[1],`push requires payloadOrJson`)}),Eu=(e,t)=>({...v(t),event:x(e[0],`trigger-app-event requires event`),payload:e[1]?dr(e[1],`trigger-app-event payload`):void 0}),Du=g(d.push,e=>Au(e)),Ou=g(d.triggerAppEvent,e=>ju(e)),ku=[z({name:`push`,text:{summary:`Deliver a push notification payload`},metadata:xu,run:(e,t)=>e.apps.push(t),cliSchema:Cu,cliReader:Tu,daemonWriter:Du}),z({name:`trigger-app-event`,text:{summary:`Invoke an app-defined automation event`},metadata:Su,run:(e,t)=>e.apps.triggerEvent(t),cliSchema:wu,cliReader:Eu,daemonWriter:Ou})];function Au(e){return[e.app,typeof e.payload==`string`?e.payload:JSON.stringify(e.payload)]}function ju(e){return[e.event,...e.payload?[JSON.stringify(e.payload)]:[]]}function Mu(e){return Nr(e)}const Nu=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 Fu(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:Pu(e[0]),path:e[1],force:t.force}),cliOutputFormatter:Z.session});function Pu(e){let t=e??`list`;if(t===`list`||t===`state-dir`||t===`save-script`)return t;throw new i(`INVALID_ARGS`,`session only supports list, state-dir, or save-script`)}function Fu(e,t,n){if(e!==`save-script`&&(t!==void 0||n===!0))throw new i(`INVALID_ARGS`,`session ${e} does not accept a path or --force; use session save-script [path] [--force] to publish a recording.`)}const Iu={viewport:C({width:D(),height:D(),message:E()},[`width`,`height`,`message`])},Lu=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),...We(e)}),daemonWriter:g(d.viewport,e=>{let{width:t,height:n}=e;return[String(t),String(n)]}),cliOutputFormatter:Z.viewport}),Ru=B({name:`management`,commands:[...Ll,Qc,zl,yu,ml,Nu,hl,gl,Lu,...lu,...ku]});function zu(e){return{data:e.result,text:e.action===`reload`?`Reloaded React Native apps via ${e.result.reloadUrl}`:JSON.stringify(e.result,null,2)}}const Bu={metro:({input:e,result:t})=>zu({result:t,action:e.action})},Vu=[`auto`,`react-native`,`expo`,`repack`];function Hu(e){if(e!==void 0){if(Vu.includes(e))return e;throw new i(`INVALID_ARGS`,`metro prepare --kind must be auto, react-native, expo, or repack`)}}const Uu=`metro`,Wu=B({name:`metro`,commands:[z({name:Uu,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(Uu,`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:Or(j(),{operatorPath:`Configure the remote proxy in the remote-config profile or operator config for the process serving these tools.`}),bearerToken:Or(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(Gu(t)):await e.metro.reload(qu(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:[...Hi,...Vi]},cliReader:(e,t)=>{let n=(e[0]??``).toLowerCase();if(n!==`prepare`&&n!==`reload`)throw new i(`INVALID_ARGS`,`metro requires a subcommand: prepare or reload`);if(n===`reload`)return{action:n,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,timeoutMs:t.metroProbeTimeoutMs};if(!t.metroPublicBaseUrl&&!t.metroProxyBaseUrl)throw new i(`INVALID_ARGS`,`metro prepare requires --public-base-url <url> or --proxy-base-url <url>.`);return{action:n,projectRoot:t.metroProjectRoot,kind:Hu(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:Bu.metro})]});function Gu(e){return{projectRoot:e.projectRoot,kind:e.kind,publicBaseUrl:e.publicBaseUrl,proxyBaseUrl:e.proxyBaseUrl,bearerToken:e.bearerToken,bridgeScope:e.bridgeScope??Ku(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 Ku(e){return e.tenant&&e.runId&&e.leaseId?{tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId}:void 0}function qu(e){return{metroHost:e.metroHost,metroPort:e.metroPort,bundleUrl:e.bundleUrl,timeoutMs:e.timeoutMs}}function Ju(e,t){return e.includes(t)}function Yu(e,t,n={}){let r=t===void 0?void 0:n.normalize?.(t)??t;if(r!==void 0&&Ju(e,r))return r;let a=typeof n.message==`function`?n.message(t):n.message;throw new i(`INVALID_ARGS`,a??`Invalid value: ${t}. Use ${e.join(`|`)}.`)}const Xu=[`started`,`stopped`,`marked`,`cleared`,`restarted`,`removedRotatedFiles`];function Zu(e){return{data:e,text:e.path,stderr:Cd([xd(e,[`active`,`state`,`backend`,`sizeBytes`]),xd(e,Xu),e.hint,Sd(e.notes)])}}function Qu(e){let t=e.events??[];return{data:e,text:t.length>0?nd(t):`No session events found.`,stderr:Cd([xd(e,[`path`,`cursor`,`nextCursor`,`limit`])])}}function $u(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(...vd(e));return{data:e,text:t.join(`
32
- `),stderr:Cd([xd(e,[`active`,`state`,`backend`,`include`,`scannedLines`,`matchedLines`]),Sd(e.notes)])}}function ed(e){return{data:e,text:[`Audio probe: ${String(e.state??`stopped`)} heard=${String(e.heard===!0)}`,md(`rmsDbfs`,e.rmsDbfs),md(`peakDbfs`,e.peakDbfs)].filter(e=>!!e).join(`
33
- `),stderr:Cd([xd(e,[`active`,`backend`,`source`,`durationMs`,`elapsedMs`,`bucketMs`,`sampleCount`,`sourceCount`,`mediaElementCount`]),Sd(e.notes)])}}const td={logs:V(Zu),events:V(Qu),network:V($u),audio:V(ed)};function nd(e){let t=e.map(rd),n=Math.min(Math.max(...t.map(e=>e.label.length),5),32);return t.map(e=>id(e,n)).join(`
34
- `)}function rd(e){return{timestamp:ad(e.ts),label:od(e),summary:sd(e)}}function id(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 ad(e){return e?e.replace(`T`,` `):``}function od(e){let t=e.command??`command`;switch(e.kind){case`request.started`:return`start ${t}`;case`request.finished`:return hd([e.status===`error`?`error`:`ok`,t,pd(_d(e.details?.durationMs))]);case`action.recorded`:return`action ${t}`;default:return hd([e.kind??`event`,e.command])}}function sd(e){let t=cd(e.summary,e);return`${t}${ld(e,t)}`.trim()}function cd(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 ld(e,t){if(e.kind!==`action.recorded`)return``;let n=e.details;if(!n)return``;let r=[ud(n,t),fd(_d(n.textLength))].filter(e=>!!e);return r.length>0?` (${r.join(`, `)})`:``}function ud(e,t){let n=gd(e.ref)??gd(e.selector)??dd(e);if(!(!n||t.includes(n)))return`target=${n}`}function dd(e){let t=_d(e.x),n=_d(e.y);return t===void 0||n===void 0?void 0:`(${t}, ${n})`}function fd(e){return e===void 0?void 0:`text=${e} chars`}function pd(e){return e===void 0?void 0:`${Math.round(e)}ms`}function md(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 hd(e){return e.filter(e=>!!e).join(` `)}function gd(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function _d(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function vd(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?bd(o,`headers`,e.headers):(yd(o,`request headers`,e.requestHeaders),yd(o,`response headers`,e.responseHeaders)),bd(o,`request`,e.requestBody),bd(o,`response`,e.responseBody),o}function yd(e,t,n){!n||Object.keys(n).length===0||e.push(` ${t}: ${JSON.stringify(n)}`)}function bd(e,t,n){n!==void 0&&e.push(` ${t}: ${n}`)}function xd(e,t){return t.map(t=>e[t]!==void 0&&e[t]!==null?`${t}=${e[t]}`:``).filter(Boolean).join(` `)||void 0}function Sd(e){let t=e?.filter(e=>e.length>0)??[];return t.length>0?t.join(`
35
- `):void 0}function Cd(e){return e.filter(e=>!!e).join(`
36
- `)||void 0}const wd=`logs`,Td=`events`,Ed=`network`,Dd=`audio`,Od=[`dump`,`log`],kd=[`probe`],Ad=[`start`,`status`,`stop`],jd=R(wd,`Session app log info, start/stop streaming, diagnostics, and markers`,{action:F(_n),message:j(),restart:P()}),Md=R(Td,`Read the daemon-owned session event timeline as paged JSON-friendly entries`,{limit:N(),cursor:j()}),Nd=R(Ed,`Dump recent HTTP(s) traffic parsed from the session app log`,{action:F(Od),limit:N(),include:F(s)}),Pd=R(Dd,`Measure browser or host-rendered simulator/emulator audio as compact dBFS buckets. Start a probe before requesting its status or stopping it.`,{action:F(kd),probeAction:F(Ad),durationMs:N(`Probe duration in milliseconds.`),bucketMs:N(`Audio level bucket size in milliseconds.`)}),Fd=B({name:`observability`,commands:[z({name:wd,text:{summary:`Manage session app logs`},metadata:jd,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:Bd(e[0]),message:e.slice(1).join(` `)||void 0,restart:t.restart}),daemonWriter:g(wd,e=>Id(e)),cliOutputFormatter:td.logs}),z({name:Td,text:{summary:`Read session event timeline`},metadata:Md,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()?hr(e[0]):void 0,cursor:e[1]}),daemonWriter:e=>_(Td,Ld(e),e),cliOutputFormatter:td.events}),z({name:Ed,text:{summary:`Inspect HTTP(S) traffic from session logs`},metadata:Nd,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:Vd(e[0]),limit:hr(e[1]),include:t.networkInclude??Hd(e[2])}),daemonWriter:e=>_(Ed,Rd(e),{...e,networkInclude:e.include}),cliOutputFormatter:td.network}),z({name:Dd,text:{summary:`Probe audio levels`},metadata:Pd,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:Ud(e[0]),probeAction:Wd(e[1]),durationMs:Gd(e[2]),bucketMs:hr(e[3])}),daemonWriter:e=>_(Dd,zd(e),e),cliOutputFormatter:td.audio})]});function Id(e){return[e.action??`path`,...y(e.message)]}function Ld(e){return e.cursor===void 0?b(e.limit):[e.limit===void 0?``:String(e.limit),e.cursor]}function Rd(e){return[...e.action?[e.action]:[],...b(e.limit)]}function zd(e){return[e.action??`probe`,e.probeAction??`status`,...b(e.durationMs),...b(e.bucketMs)]}function Bd(e){if(e!==void 0)return Yu(_n,e,{message:`logs requires path, start, stop, doctor, mark, or clear`})}function Vd(e){if(e!==void 0){if(e===`dump`||e===`log`)return e;throw new i(`INVALID_ARGS`,`network requires dump or log`)}}function Hd(e){if(e!==void 0)return Yu(s,e,{message:`network include must be summary, headers, body, or all`})}function Ud(e){if(e!==void 0)return Yu(kd,e,{message:`audio requires probe`})}function Wd(e){if(e!==void 0)return Yu(Ad,e,{message:`audio probe requires start, status, or stop`})}function Gd(e){let t=hr(e);return t===void 0?void 0:Math.round(t*1e3)}function Kd(e){let t=e;return{data:t,text:Jd(t)}}const qd={perf:V(Kd)};function Jd(e){return tf(e)??Yd(e)}function Yd(e){let t=u(e.artifact)?e.artifact:void 0;return t?ef(t):Xd(u(e.metrics)?e.metrics:void 0)}function Xd(e){return u(e?.fps)?Qd(e):Zd(e)??`Memory: unavailable - missing memory metric`}function Zd(e){let t=u(e?.memory)?e.memory:void 0;if(!t)return;if(t.available===!1)return`Memory: unavailable - ${mf(t)}`;let n=bf(t);return n?`Performance: ${n}`:`Memory: unavailable - missing memory metric`}function Qd(e){let t=u(e?.fps)?e.fps:void 0;if(!t)return pf(`missing frame metric`);if(t.available===!1)return pf(mf(t));let n=hf(t);return n?$d(t,n):pf(`missing dropped-frame summary`)}function $d(e,t){let n=[`Frame health: ${t}`],r=vf(e);return r.length>0&&n.push(`Worst windows:`,...r),n.join(`
37
- `)}function ef(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?``:` (${wf(r)})`;return n?`Memory artifact (${t}): ${n}${i}`:`Memory artifact (${t}): captured${i}`}function tf(e){return e.kind===`xctrace`?nf(e):sf(e)}function nf(e){let t=typeof e.perf==`string`?e.perf:void 0,n=af(e);if(!t||!n||e.kind!==`xctrace`)return;let r=of(n,typeof e.mode==`string`?e.mode:`capture`,t,e.template),i=rf(e);return i.length>0?`${r}\nTop CPU self time:\n${i.join(`
38
- `)}`:r}function rf(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=df(e.symbol),n=Q(e.selfSamplePercent);if(!t||n===void 0)return[];let r=df(e.binary);return[`- ${xf(n)} ${t}${r?` (${r})`:``}`]}):[]}function af(e){return typeof e.outPath==`string`?e.outPath:typeof e.reportPath==`string`?e.reportPath:void 0}function of(e,t,n,r){let i=[e,`Perf ${t}: ${n}`];return typeof r==`string`&&i.push(`Template: ${r}`),i.join(`
39
- `)}function sf(e){let t=cf(e);if(!t)return;let n=`Perf ${t.action}: ${t.kind} ${t.type}${lf(e)}${uf(e)}${ff(e)}`,r=rf(e);return r.length>0?`${n}\nTop CPU self time:\n${r.join(`
40
- `)}`:n}function cf(e){let t=df(e.action),n=df(e.kind),r=df(e.type);return t&&n&&r?{action:t,kind:n,type:r}:void 0}function lf(e){let t=df(e.state);return t?` state=${t}`:``}function uf(e){let t=df(e.outPath);if(!t)return``;let n=Q(e.sizeBytes);return`\n${t}${n===void 0?``:` (${wf(n)})`}`}function df(e){return typeof e==`string`?e:void 0}function ff(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 ${xf(r)} (${Math.round(i)}/${Math.round(a)} frames)`}function pf(e){return`Frame health: unavailable - ${e}`}function mf(e){return typeof e.reason==`string`&&e.reason.length>0?e.reason:`not available`}function hf(e){let t=Q(e.droppedFramePercent),n=Q(e.droppedFrameCount);if(t!==void 0&&n!==void 0)return[`dropped ${xf(t)}`,gf(n,Q(e.totalFrameCount)),_f(Q(e.sampleWindowMs))].filter(Boolean).join(` `)}function gf(e,t){return t===void 0?`(${Math.round(e)} dropped frames)`:`(${Math.round(e)}/${Math.round(t)} frames)`}function _f(e){return e===void 0?``:`window ${Sf(e)}`}function vf(e){return Array.isArray(e.worstWindows)?e.worstWindows.flatMap(e=>{if(!u(e))return[];let t=yf(e);return t?[t]:[]}):[]}function yf(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 ${Sf(i)}`;return`- +${Sf(t)}-+${Sf(n)}: ${Math.round(r)} missed-deadline frames${a}`}function bf(e){if(e?.available!==!0)return;let t=Q(e.residentMemoryKb)??Q(e.totalPssKb)??Q(e.totalRssKb);return t===void 0?void 0:`memory ${Cf(t)}`}function Q(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function xf(e){return`${Number.isInteger(e)?e:e.toFixed(1)}%`}function Sf(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 Cf(e){let t=e/1024;return`${t>=10?Math.round(t):t.toFixed(1)}MB`}function wf(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 Tf=`perf`,Ef=B({name:`perf`,commands:[z({name:Tf,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(Tf,`Collect frame health, memory diagnostics, and platform profiling artifacts with compact agent-readable summaries.`,{area:A(F(Kt)),subject:F(Xt),action:F(Gt),kind:F(Rt),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 Gc(e){return`source`in e&&e.source===`daemon`}async function Kc(e){let{serializeDeployResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return U(t(e))}async function qc(e){let{serializeInstallFromSourceResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return U(t(e))}function Jc(e){let t=e,n=t.platform??`unknown`;return{data:t,text:`Boot ready: ${t.device??t.id??`unknown`} (${n})`}}function Yc(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 Xc(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=tl(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(Jc),shutdown:V(Yc),devices:V(Lc),capabilities:V(Rc),doctor:({result:e,env:t,progress:n})=>Xc(e,t,n),apps:({input:e,result:t})=>zc({result:t,appsFilter:e.appsFilter}),session:V(Bc),artifacts:V(Wc),open:V(Vc),close:V(Uc),install:V(Kc),reinstall:V(Kc),"install-from-source":V(qc),prepare:H,viewport:H};function Zc(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 Qc(e){let t=e.url?` ${e.url}`:``,n=e.availability?` ${e.availability}`:``;return`${e.kind}: ${e.name}${n}${t}`}function $c(e){let t=e.artifactType?` (${e.artifactType})`:``;return`${e.filename}${t}: ${e.mimeType} ${e.sizeBytes} bytes id=${e.id}`}function el(e){if(e.providerSessionId)return`agent-device artifacts ${e.providerSessionId} --provider ${e.provider} --json`}function tl(e){return Array.isArray(e)?e.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):[]}const nl=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 rl(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 il(e){let{metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i,...a}=e,o=rl({metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i});return o?{...a,runtime:o}:a}const al=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.`)}),ol=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(Ut,`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. iOS simulator direct app launches only; not for URL opens.`),launchArgs:Vr(`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:Ir(`waitMs`),foreground:Ir(`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.`)}),sl=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, or its process stays running, past its 2s check window.`,{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 cl(e){return il(e)}const ll={allowedFlags:[`appsFilter`]},ul={positionalArgs:[`appOrUrl?`,`url?`],allowedFlags:[`activity`,`launchConsole`,`launchArgs`,`testIme`,`saveScript`,`force`,`noRecord`,`relaunch`,`foreground`,`timeoutMs`,`waitMs`,`surface`,...Zi,`launchUrl`]},dl={positionalArgs:[`app?`],allowedFlags:[`saveScript`,`force`,`shutdown`]},fl=(e,t)=>({...v(t),appsFilter:bn(t.appsFilter)}),pl=(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}),ml=(e,t)=>({...v(t),app:e[0],shutdown:t.shutdown,saveScript:t.saveScript,force:t.force}),hl=g(d.apps),gl=g(d.open,Sl),_l=g(d.close,e=>y(e.app)),vl=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:al,run:(e,t)=>e.apps.list(t),cliSchema:ll,cliReader:fl,daemonWriter:hl,cliOutputFormatter:Z.apps}),yl=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 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; in both cases inspect the warning and answer with alert get then alert accept; 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. A recognized prompt still visible after a failed accept 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:ol,run:(e,t)=>e.apps.open(cl(t)),cliSchema:ul,cliReader:pl,daemonWriter:gl,cliOutputFormatter:Z.open}),bl=z({name:`close`,text:{summary:`Close an app or end the session`},metadata:sl,run:(e,t)=>t.app?e.apps.close(t):e.sessions.close(xl(t)),cliSchema:dl,cliReader:ml,daemonWriter:_l,cliOutputFormatter:Z.close});function xl(e){let{app:t,...n}=e;return n}function Sl(e){return e.app?e.url?[e.app,e.url]:[e.app]:[]}const Cl={platform:w(mt),target:w(gt),device:E(`Human-readable device name.`),id:E(`Stable device id.`),kind:w(_t)},wl=[`platform`,`target`,`device`,`id`,`kind`],Tl=C({success:O(),exitCode:D(),stdout:E(),stderr:E(),error:k(`Normalized error detail when shutdown failed.`)},[`success`,`exitCode`,`stdout`,`stderr`]),El={boot:C({...Cl,booted:{type:`boolean`,const:!0}},[...wl,`booted`]),shutdown:C({...Cl,shutdown:Tl},[...wl,`shutdown`])},Dl=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.`,{}),Ol=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.`,{}),kl=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})}),Al=R(`shutdown`,`Shutdown a selected simulator or emulator.`,{}),jl={allowedFlags:[`headless`,`timeoutMs`]},Ml={},Nl={},Pl={},Fl=(e,t)=>v(t),Il=(e,t)=>({...v(t),headless:t.headless,timeoutMs:t.timeoutMs}),Ll=g(d.devices),Rl=g(d.capabilities),zl=g(d.boot),Bl=g(d.shutdown),Vl=[z({name:`devices`,text:{summary:`List available devices and simulators`},metadata:Dl,run:(e,t)=>e.devices.list(t),cliSchema:Ml,cliReader:Fl,daemonWriter:Ll,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:Ol,run:(e,t)=>e.devices.capabilities(t),cliSchema:Nl,cliReader:Fl,daemonWriter:Rl,cliOutputFormatter:Z.capabilities}),z({name:`boot`,text:{summary:`Boot target device/simulator`},metadata:kl,run:(e,t)=>e.devices.boot(t),cliSchema:jl,cliReader:Il,daemonWriter:zl,cliOutputFormatter:Z.boot}),z({name:`shutdown`,text:{summary:`Shutdown target simulator/emulator`},metadata:Al,run:(e,t)=>e.devices.shutdown(t),cliSchema:Pl,cliReader:Fl,daemonWriter:Bl,cliOutputFormatter:Z.shutdown})],Hl={doctor:C({status:w([`pass`,`warn`,`fail`,`info`]),summary:E(),kind:w([`auto`,`react-native`,`expo`,`repack`]),platform:E(),target:w(gt),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`])},Ul=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 Wl(e,t=`--github-actions-artifact`){let n=e.indexOf(`:`);if(n<=0||n===e.length-1)throw new i(`INVALID_ARGS`,`${t} must use owner/repo:artifact, for example thymikee/RNCLI83:6635342232`);let{owner:r,repo:a}=ql(e.slice(0,n),t);return Kl(r,a,e.slice(n+1),`${t} artifact`)}function Gl(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new i(`INVALID_ARGS`,`${t} installSource must be an object.`);let n=e;if(Yl(n.type,`${t} installSource.type`)!==`github-actions-artifact`)throw new i(`INVALID_ARGS`,`${t} installSource.type must be "github-actions-artifact".`);let{owner:r,repo:a}=ql(Yl(n.repo,`${t} installSource.repo`),`${t} installSource.repo`);return Kl(r,a,n.artifact,`${t} installSource.artifact`)}function Kl(e,t,n,r){return typeof n==`number`||Zl(n)?{kind:`github-actions-artifact`,owner:e,repo:t,artifactId:Xl(n,r)}:{kind:`github-actions-artifact`,owner:e,repo:t,artifactName:Yl(n,r)}}function ql(e,t){let n=e.indexOf(`/`);if(n<=0||n===e.length-1||e.indexOf(`/`,n+1)!==-1)throw new i(`INVALID_ARGS`,`${t} must use owner/repo.`);let r={owner:e.slice(0,n).trim(),repo:e.slice(n+1).trim()};if(!r.owner||!r.repo)throw new i(`INVALID_ARGS`,`${t} must use owner/repo.`);return r}function Jl(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Yl(e,t){let n=Jl(e);if(!n)throw new i(`INVALID_ARGS`,`${t} must be a non-empty string.`);return n}function Xl(e,t){let n=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;if(!Number.isInteger(n))throw new i(`INVALID_ARGS`,`${t} must be an integer.`);return n}function Zl(e){return typeof e==`string`&&/^\d+$/.test(e.trim())}const Ql=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.`))}),$l=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.`))}),eu=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.`))}),tu=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()}),nu={usageOverride:`install <path> | install <app> <path>`,listUsageOverride:`install <path>`,positionalArgs:[`appOrPath`,`path?`]},ru={positionalArgs:[`app`,`path`]},iu={positionalArgs:[`app`]},au={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`]},ou=(e,t)=>mu(e,t),su=(e,t)=>hu(e,t),cu=(e,t)=>({...v(t),app:x(e[0],`uninstall requires app`)}),lu=(e,t)=>({...v(t),source:vu(e,t),retainPaths:t.retainPaths,retentionMs:t.retentionMs}),uu=g(d.install,e=>gu(e.app,e.appPath)),du=g(d.reinstall,e=>_u(e.app,e.appPath)),fu=g(d.uninstall,e=>[S(e.app,`missing app`)]),pu=[z({name:`install`,text:{summary:`Install an app binary from a path`},metadata:Ql,run:(e,t)=>e.apps.install(t),cliSchema:nu,cliReader:ou,daemonWriter:uu,cliOutputFormatter:Z.install}),z({name:`reinstall`,text:{summary:`Replace an installed app with a new build`},metadata:$l,run:(e,t)=>e.apps.reinstall(t),cliSchema:ru,cliReader:su,daemonWriter:du,cliOutputFormatter:Z.reinstall}),z({name:`uninstall`,text:{summary:`Remove an installed app`},metadata:eu,run:(e,t)=>e.apps.uninstall(t),cliSchema:iu,cliReader:cu,daemonWriter:fu}),z({name:`install-from-source`,text:{summary:`Install app builds from URLs or CI artifacts`},metadata:tu,run:(e,t)=>e.apps.installFromSource(t),cliSchema:au,cliReader:lu,daemonWriter:e=>_(Xe.installSource,[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),cliOutputFormatter:Z[`install-from-source`]})];function mu(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`)}}function hu(e,t){return{...v(t),app:x(e[0],`reinstall requires app`),appPath:x(e[1],`reinstall requires path`)}}function gu(e,t){let n=S(t,`missing app path`);return typeof e==`string`&&e.length>0?[e,n]:[n]}function _u(e,t){return[S(e,`missing first positional`),S(t,`missing second positional`)]}function vu(e,t){let n=e[0]?.trim();if(e.length>1)throw new i(`INVALID_ARGS`,`install-from-source accepts either one <url> positional or --github-actions-artifact`);let r=t.githubActionsArtifact?Wl(t.githubActionsArtifact):void 0,a=t.installSource;if(+!!n+ +!!r+ +!!a!=1)throw new i(`INVALID_ARGS`,`install-from-source requires exactly one source: <url>, --github-actions-artifact, or config installSource`);if(!n&&t.header&&t.header.length>0)throw new i(`INVALID_ARGS`,`install-from-source --header is only supported for URL sources`);if(r)return r;if(a)return a;if(!yu(n))throw new i(`INVALID_ARGS`,`install-from-source <url> must be an http(s) URL: ${n}`,{hint:`Install a local build with install <app> <path>.`});return{kind:`url`,url:n,headers:bu(t.header)}}function yu(e){let t=URL.parse(e)?.protocol;return t===`http:`||t===`https:`}function bu(e){if(!e||e.length===0)return;let t={};for(let n of e){let e=n.indexOf(`:`);if(e<=0)throw new i(`INVALID_ARGS`,`Invalid --header value "${n}". Expected "name:value".`);let r=n.slice(0,e).trim(),a=n.slice(e+1).trim();if(!r)throw new i(`INVALID_ARGS`,`Invalid --header value "${n}". Header name cannot be empty.`);t[r]=a}return t}const xu=[`ios-runner`],Su={prepare:C({action:T(`ios-runner`),platform:w(mt),deviceId:E(),deviceName:E(),kind:w(_t),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`])},Cu=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(xu)),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}),wu={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`])},Tu=R(`push`,`Deliver push notification payloads to an installed app.`,{app:A(j()),payload:A(I({oneOf:[E(),k()]}))}),Eu=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:Iu(`Structured payload passed to the event, in the shape the app documents for it.`)}),Du={listUsageOverride:`push`,positionalArgs:[`bundleOrPackage`,`payloadOrJson`]},Ou={usageOverride:`trigger-app-event <event> [payloadJson]`,listUsageOverride:`trigger-app-event`,positionalArgs:[`event`,`payloadJson?`]},ku=(e,t)=>({...v(t),app:x(e[0],`push requires bundleOrPackage`),payload:x(e[1],`push requires payloadOrJson`)}),Au=(e,t)=>({...v(t),event:x(e[0],`trigger-app-event requires event`),payload:e[1]?vr(e[1],`trigger-app-event payload`):void 0}),ju=g(d.push,e=>Pu(e)),Mu=g(d.triggerAppEvent,e=>Fu(e)),Nu=[z({name:`push`,text:{summary:`Deliver a push notification payload`},metadata:Tu,run:(e,t)=>e.apps.push(t),cliSchema:Du,cliReader:ku,daemonWriter:ju}),z({name:`trigger-app-event`,text:{summary:`Invoke an app-defined automation event`},metadata:Eu,run:(e,t)=>e.apps.triggerEvent(t),cliSchema:Ou,cliReader:Au,daemonWriter:Mu})];function Pu(e){return[e.app,typeof e.payload==`string`?e.payload:JSON.stringify(e.payload)]}function Fu(e){return[e.event,...e.payload?[JSON.stringify(e.payload)]:[]]}function Iu(e){return Br(e)}const Lu=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 zu(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:Ru(e[0]),path:e[1],force:t.force}),cliOutputFormatter:Z.session});function Ru(e){let t=e??`list`;if(t===`list`||t===`state-dir`||t===`save-script`)return t;throw new i(`INVALID_ARGS`,`session only supports list, state-dir, or save-script`)}function zu(e,t,n){if(e!==`save-script`&&(t!==void 0||n===!0))throw new i(`INVALID_ARGS`,`session ${e} does not accept a path or --force; use session save-script [path] [--force] to publish a recording.`)}const Bu={viewport:C({width:D(),height:D(),message:E()},[`width`,`height`,`message`])},Vu=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),...Ke(e)}),daemonWriter:g(d.viewport,e=>{let{width:t,height:n}=e;return[String(t),String(n)]}),cliOutputFormatter:Z.viewport}),Hu=B({name:`management`,commands:[...Vl,nl,Ul,Cu,vl,Lu,yl,bl,Vu,...pu,...Nu]});function Uu(e){return{data:e.result,text:e.action===`reload`?`Reloaded React Native apps via ${e.result.reloadUrl}`:JSON.stringify(e.result,null,2)}}const Wu={metro:({input:e,result:t})=>Uu({result:t,action:e.action})},Gu=[`auto`,`react-native`,`expo`,`repack`];function Ku(e){if(e!==void 0){if(Gu.includes(e))return e;throw new i(`INVALID_ARGS`,`metro prepare --kind must be auto, react-native, expo, or repack`)}}const qu=`metro`,Ju=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:Fr(j(),{operatorPath:`Configure the remote proxy in the remote-config profile or operator config for the process serving these tools.`}),bearerToken:Fr(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(Yu(t)):await e.metro.reload(Zu(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:[...Zi,...Xi]},cliReader:(e,t)=>{let n=(e[0]??``).toLowerCase();if(n!==`prepare`&&n!==`reload`)throw new i(`INVALID_ARGS`,`metro requires a subcommand: prepare or reload`);if(n===`reload`)return{action:n,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,timeoutMs:t.metroProbeTimeoutMs};if(!t.metroPublicBaseUrl&&!t.metroProxyBaseUrl)throw new i(`INVALID_ARGS`,`metro prepare requires --public-base-url <url> or --proxy-base-url <url>.`);return{action:n,projectRoot:t.metroProjectRoot,kind:Ku(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:Wu.metro})]});function Yu(e){return{projectRoot:e.projectRoot,kind:e.kind,publicBaseUrl:e.publicBaseUrl,proxyBaseUrl:e.proxyBaseUrl,bearerToken:e.bearerToken,bridgeScope:e.bridgeScope??Xu(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 Xu(e){return e.tenant&&e.runId&&e.leaseId?{tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId}:void 0}function Zu(e){return{metroHost:e.metroHost,metroPort:e.metroPort,bundleUrl:e.bundleUrl,timeoutMs:e.timeoutMs}}function Qu(e,t){return e.includes(t)}function $u(e,t,n={}){let r=t===void 0?void 0:n.normalize?.(t)??t;if(r!==void 0&&Qu(e,r))return r;let a=typeof n.message==`function`?n.message(t):n.message;throw new i(`INVALID_ARGS`,a??`Invalid value: ${t}. Use ${e.join(`|`)}.`)}const ed=[`started`,`stopped`,`marked`,`cleared`,`restarted`,`removedRotatedFiles`];function td(e){return{data:e,text:e.path,stderr:Dd([Td(e,[`active`,`state`,`backend`,`sizeBytes`]),Td(e,ed),e.hint,Ed(e.notes)])}}function nd(e){let t=e.events??[];return{data:e,text:t.length>0?od(t):`No session events found.`,stderr:Dd([Td(e,[`path`,`cursor`,`nextCursor`,`limit`])])}}function rd(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(...Sd(e));return{data:e,text:t.join(`
32
+ `),stderr:Dd([Td(e,[`active`,`state`,`backend`,`include`,`scannedLines`,`matchedLines`]),Ed(e.notes)])}}function id(e){return{data:e,text:[`Audio probe: ${String(e.state??`stopped`)} heard=${String(e.heard===!0)}`,vd(`rmsDbfs`,e.rmsDbfs),vd(`peakDbfs`,e.peakDbfs)].filter(e=>!!e).join(`
33
+ `),stderr:Dd([Td(e,[`active`,`backend`,`source`,`durationMs`,`elapsedMs`,`bucketMs`,`sampleCount`,`sourceCount`,`mediaElementCount`]),Ed(e.notes)])}}const ad={logs:V(td),events:V(nd),network:V(rd),audio:V(id)};function od(e){let t=e.map(sd),n=Math.min(Math.max(...t.map(e=>e.label.length),5),32);return t.map(e=>cd(e,n)).join(`
34
+ `)}function sd(e){return{timestamp:ld(e.ts),label:ud(e),summary:dd(e)}}function cd(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 ld(e){return e?e.replace(`T`,` `):``}function ud(e){let t=e.command??`command`;switch(e.kind){case`request.started`:return`start ${t}`;case`request.finished`:return yd([e.status===`error`?`error`:`ok`,t,_d(xd(e.details?.durationMs))]);case`action.recorded`:return`action ${t}`;default:return yd([e.kind??`event`,e.command])}}function dd(e){let t=fd(e.summary,e);return`${t}${pd(e,t)}`.trim()}function fd(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 pd(e,t){if(e.kind!==`action.recorded`)return``;let n=e.details;if(!n)return``;let r=[md(n,t),gd(xd(n.textLength))].filter(e=>!!e);return r.length>0?` (${r.join(`, `)})`:``}function md(e,t){let n=bd(e.ref)??bd(e.selector)??hd(e);if(!(!n||t.includes(n)))return`target=${n}`}function hd(e){let t=xd(e.x),n=xd(e.y);return t===void 0||n===void 0?void 0:`(${t}, ${n})`}function gd(e){return e===void 0?void 0:`text=${e} chars`}function _d(e){return e===void 0?void 0:`${Math.round(e)}ms`}function vd(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 yd(e){return e.filter(e=>!!e).join(` `)}function bd(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function xd(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Sd(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?wd(o,`headers`,e.headers):(Cd(o,`request headers`,e.requestHeaders),Cd(o,`response headers`,e.responseHeaders)),wd(o,`request`,e.requestBody),wd(o,`response`,e.responseBody),o}function Cd(e,t,n){!n||Object.keys(n).length===0||e.push(` ${t}: ${JSON.stringify(n)}`)}function wd(e,t,n){n!==void 0&&e.push(` ${t}: ${n}`)}function Td(e,t){return t.map(t=>e[t]!==void 0&&e[t]!==null?`${t}=${e[t]}`:``).filter(Boolean).join(` `)||void 0}function Ed(e){let t=e?.filter(e=>e.length>0)??[];return t.length>0?t.join(`
35
+ `):void 0}function Dd(e){return e.filter(e=>!!e).join(`
36
+ `)||void 0}const Od=`logs`,kd=`events`,Ad=`network`,jd=`audio`,Md=[`dump`,`log`],Nd=[`probe`],Pd=[`start`,`status`,`stop`],Fd=R(Od,`Session app log info, start/stop streaming, diagnostics, and markers`,{action:F(wn),message:j(),restart:P()}),Id=R(kd,`Read the daemon-owned session event timeline as paged JSON-friendly entries`,{limit:N(),cursor:j()}),Ld=R(Ad,`Dump recent HTTP(s) traffic parsed from the session app log`,{action:F(Md),limit:N(),include:F(s)}),Rd=R(jd,`Measure browser or host-rendered simulator/emulator audio as compact dBFS buckets. Start a probe before requesting its status or stopping it.`,{action:F(Nd),probeAction:F(Pd),durationMs:N(`Probe duration in milliseconds.`),bucketMs:N(`Audio level bucket size in milliseconds.`)}),zd=B({name:`observability`,commands:[z({name:Od,text:{summary:`Manage session app logs`},metadata:Fd,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:Wd(e[0]),message:e.slice(1).join(` `)||void 0,restart:t.restart}),daemonWriter:g(Od,e=>Bd(e)),cliOutputFormatter:ad.logs}),z({name:kd,text:{summary:`Read session event timeline`},metadata:Id,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()?Sr(e[0]):void 0,cursor:e[1]}),daemonWriter:e=>_(kd,Vd(e),e),cliOutputFormatter:ad.events}),z({name:Ad,text:{summary:`Inspect HTTP(S) traffic from session logs`},metadata:Ld,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:Gd(e[0]),limit:Sr(e[1]),include:t.networkInclude??Kd(e[2])}),daemonWriter:e=>_(Ad,Hd(e),{...e,networkInclude:e.include}),cliOutputFormatter:ad.network}),z({name:jd,text:{summary:`Probe audio levels`},metadata:Rd,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:Jd(e[1]),durationMs:Yd(e[2]),bucketMs:Sr(e[3])}),daemonWriter:e=>_(jd,Ud(e),e),cliOutputFormatter:ad.audio})]});function Bd(e){return[e.action??`path`,...y(e.message)]}function Vd(e){return e.cursor===void 0?b(e.limit):[e.limit===void 0?``:String(e.limit),e.cursor]}function Hd(e){return[...e.action?[e.action]:[],...b(e.limit)]}function Ud(e){return[e.action??`probe`,e.probeAction??`status`,...b(e.durationMs),...b(e.bucketMs)]}function Wd(e){if(e!==void 0)return $u(wn,e,{message:`logs requires path, start, stop, doctor, mark, or clear`})}function Gd(e){if(e!==void 0){if(e===`dump`||e===`log`)return e;throw new i(`INVALID_ARGS`,`network requires dump or log`)}}function Kd(e){if(e!==void 0)return $u(s,e,{message:`network include must be summary, headers, body, or all`})}function qd(e){if(e!==void 0)return $u(Nd,e,{message:`audio requires probe`})}function Jd(e){if(e!==void 0)return $u(Pd,e,{message:`audio probe requires start, status, or stop`})}function Yd(e){let t=Sr(e);return t===void 0?void 0:Math.round(t*1e3)}function Xd(e){let t=e;return{data:t,text:Qd(t)}}const Zd={perf:V(Xd)};function Qd(e){return of(e)??$d(e)}function $d(e){let t=u(e.artifact)?e.artifact:void 0;return t?af(t):ef(u(e.metrics)?e.metrics:void 0)}function ef(e){return u(e?.fps)?nf(e):tf(e)??`Memory: unavailable - missing memory metric`}function tf(e){let t=u(e?.memory)?e.memory:void 0;if(!t)return;if(t.available===!1)return`Memory: unavailable - ${vf(t)}`;let n=wf(t);return n?`Performance: ${n}`:`Memory: unavailable - missing memory metric`}function nf(e){let t=u(e?.fps)?e.fps:void 0;if(!t)return _f(`missing frame metric`);if(t.available===!1)return _f(vf(t));let n=yf(t);return n?rf(t,n):_f(`missing dropped-frame summary`)}function rf(e,t){let n=[`Frame health: ${t}`],r=Sf(e);return r.length>0&&n.push(`Worst windows:`,...r),n.join(`
37
+ `)}function af(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?``:` (${Of(r)})`;return n?`Memory artifact (${t}): ${n}${i}`:`Memory artifact (${t}): captured${i}`}function of(e){return e.kind===`xctrace`?sf(e):df(e)}function sf(e){let t=typeof e.perf==`string`?e.perf:void 0,n=lf(e);if(!t||!n||e.kind!==`xctrace`)return;let r=uf(n,typeof e.mode==`string`?e.mode:`capture`,t,e.template),i=cf(e);return i.length>0?`${r}\nTop CPU self time:\n${i.join(`
38
+ `)}`:r}function cf(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=hf(e.symbol),n=Q(e.selfSamplePercent);if(!t||n===void 0)return[];let r=hf(e.binary);return[`- ${Tf(n)} ${t}${r?` (${r})`:``}`]}):[]}function lf(e){return typeof e.outPath==`string`?e.outPath:typeof e.reportPath==`string`?e.reportPath:void 0}function uf(e,t,n,r){let i=[e,`Perf ${t}: ${n}`];return typeof r==`string`&&i.push(`Template: ${r}`),i.join(`
39
+ `)}function df(e){let t=ff(e);if(!t)return;let n=`Perf ${t.action}: ${t.kind} ${t.type}${pf(e)}${mf(e)}${gf(e)}`,r=cf(e);return r.length>0?`${n}\nTop CPU self time:\n${r.join(`
40
+ `)}`:n}function ff(e){let t=hf(e.action),n=hf(e.kind),r=hf(e.type);return t&&n&&r?{action:t,kind:n,type:r}:void 0}function pf(e){let t=hf(e.state);return t?` state=${t}`:``}function mf(e){let t=hf(e.outPath);if(!t)return``;let n=Q(e.sizeBytes);return`\n${t}${n===void 0?``:` (${Of(n)})`}`}function hf(e){return typeof e==`string`?e:void 0}function gf(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 ${Tf(r)} (${Math.round(i)}/${Math.round(a)} frames)`}function _f(e){return`Frame health: unavailable - ${e}`}function vf(e){return typeof e.reason==`string`&&e.reason.length>0?e.reason:`not available`}function yf(e){let t=Q(e.droppedFramePercent),n=Q(e.droppedFrameCount);if(t!==void 0&&n!==void 0)return[`dropped ${Tf(t)}`,bf(n,Q(e.totalFrameCount)),xf(Q(e.sampleWindowMs))].filter(Boolean).join(` `)}function bf(e,t){return t===void 0?`(${Math.round(e)} dropped frames)`:`(${Math.round(e)}/${Math.round(t)} frames)`}function xf(e){return e===void 0?``:`window ${Ef(e)}`}function Sf(e){return Array.isArray(e.worstWindows)?e.worstWindows.flatMap(e=>{if(!u(e))return[];let t=Cf(e);return t?[t]:[]}):[]}function Cf(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 ${Ef(i)}`;return`- +${Ef(t)}-+${Ef(n)}: ${Math.round(r)} missed-deadline frames${a}`}function wf(e){if(e?.available!==!0)return;let t=Q(e.residentMemoryKb)??Q(e.totalPssKb)??Q(e.totalRssKb);return t===void 0?void 0:`memory ${Df(t)}`}function Q(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Tf(e){return`${Number.isInteger(e)?e:e.toFixed(1)}%`}function Ef(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 Df(e){let t=e/1024;return`${t>=10?Math.round(t):t.toFixed(1)}MB`}function Of(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 kf=`perf`,Af=B({name:`perf`,commands:[z({name:kf,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(kf,`Collect frame health, memory diagnostics, and platform profiling artifacts with compact agent-readable summaries.`,{area:A(F($t)),subject:F(rn),action:F(Qt),kind:F(Gt),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
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{A as e,C as t,L as n,O as r,R as i,h as a,j as o,n as s,v 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),...kf(e,{kind:Ff(t.kind),template:t.perfTemplate,out:t.out})}),daemonWriter:g(Tf,e=>Df(e)),cliOutputFormatter:qd.perf})]});function Df(e){let t=e.area;return t===`cpu`?Of([...y(t),...y(e.subject),...y(e.action),...y(e.kind)],e):t===`trace`?Of([...y(t),...y(e.action),...y(e.kind)],e):[...y(t),...y(e.action)]}function Of(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 kf(e,t={}){let n=jf(e[0]);if(n===`cpu`)return{area:n,subject:Nf(e[1]),action:Mf(e[2]),kind:Pf(t.kind),template:t.template,out:t.out};if(n===`trace`)return{area:n,action:Mf(e[1]),kind:Pf(t.kind),template:t.template,out:t.out};let r=Mf(e[1]),i=Pf(t.kind);return Af(n,r,i,t.out),{area:n,action:r,kind:i,out:t.out}}function Af(e,t,n,r){if(e===`frames`){if(n!==void 0)throw new i(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(r!==void 0)throw new i(`INVALID_ARGS`,`--out is only supported with perf memory snapshot, perf cpu profile, or perf trace`)}if(e===`memory`){if(t!==`snapshot`&&n!==void 0)throw new i(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(t!==`snapshot`&&r!==void 0)throw new i(`INVALID_ARGS`,`--out is only supported with perf memory snapshot`)}}function jf(e){let t=e?.toLowerCase();if(Vt(t))throw new i(`INVALID_ARGS`,Ut);if(Bt(t))return t;throw new i(`INVALID_ARGS`,Lt)}function Mf(e){if(e===void 0)return;let t=e.toLowerCase();if(zt(t))return t;throw new i(`INVALID_ARGS`,Yt)}function Nf(e){let t=e?.toLowerCase();if(t!==void 0&&Ht(t))return t;throw new i(`INVALID_ARGS`,Wt)}function Pf(e){if(e===void 0)return;let t=e.toLowerCase();if(qt(t))return t;throw new i(`INVALID_ARGS`,Jt)}function Ff(e){return typeof e==`string`?Pf(e):void 0}const If=`react-native`,Lf=B({name:`react-native`,commands:[z({name:If,text:{summary:`Run React Native automation helpers`},metadata:R(If,`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:Rf(e[0])}),daemonWriter:g(If,e=>[S(e.action,`react-native requires action`)])})]});function Rf(e){if(e===`dismiss-overlay`)return e;throw new i(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}function zf(e){let t=e,n=typeof t.outPath==`string`?t.outPath:``,r=Hf(t);if(r.length<=1)return{data:t,text:Vf(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 Bf={record:V(zf)};function Vf(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 Hf(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 Uf=`record`,Wf=`trace`,Gf=[`start`,`stop`],Kf=R(Uf,`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(Gf)),path:j(),fps:N(),maxSize:Dr(he.migration.record),quality:F(jt),hideTouches:P(),recordingScope:F(Mt)},{parseableOutput:!0}),qf=R(Wf,`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(Gf)),path:j()}),Jf={start:[`recordingScope`,`fps`,`quality`,`hideTouches`],stop:[],"contact-sheet":[`out`]},Yf={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(Jf).flat())],flagsByAction:Jf},Xf={usageOverride:`trace start [path] | trace stop [path]`,listUsageOverride:`trace start [path] | trace stop [path]`,positionalArgs:[`start|stop`,`path?`]},Zf=(e,t)=>({...v(t),action:ip(e[0],Uf),path:e[1],fps:t.fps,quality:t.quality,hideTouches:t.hideTouches,recordingScope:t.recordingScope}),Qf=(e,t)=>({...v(t),action:ip(e[0],Wf),path:e[1]}),$f=g(Uf,e=>rp(e)),ep=e=>(Oe(`record`,e),$f(e)),tp=g(Wf,e=>rp(e)),np=B({name:`recording`,commands:[z({name:Uf,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:Kf,run:(e,t)=>e.recording.record(t),cliSchema:Yf,cliReader:Zf,daemonWriter:ep,cliOutputFormatter:Bf.record}),z({name:Wf,text:{summary:`Start or stop trace capture`},metadata:qf,run:(e,t)=>e.recording.trace(t),cliSchema:Xf,cliReader:Qf,daemonWriter:tp})]});function rp(e){return[e.action,...y(e.path)]}function ip(e,t){if(e===`start`||e===`stop`)return e;throw new i(`INVALID_ARGS`,`${t} requires start|stop`)}const ap=2097152;async function op(e){let t=mn(e.inputPath,{cwd:e.cwd}),n=cp(t,e.inputPath),r=Ve(t,e.replayBackend);return r===`ad`?sp(t,{[t]:n},e.inputPath):sp(t,(await(await import(`./replay-backend-registry.js`).then(e=>e.n)).getReplayBackend(r)).collectSourceFiles({entryPath:t,entrySource:n,env:e.env,readSource:lp}),e.inputPath)}function sp(e,t,n){return up(t,n),{entry:e,files:t}}function cp(e,t){try{return gn.readFileSync(e,`utf8`)}catch(n){throw new i(`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.`},n instanceof Error?n:void 0)}}function lp(e){try{return gn.readFileSync(e,`utf8`)}catch{return}}function up(e,t){let n=Object.values(e).reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0);if(!(n<=2097152))throw new i(`INVALID_ARGS`,`replay script sources for ${t} total ${n} bytes, over the ${ap}-byte limit; split the flow or drop unused runFlow includes.`,{limitBytes:ap,totalBytes:n})}const dp=/[*?[\]{}]/;function fp(e){let t=e.replayBackend===`maestro`?new Set([`.yaml`,`.yml`,`.ad`]):new Set([`.ad`]),n=[],r=[];for(let i of e.inputs){let a=pp(i,e.cwd,t);if(a.source===`file`){n.push(...a.paths);continue}r.push(a.source===`directory`?vp(a.paths):gp(a.paths))}return vp([...n,...r.flat()])}function pp(e,t,n){let r=mn(e,{cwd:t});if(gn.existsSync(r)){let t=gn.statSync(r);return t.isDirectory()?{paths:hp(r,n),source:`directory`}:t.isFile()?(mp(e,r,n),{paths:[r],source:`file`}):{paths:[],source:`file`}}if(!yp(e))throw new i(`INVALID_ARGS`,`test input not found: ${e}`);return{source:`glob`,paths:gn.globSync(hn(e),{cwd:t}).map(e=>f.isAbsolute(e)?e:f.resolve(t,e)).filter(e=>n.has(f.extname(e).toLowerCase())&&bp(e))}}function mp(e,t,n){if(!n.has(f.extname(t).toLowerCase()))throw Qe(t)&&!n.has(`.yaml`)?new i(`INVALID_ARGS`,Ze(`test`,e)):new i(`INVALID_ARGS`,`test does not support this file type: ${e}`)}function hp(e,t){let n=[],r=gn.opendirSync(e);try{let i;for(;(i=r.readSync())!==null;){let r=f.join(e,i.name);i.isDirectory()?n.push(...hp(r,t)):i.isFile()&&t.has(f.extname(i.name).toLowerCase())&&n.push(r)}}finally{r.closeSync()}return n}function gp(e){return e.map(e=>f.normalize(e)).sort((e,t)=>{let n=_p(e)-_p(t);return n===0?e.localeCompare(t):n})}function _p(e){return+(f.extname(e).toLowerCase()===`.ad`)}function vp(e){return[...new Set(e.map(e=>f.normalize(e)))]}function yp(e){return dp.test(e)}function bp(e){try{return gn.statSync(e).isFile()}catch{return!1}}const xp=`replay`,Sp=`test`,Cp=R(xp,`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:Pr(),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(`Maximum wall-clock duration for the replay request.`),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).`)}),wp=R(Sp,`Run one or more replay scripts as a serial test suite`,{paths:A(Pr()),update:P(),backend:j(),maestro:P(),env:Pr(),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).`)}),Tp={replay:C({replayed:D(),healed:D(),session:E(),sessionActive:O(`True iff the session is still active — the script had no terminal close.`),artifactPaths:Er(),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`])},Ep={usageOverride:`replay <path> | replay export <file.ad> [--out <path>]`,usageFlags:[],positionalArgs:[`path`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...Gi,...Hi,`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.`}},Dp={usageOverride:`test <path-or-glob>...`,usageFlags:[],listUsageOverride:`test <path-or-glob>...`,positionalArgs:[`pathOrGlob`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...Gi,...Hi,`failFast`,`timeoutMs`,`retries`,`recordVideo`,`artifactsDir`,`reporter`,`reportJunit`,`shardAll`,`shardSplit`,`testIme`]},Op=B({name:`replay`,commands:[z({name:xp,text:{summary:`Replay a recorded session or Maestro flow`,cliDetail:`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:Cp,run:(e,t)=>e.replay.run(el(t)),cliSchema:Ep,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=jp(e),i=Np(t.env);return _(xp,[n],{...e,replayUpdate:e.update,replayBackend:r,replayEnv:e.env,replayShellEnv:i,replayScriptSource:await op({inputPath:n,cwd:Ap(e,t.cwd),replayBackend:r,env:kp(e,i)}),replayFrom:e.resumeFrom,replayPlanDigest:e.resumePlanDigest,replayKeepSession:e.keepSession,saveScript:e.saveScript})},cliOutputFormatter:H}),z({name:Sp,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.`},metadata:wp,run:(e,t)=>e.replay.test(el(t)),cliSchema:Dp,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=jp(e),i=Ap(e,t.cwd),a=Np(t.env),o=kp(e,a);return _(Sp,n,{...Mp(e),replayUpdate:e.update,replayBackend:r,replayEnv:e.env,replayShellEnv:a,replayScriptSources:await Promise.all(fp({inputs:n,cwd:i,replayBackend:r}).map(async e=>await op({inputPath:e,cwd:i,replayBackend:r,env:o})))})}})]});function kp(e,t){return{...Ft(t),...Pt(Nt(e.env))}}function Ap(e,t){return typeof e.cwd==`string`&&e.cwd.length>0?e.cwd:t}function jp(e){return e.backend??(e.maestro===!0?`maestro`:void 0)}function Mp(e){let t={...e};return delete t.reporter,delete t.reportJunit,t}function Np(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&n.startsWith(`AD_VAR_`)&&(t[n]=r);return t}function Pp(e){return{data:e,text:Lp(e)}}function Fp(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: ${zp(e.visible,e.inputOwner)}`),{data:e,text:t.join(`
55
- `)}}return U(e)}function Ip(e){return e.action===`read`?{data:e,text:e.text}:U(e)}const $=Rs({appstate:V(Pp),back:H,home:H,orientation:H,fold:H,"app-switcher":H,"action-button":H,keyboard:V(Fp),clipboard:V(Ip),"tv-remote":H,telephony:H});function Lp(e){switch(e.platform){case`ios`:case`macos`:return Rp(e);case`android`:case`harmonyos`:{let t=[`Foreground app: ${e.package??`unknown`}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join(`
56
- `)}}}function Rp(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 zp(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 Bp=`back`,Vp=`orientation`,Hp=`fold`,Up=`keyboard`,Wp=`clipboard`,Gp=`tv-remote`,Kp=`telephony`,qp=[`read`,`write`],Jp=[`status`,`dismiss`,`enter`,`return`],Yp={back:C({action:T(`back`),mode:w(it),message:E()},[`action`,`mode`,`message`]),home:C({action:T(`home`),message:E()},[`action`,`message`]),orientation:C({action:T(`orientation`),orientation:w(ue),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(ge),hingeAngleDegrees:D(`Hinge angle read back after the pose settled: from CoreDevice on iOS, from the emulator hinge sensor on Android.`),screen:C({display:E(`CoreDevice name of the panel the device now lights.`),coordinateSpace:T(De),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:w(Te),durationMs:D(),message:E()},[`action`,`button`,`message`]),telephony:{type:`object`,oneOf:[C({action:w(ye),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(a,`The session app XCUIApplication state as a live runner reads it; absent with source session.`),surface:w(It),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`])},Xp={hingeEvent:`simulator HID hinge event`,permissions:`Device Hub and host Accessibility permission are not required.`,unsupportedScope:`UNSUPPORTED_OPERATION and reason unsupported-device-scope`},Zp=`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 ${Xp.hingeEvent}, then reads the hinge angle back from CoreDevice 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; ${Xp.permissions} A simulator scoped to a non-default simulator set is refused with ${Xp.unsupportedScope}; run fold against a simulator in the default set.`,Qp={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)=>({...v(t),...Nf(e,{kind:zf(t.kind),template:t.perfTemplate,out:t.out})}),daemonWriter:g(kf,e=>jf(e)),cliOutputFormatter:Zd.perf})]});function jf(e){let t=e.area;return t===`cpu`?Mf([...y(t),...y(e.subject),...y(e.action),...y(e.kind)],e):t===`trace`?Mf([...y(t),...y(e.action),...y(e.kind)],e):[...y(t),...y(e.action)]}function Mf(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 Nf(e,t={}){let n=Ff(e[0]);if(n===`cpu`)return{area:n,subject:Lf(e[1]),action:If(e[2]),kind:Rf(t.kind),template:t.template,out:t.out};if(n===`trace`)return{area:n,action:If(e[1]),kind:Rf(t.kind),template:t.template,out:t.out};let r=If(e[1]),i=Rf(t.kind);return Pf(n,r,i,t.out),{area:n,action:r,kind:i,out:t.out}}function Pf(e,t,n,r){if(e===`frames`){if(n!==void 0)throw new i(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(r!==void 0)throw new i(`INVALID_ARGS`,`--out is only supported with perf memory snapshot, perf cpu profile, or perf trace`)}if(e===`memory`){if(t!==`snapshot`&&n!==void 0)throw new i(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(t!==`snapshot`&&r!==void 0)throw new i(`INVALID_ARGS`,`--out is only supported with perf memory snapshot`)}}function Ff(e){let t=e?.toLowerCase();if(Jt(t))throw new i(`INVALID_ARGS`,Xt);if(qt(t))return t;throw new i(`INVALID_ARGS`,Wt)}function If(e){if(e===void 0)return;let t=e.toLowerCase();if(Kt(t))return t;throw new i(`INVALID_ARGS`,nn)}function Lf(e){let t=e?.toLowerCase();if(t!==void 0&&Yt(t))return t;throw new i(`INVALID_ARGS`,Zt)}function Rf(e){if(e===void 0)return;let t=e.toLowerCase();if(en(t))return t;throw new i(`INVALID_ARGS`,tn)}function zf(e){return typeof e==`string`?Rf(e):void 0}const Bf=`react-native`,Vf=B({name:`react-native`,commands:[z({name:Bf,text:{summary:`Run React Native automation helpers`},metadata:R(Bf,`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:Hf(e[0])}),daemonWriter:g(Bf,e=>[S(e.action,`react-native requires action`)])})]});function Hf(e){if(e===`dismiss-overlay`)return e;throw new i(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}function Uf(e){let t=e,n=typeof t.outPath==`string`?t.outPath:``,r=Kf(t);if(r.length<=1)return{data:t,text:Gf(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 Wf={record:V(Uf)};function Gf(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 Kf(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`,Jf=`trace`,Yf=[`start`,`stop`],Xf=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(Yf)),path:j(),fps:N(),maxSize:Pr(Se.migration.record),quality:F(Rt),hideTouches:P(),recordingScope:F(zt)},{parseableOutput:!0}),Zf=R(Jf,`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(Yf)),path:j()}),Qf={start:[`recordingScope`,`fps`,`quality`,`hideTouches`],stop:[],"contact-sheet":[`out`]},$f={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(Qf).flat())],flagsByAction:Qf},ep={usageOverride:`trace start [path] | trace stop [path]`,listUsageOverride:`trace start [path] | trace stop [path]`,positionalArgs:[`start|stop`,`path?`]},tp=(e,t)=>({...v(t),action:cp(e[0],qf),path:e[1],fps:t.fps,quality:t.quality,hideTouches:t.hideTouches,recordingScope:t.recordingScope}),np=(e,t)=>({...v(t),action:cp(e[0],Jf),path:e[1]}),rp=g(qf,e=>sp(e)),ip=e=>(ce(`record`,e),rp(e)),ap=g(Jf,e=>sp(e)),op=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:Xf,run:(e,t)=>e.recording.record(t),cliSchema:$f,cliReader:tp,daemonWriter:ip,cliOutputFormatter:Wf.record}),z({name:Jf,text:{summary:`Start or stop trace capture`},metadata:Zf,run:(e,t)=>e.recording.trace(t),cliSchema:ep,cliReader:np,daemonWriter:ap})]});function sp(e){return[e.action,...y(e.path)]}function cp(e,t){if(e===`start`||e===`stop`)return e;throw new i(`INVALID_ARGS`,`${t} requires start|stop`)}const lp=2097152;async function up(e){let t=xn(e.inputPath,{cwd:e.cwd}),n=fp(t,e.inputPath),r=qe(t,e.replayBackend);return r===`ad`?dp(t,{[t]:n},e.inputPath):dp(t,(await(await import(`./replay-backend-registry.js`).then(e=>e.n)).getReplayBackend(r)).collectSourceFiles({entryPath:t,entrySource:n,env:e.env,readSource:pp}),e.inputPath)}function dp(e,t,n){return mp(t,n),{entry:e,files:t}}function fp(e,t){try{return Cn.readFileSync(e,`utf8`)}catch(n){throw new i(`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.`},n instanceof Error?n:void 0)}}function pp(e){try{return Cn.readFileSync(e,`utf8`)}catch{return}}function mp(e,t){let n=Object.values(e).reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0);if(!(n<=2097152))throw new i(`INVALID_ARGS`,`replay script sources for ${t} total ${n} bytes, over the ${lp}-byte limit; split the flow or drop unused runFlow includes.`,{limitBytes:lp,totalBytes:n})}const hp=/[*?[\]{}]/;function gp(e){let t=e.replayBackend===`maestro`?new Set([`.yaml`,`.yml`,`.ad`]):new Set([`.ad`]),n=[],r=[];for(let i of e.inputs){let a=_p(i,e.cwd,t);if(a.source===`file`){n.push(...a.paths);continue}r.push(a.source===`directory`?Sp(a.paths):bp(a.paths))}return Sp([...n,...r.flat()])}function _p(e,t,n){let r=xn(e,{cwd:t});if(Cn.existsSync(r)){let t=Cn.statSync(r);return t.isDirectory()?{paths:yp(r,n),source:`directory`}:t.isFile()?(vp(e,r,n),{paths:[r],source:`file`}):{paths:[],source:`file`}}if(!Cp(e))throw new i(`INVALID_ARGS`,`test input not found: ${e}`);return{source:`glob`,paths:Cn.globSync(Sn(e),{cwd:t}).map(e=>f.isAbsolute(e)?e:f.resolve(t,e)).filter(e=>n.has(f.extname(e).toLowerCase())&&wp(e))}}function vp(e,t,n){if(!n.has(f.extname(t).toLowerCase()))throw rt(t)&&!n.has(`.yaml`)?new i(`INVALID_ARGS`,nt(`test`,e)):new i(`INVALID_ARGS`,`test does not support this file type: ${e}`)}function yp(e,t){let n=[],r=Cn.opendirSync(e);try{let i;for(;(i=r.readSync())!==null;){let r=f.join(e,i.name);i.isDirectory()?n.push(...yp(r,t)):i.isFile()&&t.has(f.extname(i.name).toLowerCase())&&n.push(r)}}finally{r.closeSync()}return n}function bp(e){return e.map(e=>f.normalize(e)).sort((e,t)=>{let n=xp(e)-xp(t);return n===0?e.localeCompare(t):n})}function xp(e){return+(f.extname(e).toLowerCase()===`.ad`)}function Sp(e){return[...new Set(e.map(e=>f.normalize(e)))]}function Cp(e){return hp.test(e)}function wp(e){try{return Cn.statSync(e).isFile()}catch{return!1}}const Tp=`replay`,Ep=`test`,Dp=R(Tp,`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:Vr(),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(`Maximum wall-clock duration for the replay request.`),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).`)}),Op=R(Ep,`Run one or more replay scripts as a serial test suite`,{paths:A(Vr()),update:P(),backend:j(),maestro:P(),env:Vr(),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).`)}),kp={replay:C({replayed:D(),healed:D(),session:E(),sessionActive:O(`True iff the session is still active — the script had no terminal close.`),artifactPaths:Nr(),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`])},Ap={usageOverride:`replay <path> | replay export <file.ad> [--out <path>]`,usageFlags:[],positionalArgs:[`path`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...ea,...Zi,`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.`}},jp={usageOverride:`test <path-or-glob>...`,usageFlags:[],listUsageOverride:`test <path-or-glob>...`,positionalArgs:[`pathOrGlob`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...ea,...Zi,`failFast`,`timeoutMs`,`retries`,`recordVideo`,`artifactsDir`,`reporter`,`reportJunit`,`shardAll`,`shardSplit`,`testIme`]},Mp=B({name:`replay`,commands:[z({name:Tp,text:{summary:`Replay a recorded session or Maestro flow`,cliDetail:`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:Dp,run:(e,t)=>e.replay.run(il(t)),cliSchema:Ap,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=Fp(e),i=Lp(t.env);return _(Tp,[n],{...e,replayUpdate:e.update,replayBackend:r,replayEnv:e.env,replayShellEnv:i,replayScriptSource:await up({inputPath:n,cwd:Pp(e,t.cwd),replayBackend:r,env:Np(e,i)}),replayFrom:e.resumeFrom,replayPlanDigest:e.resumePlanDigest,replayKeepSession:e.keepSession,saveScript:e.saveScript})},cliOutputFormatter:H}),z({name:Ep,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.`},metadata:Op,run:(e,t)=>e.replay.test(il(t)),cliSchema:jp,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=Fp(e),i=Pp(e,t.cwd),a=Lp(t.env),o=Np(e,a);return _(Ep,n,{...Ip(e),replayUpdate:e.update,replayBackend:r,replayEnv:e.env,replayShellEnv:a,replayScriptSources:await Promise.all(gp({inputs:n,cwd:i,replayBackend:r}).map(async e=>await up({inputPath:e,cwd:i,replayBackend:r,env:o})))})}})]});function Np(e,t){return{...Ht(t),...Vt(Bt(e.env))}}function Pp(e,t){return typeof e.cwd==`string`&&e.cwd.length>0?e.cwd:t}function Fp(e){return e.backend??(e.maestro===!0?`maestro`:void 0)}function Ip(e){let t={...e};return delete t.reporter,delete t.reportJunit,t}function Lp(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&n.startsWith(`AD_VAR_`)&&(t[n]=r);return t}function Rp(e){return{data:e,text:Vp(e)}}function zp(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: ${Up(e.visible,e.inputOwner)}`),{data:e,text:t.join(`
55
+ `)}}return U(e)}function Bp(e){return e.action===`read`?{data:e,text:e.text}:U(e)}const $=qs({appstate:V(Rp),back:H,home:H,orientation:H,fold:H,"app-switcher":H,"action-button":H,keyboard:V(zp),clipboard:V(Bp),"tv-remote":H,"hardware-button":H,telephony:H});function Vp(e){switch(e.platform){case`ios`:case`macos`:return Hp(e);case`android`:case`harmonyos`:{let t=[`Foreground app: ${e.package??`unknown`}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join(`
56
+ `)}}}function Hp(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 Up(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 Wp=`back`,Gp=`orientation`,Kp=`fold`,qp=`hardware-button`,Jp=`keyboard`,Yp=`clipboard`,Xp=`tv-remote`,Zp=`telephony`,Qp=[`read`,`write`],$p=[`status`,`dismiss`,`enter`,`return`],em={description:`TV remote button. Android TV also accepts android-keycode:<n> with n from 1 to 2147483647.`,oneOf:[w(De),{type:`string`,pattern:Me.source}]},tm={back:C({action:T(`back`),mode:w(lt),message:E()},[`action`,`mode`,`message`]),home:C({action:T(`home`),message:E()},[`action`,`message`]),orientation:C({action:T(`orientation`),orientation:w(ne),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(Ie),hingeAngleDegrees:D(`Hinge angle read back after the pose settled: from CoreDevice on iOS, from the emulator hinge sensor on Android.`),screen:C({display:E(`CoreDevice name of the panel the device now lights.`),coordinateSpace:T(Fe),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:em,durationMs:D(),message:E()},[`action`,`button`,`message`]),"hardware-button":C({action:T(`hardware-button`),button:w(le),message:E()},[`action`,`button`,`message`]),telephony:{type:`object`,oneOf:[C({action:w(be),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(a,`The session app XCUIApplication state as a live runner reads it; absent with source session.`),surface:w(Ut),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`])},nm={hingeEvent:`simulator HID hinge event`,permissions:`Device Hub and host Accessibility permission are not required.`,unsupportedScope:`UNSUPPORTED_OPERATION and reason unsupported-device-scope`},rm=`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 ${nm.hingeEvent}, then reads the hinge angle back from CoreDevice 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; ${nm.permissions} A simulator scoped to a non-default simulator set is refused with ${nm.unsupportedScope}; run fold against a simulator in the default set.`,im={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
 
@@ -65,10 +65,10 @@ Screens are handled for you:
65
65
 
66
66
  Changing the pose:
67
67
  agent-device fold closed | half-open | open
68
- fold sends a private HID hinge event inside the selected simulator and then reads the hinge angle back from CoreDevice until it agrees: closed is 0 degrees, open is 180, and half-open is any angle between them (requested at 130 degrees). An angle in that interval only proves the category, so half-open is reported once two consecutive readings both fall inside it and agree within 0.5 degrees. The response reports the verified pose, the hinge angle, and the panel the device now lights with its native panel point size, marked coordinateSpace "native-panel". That point size is the panel's own geometry, not the next snapshot's viewport, so it cannot place a tap: the active app window can differ (a 669x951 inner panel hosts a 951x669 window). A hinge whose last reading is some other pose fails with COMMAND_FAILED and reason fold-pose-unverified, naming the angle CoreDevice still reports; a hinge seen half-open but never at rest fails with reason fold-pose-unsettled, naming the observed and previous angles; a first hinge-angle read that returns no sample (for example a devicectl without device motion) fails with reason fold-pose-dispatched-unverified, meaning the pose was sent but cannot be confirmed; hingeReadFailure holds the read's own failure details, and screen holds the lit panel's size when panel power decides one panel, so take a screenshot or snapshot to check. A single-panel simulator fails with UNSUPPORTED_OPERATION. A simulator scoped to a non-default set with --ios-simulator-device-set is refused before any hinge is touched, with ${Xp.unsupportedScope}: the HID send honors the set, but CoreDevice's display inventory and hinge-angle readback resolve a scoped simulator as not found, so the pose could not be verified. Run fold without --ios-simulator-device-set (in the default set).
68
+ fold sends a private HID hinge event inside the selected simulator and then reads the hinge angle back from CoreDevice until it agrees: closed is 0 degrees, open is 180, and half-open is any angle between them (requested at 130 degrees). An angle in that interval only proves the category, so half-open is reported once two consecutive readings both fall inside it and agree within 0.5 degrees. The response reports the verified pose, the hinge angle, and the panel the device now lights with its native panel point size, marked coordinateSpace "native-panel". That point size is the panel's own geometry, not the next snapshot's viewport, so it cannot place a tap: the active app window can differ (a 669x951 inner panel hosts a 951x669 window). A hinge whose last reading is some other pose fails with COMMAND_FAILED and reason fold-pose-unverified, naming the angle CoreDevice still reports; a hinge seen half-open but never at rest fails with reason fold-pose-unsettled, naming the observed and previous angles; a first hinge-angle read that returns no sample (for example a devicectl without device motion) fails with reason fold-pose-dispatched-unverified, meaning the pose was sent but cannot be confirmed; hingeReadFailure holds the read's own failure details, and screen holds the lit panel's size when panel power decides one panel, so take a screenshot or snapshot to check. A single-panel simulator fails with UNSUPPORTED_OPERATION. A simulator scoped to a non-default set with --ios-simulator-device-set is refused before any hinge is touched, with ${nm.unsupportedScope}: the HID send honors the set, but CoreDevice's display inventory and hinge-angle readback resolve a scoped simulator as not found, so the pose could not be verified. Run fold without --ios-simulator-device-set (in the default set).
69
69
  Expect a fold to take 10-16 seconds: each hinge read is a five-second devicectl stream, and half-open waits for the hinge to stop moving. 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). ${Xp.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. 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). ${nm.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. 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.`},$p=R(Bp,`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.`,{mode:F(it),...as(Bp)}),em=R(Vp,`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.`,{orientation:A(F(ue))}),tm={pose:F(ge,`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:Ae},angle:{type:`number`,minimum:0,maximum:180}}}})},nm=R(Hp,Zp,tm,{readInput:e=>{let{pose:t,keyframes:n,...r}=Hr(e,tm);return{...r,...ne({pose:t,keyframes:n})}}}),rm={...nm,inputSchema:{...nm.inputSchema,oneOf:[{required:[`pose`],not:{required:[`keyframes`]}},{required:[`keyframes`],not:{required:[`pose`]}}]}},im=R(Up,`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(Jp)}),am=R(Wp,`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(qp)),text:j()},{parseableOutput:!0}),om=R(Gp,`Press or long-press a TV remote or D-pad button on Android TV, tvOS, or Vega OS. Choose the button and optional hold duration through the input fields. The aliases ok, center, and enter all map to select.`,{button:A(F(Te)),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 (${we(`android`)}).`,{min:0})}),sm={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.`)},cm=R(Kp,`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.`,sm,{readInput:e=>{let{action:t,number:n,text:r,...i}=Hr(e,sm);return{...i,...fe({action:t,number:n,text:r})}}}),lm={...cm,inputSchema:{...cm.inputSchema,oneOf:[{properties:{action:T(`sms`)},required:[`text`]},{properties:{action:w(ye)},not:{required:[`text`]}}]}},um={usageOverride:`back [--in-app|--system] [--settle]`,usageFlags:[],allowedFlags:[`backMode`,...os(Bp)]},dm={usageOverride:`orientation <${ue.join(`|`)}>`,positionalArgs:[`orientation`]},fm={usageOverride:`fold [${le}]`,positionalArgs:[`pose?`],allowedFlags:Ri},pm={usageOverride:`keyboard [status|get|dismiss|enter|return]`,positionalArgs:[`action?`]},mm={usageOverride:`clipboard read | clipboard write <text>`,listUsageOverride:`clipboard read | clipboard write <text>`,positionalArgs:[`read|write`,`text?`],allowsExtraPositionals:!0},hm={usageOverride:`tv-remote [press|longpress] ${be}`,listUsageOverride:`tv-remote press|longpress <button> [--duration-ms <ms>]`,positionalArgs:[`press|longpress?`,`button`],allowedFlags:[`durationMs`]},gm={usageOverride:Ee,listUsageOverride:`telephony call|accept|cancel|sms <number> [text]`,positionalArgs:[`call|accept|cancel|sms`,`number`,`text?`],allowsExtraPositionals:!0},_m=(e,t)=>({...v(t),mode:t.backMode}),vm=(e,t)=>({...v(t),orientation:ve(e[0])}),ym=(e,t)=>({...v(t),...ne({pose:e[0],keyframes:t.keyframes===void 0?void 0:te(t.keyframes)})}),bm=(e,t)=>({...v(t),...Hm(e)}),xm=(e,t)=>({...v(t),...Um(e)}),Sm=(e,t)=>({...v(t),...Wm(e,t.durationMs)}),Cm=(e,t)=>({...v(t),...me(e)}),wm=e=>_(Bp,[],{...e,backMode:Bm(e.mode)}),Tm=g(Vp,e=>[S(e.orientation,`orientation requires orientation`)]),Em=e=>{let t=ne(e);return _(Hp,t.pose?[t.pose]:[],{...e,keyframes:t.keyframes?JSON.stringify(t.keyframes):void 0})},Dm=g(Up,e=>y(e.action)),Om=g(Wp,e=>Vm(e)),km=g(Gp,e=>[S(e.button,`tv-remote requires button`)]),Am=g(Kp,e=>xe(fe(e))),jm=ri({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}),Mm=z({name:Bp,text:{summary:`Navigate back in the app or system`},metadata:$p,run:(e,t)=>e.command.back(t),cliSchema:um,cliReader:_m,daemonWriter:wm,cliOutputFormatter:$.back}),Nm=ri({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}),Pm=z({name:Vp,text:{summary:`Set device orientation`},metadata:em,run:(e,t)=>e.command.orientation(t),cliSchema:dm,cliReader:vm,daemonWriter:Tm,cliOutputFormatter:$.orientation}),Fm=z({name:Hp,text:{summary:`Fold or unfold a foldable iPhone simulator or Android emulator`,cliDetail:`iPhone Duo simulators and foldable Android emulators. iOS sends a ${Xp.hingeEvent} and confirms the hinge angle through CoreDevice; Android sets the emulator console posture and confirms the device state. Refs and coordinates do not survive a pose change.`},metadata:rm,run:(e,t)=>e.command.fold(t),cliSchema:fm,cliReader:ym,daemonWriter:Em,cliOutputFormatter:$.fold}),Im=ri({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`]}),Lm=z({name:Up,text:{summary:`Inspect, press, or dismiss the device keyboard`},metadata:im,run:(e,t)=>e.command.keyboard(t),cliSchema:pm,cliReader:bm,daemonWriter:Dm,cliOutputFormatter:$.keyboard}),Rm=z({name:Wp,text:{summary:`Read or write device clipboard text`},metadata:am,run:(e,t)=>e.command.clipboard(t),cliSchema:mm,cliReader:xm,daemonWriter:Om,cliOutputFormatter:$.clipboard}),zm=B({name:`system`,commands:[jm,Mm,Nm,Pm,Fm,Im,ri({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`]}),Lm,Rm,z({name:Gp,text:{summary:`Press a TV remote/D-pad button`,cliDetail:`longpress holds for 500ms by default; --duration-ms overrides the preset.`},metadata:om,run:(e,t)=>e.command.tvRemote(t),cliSchema:hm,cliReader:Sm,daemonWriter:km,cliOutputFormatter:$[`tv-remote`]}),z({name:Kp,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:lm,run:(e,t)=>e.command.telephony(t),cliSchema:gm,cliReader:Cm,daemonWriter:Am,cliOutputFormatter:$.telephony})]});function Bm(e){return e===`in-app`||e===`system`?e:void 0}function Vm(e){return e.action===`read`?[`read`]:[`write`,e.text]}function Hm(e){if(e.length>1)throw new i(`INVALID_ARGS`,`keyboard accepts at most one action argument.`);return m({action:Gm(e[0])})}function Um(e){let t=e[0]?.toLowerCase();if(t!==`read`&&t!==`write`)throw new i(`INVALID_ARGS`,`clipboard requires a subcommand: read or write.`);if(t===`read`){if(e.length!==1)throw new i(`INVALID_ARGS`,`clipboard read does not accept additional arguments.`);return{action:t}}if(e.length<2)throw new i(`INVALID_ARGS`,`clipboard write requires text.`);return{action:t,text:e.slice(1).join(` `)}}function Wm(e,t){let n=e[0]?.toLowerCase(),r=n===`press`||n===`longpress`?e.slice(1):e;if(r.length!==1)throw new i(`INVALID_ARGS`,`tv-remote requires exactly one button: ${Te.join(`, `)}.`);let a=t??(n===`longpress`?500:void 0);return m({button:Ce(r[0]),durationMs:a})}function Gm(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 i(`INVALID_ARGS`,`keyboard action must be status, get, dismiss, enter, or return.`)}const Km=[vc,Ru,Xo,zm,Lf,Op,Fd,Ef,ts,np,Wu,ji];function qm(){return Km.flatMap(e=>[...e.metadata])}function Jm(){return Km.flatMap(e=>[...e.definitions])}function Ym(){return $m(`cliSchemas`)}function Xm(){return $m(`cliReaders`)}function Zm(){return $m(`daemonWriters`)}function Qm(){return $m(`cliOutputFormatters`)}function $m(e){let t={};for(let n of Km){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 eh=qm(),th=new Map(eh.map(e=>[e.name,e]));function nh(){return[...eh]}function rh(){return vt().map(e=>{let t=ah(e);if(!t)throw Error(`Missing command metadata for MCP-exposed command: ${e}`);return t})}function ih(e){return th.has(e)}function ah(e){return th.get(e)}export{Vi as A,E as B,ss as C,Ki as D,Xi as E,T as F,Ln as G,_r as H,w as I,bn as J,wn as K,k as L,ci as M,si as N,qi as O,O as P,D as R,cc as S,xo as T,Hn as U,gr as V,Un as W,xn as Y,vu as _,Qm as a,Sl as b,Zm as c,Yp as d,Qp as f,bu as g,Iu as h,rh as i,xi as j,Ji as k,Jm as l,Hu as m,ih as n,Xm as o,Tp as p,Tn as q,nh as r,Ym as s,ah as t,qm as u,Vl as v,Bo as w,_c as x,Rl as y,C 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.`},am=R(Wp,`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.`,{mode:F(lt),...ms(Wp)}),om=R(Gp,`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.`,{orientation:A(F(ne))}),sm={pose:F(Ie,`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:ue},angle:{type:`number`,minimum:0,maximum:180}}}})},cm=R(Kp,rm,sm,{readInput:e=>{let{pose:t,keyframes:n,...r}=Zr(e,sm);return{...r,...oe({pose:t,keyframes:n})}}}),lm={...cm,inputSchema:{...cm.inputSchema,oneOf:[{required:[`pose`],not:{required:[`keyframes`]}},{required:[`keyframes`],not:{required:[`pose`]}}]}},um=R(Jp,`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($p)}),dm=R(Yp,`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(Qp)),text:j()},{parseableOutput:!0}),fm=R(Xp,`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(Hr(em,(e,t)=>he(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 (${Ne(`android`)}).`,{min:0})}),pm=R(qp,`Press a phone hardware button once: volume-up, volume-down, or power. 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, and whether the HUD shows, is device behavior this command does not claim. Power toggles the Android screen; after a press that turns it off, later commands may hit a locked screen. Android (ADB-backed and Appium) presses all three on phones and tablets; a physical iPhone or iPad presses volume only through the local runner or Appium, never power. iOS Simulators, Android TV and tvOS targets refuse: on TV targets use tv-remote.`,{button:A(F(le,`One press each. volume-up and volume-down move the system volume stream the OS selects; power toggles the screen on Android and is refused on every Apple leaf.`))}),mm={action:A(F(ve,`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.`)},hm=R(Zp,`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.`,mm,{readInput:e=>{let{action:t,number:n,text:r,...i}=Zr(e,mm);return{...i,...Ee({action:t,number:n,text:r})}}}),gm={...hm,inputSchema:{...hm.inputSchema,oneOf:[{properties:{action:T(`sms`)},required:[`text`]},{properties:{action:w(be)},not:{required:[`text`]}}]}},_m={usageOverride:`back [--in-app|--system] [--settle]`,usageFlags:[],allowedFlags:[`backMode`,...hs(Wp)]},vm={usageOverride:`orientation <${ne.join(`|`)}>`,positionalArgs:[`orientation`]},ym={usageOverride:`fold [${ge}]`,positionalArgs:[`pose?`],allowedFlags:qi},bm={usageOverride:`keyboard [status|get|dismiss|enter|return]`,positionalArgs:[`action?`]},xm={usageOverride:`clipboard read | clipboard write <text>`,listUsageOverride:`clipboard read | clipboard write <text>`,positionalArgs:[`read|write`,`text?`],allowsExtraPositionals:!0},Sm={usageOverride:`tv-remote [press|longpress] ${Ae}`,listUsageOverride:`tv-remote press|longpress <button> [--duration-ms <ms>]`,positionalArgs:[`press|longpress?`,`button`],allowedFlags:[`durationMs`]},Cm={usageOverride:`hardware-button ${Pe}`,positionalArgs:[`button`]},wm={usageOverride:ke,listUsageOverride:`telephony call|accept|cancel|sms <number> [text]`,positionalArgs:[`call|accept|cancel|sms`,`number`,`text?`],allowsExtraPositionals:!0},Tm=(e,t)=>({...v(t),mode:t.backMode}),Em=(e,t)=>({...v(t),orientation:ae(e[0])}),Dm=(e,t)=>({...v(t),...oe({pose:e[0],keyframes:t.keyframes===void 0?void 0:se(t.keyframes)})}),Om=(e,t)=>({...v(t),...Qm(e)}),km=(e,t)=>({...v(t),...$m(e)}),Am=(e,t)=>({...v(t),...eh(e,t.durationMs)}),jm=(e,t)=>({...v(t),...th(e)}),Mm=(e,t)=>({...v(t),...Ce(e)}),Nm=e=>_(Wp,[],{...e,backMode:Xm(e.mode)}),Pm=g(Gp,e=>[S(e.orientation,`orientation requires orientation`)]),Fm=e=>{let t=oe(e);return _(Kp,t.pose?[t.pose]:[],{...e,keyframes:t.keyframes?JSON.stringify(t.keyframes):void 0})},Im=g(Jp,e=>y(e.action)),Lm=g(Yp,e=>Zm(e)),Rm=g(Xp,e=>[S(e.button,`tv-remote requires button`)]),zm=g(qp,e=>[S(e.button,`hardware-button requires button`)]),Bm=g(Zp,e=>xe(Ee(e))),Vm=fi({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}),Hm=z({name:Wp,text:{summary:`Navigate back in the app or system`},metadata:am,run:(e,t)=>e.command.back(t),cliSchema:_m,cliReader:Tm,daemonWriter:Nm,cliOutputFormatter:$.back}),Um=fi({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}),Wm=z({name:Gp,text:{summary:`Set device orientation`},metadata:om,run:(e,t)=>e.command.orientation(t),cliSchema:vm,cliReader:Em,daemonWriter:Pm,cliOutputFormatter:$.orientation}),Gm=z({name:Kp,text:{summary:`Fold or unfold a foldable iPhone simulator or Android emulator`,cliDetail:`iPhone Duo simulators and foldable Android emulators. iOS sends a ${nm.hingeEvent} and confirms the hinge angle through CoreDevice; Android sets the emulator console posture and confirms the device state. Refs and coordinates do not survive a pose change.`},metadata:lm,run:(e,t)=>e.command.fold(t),cliSchema:ym,cliReader:Dm,daemonWriter:Fm,cliOutputFormatter:$.fold}),Km=fi({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:Jp,text:{summary:`Inspect, press, or dismiss the device keyboard`},metadata:um,run:(e,t)=>e.command.keyboard(t),cliSchema:bm,cliReader:Om,daemonWriter:Im,cliOutputFormatter:$.keyboard}),Jm=z({name:Yp,text:{summary:`Read or write device clipboard text`},metadata:dm,run:(e,t)=>e.command.clipboard(t),cliSchema:xm,cliReader:km,daemonWriter:Lm,cliOutputFormatter:$.clipboard}),Ym=B({name:`system`,commands:[Vm,Hm,Um,Wm,Gm,Km,fi({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,Jm,z({name:Xp,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:fm,run:(e,t)=>e.command.tvRemote(t),cliSchema:Sm,cliReader:Am,daemonWriter:Rm,cliOutputFormatter:$[`tv-remote`]}),z({name:qp,text:{summary:`Press a phone hardware button once`,cliDetail:`Single press; no hold. Android presses volume-up, volume-down, and power on phones and tablets. A physical iPhone or iPad presses volume only; power is never supported on Apple targets. iOS Simulators, Android TV, and tvOS refuse — use tv-remote on TV targets.`},metadata:pm,run:(e,t)=>e.command.hardwareButton(t),cliSchema:Cm,cliReader:jm,daemonWriter:zm,cliOutputFormatter:$[`hardware-button`]}),z({name:Zp,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:gm,run:(e,t)=>e.command.telephony(t),cliSchema:wm,cliReader:Mm,daemonWriter:Bm,cliOutputFormatter:$.telephony})]});function Xm(e){return e===`in-app`||e===`system`?e:void 0}function Zm(e){return e.action===`read`?[`read`]:[`write`,e.text]}function Qm(e){if(e.length>1)throw new i(`INVALID_ARGS`,`keyboard accepts at most one action argument.`);return m({action:nh(e[0])})}function $m(e){let t=e[0]?.toLowerCase();if(t!==`read`&&t!==`write`)throw new i(`INVALID_ARGS`,`clipboard requires a subcommand: read or write.`);if(t===`read`){if(e.length!==1)throw new i(`INVALID_ARGS`,`clipboard read does not accept additional arguments.`);return{action:t}}if(e.length<2)throw new i(`INVALID_ARGS`,`clipboard write requires text.`);return{action:t,text:e.slice(1).join(` `)}}function eh(e,t){let n=e[0]?.toLowerCase(),r=n===`press`||n===`longpress`?e.slice(1):e;if(r.length!==1)throw new i(`INVALID_ARGS`,`tv-remote requires exactly one button: ${De.join(`, `)}, or android-keycode:<n>.`);let a=t??(n===`longpress`?500:void 0);return m({button:he(r[0]),durationMs:a})}function th(e){return{button:ee[ie(e)]}}function nh(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 i(`INVALID_ARGS`,`keyboard action must be status, get, dismiss, enter, or return.`)}const rh=[kc,Hu,as,Ym,Vf,Mp,zd,Af,us,op,Ju,Bi];function ih(){return rh.flatMap(e=>[...e.metadata])}function ah(){return rh.flatMap(e=>[...e.definitions])}function oh(){return uh(`cliSchemas`)}function sh(){return uh(`cliReaders`)}function ch(){return uh(`daemonWriters`)}function lh(){return uh(`cliOutputFormatters`)}function uh(e){let t={};for(let n of rh){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 dh=ih(),fh=new Map(dh.map(e=>[e.name,e]));function ph(){return[...dh]}function mh(){return Tt().map(e=>{let t=gh(e);if(!t)throw Error(`Missing command metadata for MCP-exposed command: ${e}`);return t})}function hh(e){return fh.has(e)}function gh(e){return fh.get(e)}export{Xi as A,E as B,gs as C,ta as D,aa as E,T as F,Wn as G,wr as H,w as I,Dn as J,jn as K,k as L,_i as M,gi as N,na as O,O as P,D as R,_c as S,Ao as T,Yn as U,Cr as V,Xn as W,On as Y,Su as _,lh as a,El as b,ch as c,tm as d,im as f,wu as g,Bu as h,mh as i,Ai as j,ra as k,ah as l,Ku as m,hh as n,sh as o,kp as p,Mn as q,ph as r,oh as s,gh as t,ih as u,Gl as v,Yo as w,Ec as x,Hl as y,C as z};