agent-device 0.21.18 → 0.21.20

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 (205) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.18.apk → agent-device-android-ime-helper-0.21.20.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.20.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.18.manifest.json → agent-device-android-ime-helper-0.21.20.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.18.apk → agent-device-android-snapshot-helper-0.21.20.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.20.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.18.manifest.json → agent-device-android-snapshot-helper-0.21.20.manifest.json} +6 -6
  7. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +12 -0
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +1 -14
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +14 -16
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +40 -14
  11. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +20 -5
  12. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationProjection.swift +2 -15
  13. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFold.swift +10 -25
  14. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFoldProjection.swift +1 -18
  15. package/dist/src/adapter.js +1 -1
  16. package/dist/src/adb-executor.js +2 -2
  17. package/dist/src/adb-failure.js +2 -1
  18. package/dist/src/agent-browser-lifecycle.js +1 -1
  19. package/dist/src/agent-browser-process-record.js +1 -1
  20. package/dist/src/agent-browser-provider.js +1 -1
  21. package/dist/src/agent-browser-tool.js +1 -1
  22. package/dist/src/agent-device-client.js +2 -2
  23. package/dist/src/ai-sdk.js +1 -1
  24. package/dist/src/alert-runtime.js +1 -1
  25. package/dist/src/alert.js +1 -0
  26. package/dist/src/android-input-ownership.js +1 -1
  27. package/dist/src/android.js +1 -1
  28. package/dist/src/app-launch.js +2 -2
  29. package/dist/src/app-lifecycle.js +1 -1
  30. package/dist/src/app-log-runtime2.js +1 -1
  31. package/dist/src/app-resolution.js +2 -2
  32. package/dist/src/apple-runner-platform.js +1 -1
  33. package/dist/src/archive.js +2 -2
  34. package/dist/src/browser-launch.js +1 -1
  35. package/dist/src/cache.js +1 -1
  36. package/dist/src/catalog.js +1 -1
  37. package/dist/src/cli-config.js +1 -1
  38. package/dist/src/cli-help.js +287 -301
  39. package/dist/src/cli-runner.js +1 -1
  40. package/dist/src/cli.js +4 -4
  41. package/dist/src/client-metro-companion.js +1 -1
  42. package/dist/src/client-metro.js +1 -1
  43. package/dist/src/client-types.d.ts +25 -6
  44. package/dist/src/{scroll-command.d.ts → cloud-artifacts.d.ts} +242 -238
  45. package/dist/src/command-metadata.js +1 -1
  46. package/dist/src/command-schema.js +3 -3
  47. package/dist/src/command-tools.js +2 -2
  48. package/dist/src/command.js +1 -1
  49. package/dist/src/config.js +1 -1
  50. package/dist/src/connection-runtime.js +1 -1
  51. package/dist/src/contracts.js +1 -1
  52. package/dist/src/daemon-client-lease-beat.js +1 -1
  53. package/dist/src/daemon-client-lifecycle.js +1 -1
  54. package/dist/src/daemon-client-transport.js +1 -1
  55. package/dist/src/daemon-policy-file.js +1 -1
  56. package/dist/src/daemon-registration.js +1 -1
  57. package/dist/src/debug-symbols-facade.js +3 -3
  58. package/dist/src/device-claim-inspection.js +1 -1
  59. package/dist/src/device-claim-rule.js +1 -1
  60. package/dist/src/device-inventory-context.js +1 -1
  61. package/dist/src/device-rotation.js +1 -1
  62. package/dist/src/device-session.js +1 -1
  63. package/dist/src/devicectl.js +1 -1
  64. package/dist/src/diagnostics.js +1 -1
  65. package/dist/src/diagnostics2.js +1 -1
  66. package/dist/src/display-inventory.js +1 -1
  67. package/dist/src/durable-resource.js +1 -1
  68. package/dist/src/engine-eval-script.js +1 -1
  69. package/dist/src/error.js +1 -1
  70. package/dist/src/exec.js +1 -1
  71. package/dist/src/find.js +1 -1
  72. package/dist/src/finders.js +1 -1
  73. package/dist/src/generic-settle.js +1 -1
  74. package/dist/src/gesture-runtime.js +1 -1
  75. package/dist/src/hdc.js +1 -1
  76. package/dist/src/helper.js +2 -2
  77. package/dist/src/host.js +1 -1
  78. package/dist/src/index.d.ts +3 -3
  79. package/dist/src/index.js +1 -1
  80. package/dist/src/input-actions2.js +2 -2
  81. package/dist/src/install-source-network-transport.js +1 -1
  82. package/dist/src/interaction-positionals.js +1 -1
  83. package/dist/src/interaction-ref-policy.js +1 -1
  84. package/dist/src/interaction.js +1 -1
  85. package/dist/src/interaction2.js +1 -1
  86. package/dist/src/interactor.js +5 -5
  87. package/dist/src/interactor2.js +1 -1
  88. package/dist/src/internal/bin.js +1 -1
  89. package/dist/src/internal/daemon.js +2 -2
  90. package/dist/src/internal/png-worker.js +1 -1
  91. package/dist/src/ios-snapshot-acquisition.js +1 -1
  92. package/dist/src/ios-snapshot-engine.js +1 -1
  93. package/dist/src/launch-confirmation.js +1 -0
  94. package/dist/src/lease.js +1 -1
  95. package/dist/src/limrun-runtime-dependencies.js +1 -1
  96. package/dist/src/limrun.d.ts +50 -42
  97. package/dist/src/local-interactor-operation-set.js +1 -1
  98. package/dist/src/mechanics.js +16 -17
  99. package/dist/src/mobile-snapshot-semantics.js +1 -1
  100. package/dist/src/observe-until.js +1 -0
  101. package/dist/src/overlay.js +2 -2
  102. package/dist/src/owner-identity.js +1 -1
  103. package/dist/src/parameterized-recorded-fill.js +1 -1
  104. package/dist/src/perf-facade.js +1 -1
  105. package/dist/src/perf-runtime-operation-builder.js +1 -1
  106. package/dist/src/perf-runtime-plan.js +1 -1
  107. package/dist/src/perf-target.js +1 -1
  108. package/dist/src/physical-device-control.js +1 -1
  109. package/dist/src/platform-request-scope.js +1 -1
  110. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  111. package/dist/src/platform-runtime-app-log-process.js +1 -1
  112. package/dist/src/platform-runtime-host.js +1 -1
  113. package/dist/src/platform-runtime-managed-owner.js +1 -1
  114. package/dist/src/platform-runtime-operation-host.js +2 -2
  115. package/dist/src/platform-runtime-runtime-hints.js +1 -1
  116. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  117. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  118. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  119. package/dist/src/platform-runtime.js +1 -1
  120. package/dist/src/platform-runtime2.js +1 -1
  121. package/dist/src/png-worker-client.js +1 -1
  122. package/dist/src/provider-device-admission.js +1 -0
  123. package/dist/src/provider-session-ownership.js +1 -1
  124. package/dist/src/provider-webdriver.js +1 -1
  125. package/dist/src/proxy.js +1 -1
  126. package/dist/src/react-native.js +1 -1
  127. package/dist/src/record-runtime.js +1 -1
  128. package/dist/src/registry.js +52 -36
  129. package/dist/src/replay-divergence.js +1 -1
  130. package/dist/src/replay.js +1 -1
  131. package/dist/src/request-admission.js +1 -1
  132. package/dist/src/request-runtime-binding.js +1 -1
  133. package/dist/src/result-serialization.js +1 -1
  134. package/dist/src/runner-cache-metadata.js +3 -3
  135. package/dist/src/runner-client.js +1 -1
  136. package/dist/src/runner-dev-tools-security.js +1 -1
  137. package/dist/src/runner-device-readiness.js +1 -1
  138. package/dist/src/runner-disposal.js +1 -1
  139. package/dist/src/runner-error-classification.js +3 -3
  140. package/dist/src/runner-exchange.js +1 -1
  141. package/dist/src/runner-operations-facade.js +1 -1
  142. package/dist/src/runner-session-types.js +1 -1
  143. package/dist/src/runner-start-budget.js +1 -1
  144. package/dist/src/runner-startup-transport.js +1 -1
  145. package/dist/src/runner-xctestrun.js +1 -1
  146. package/dist/src/runner.js +1 -1
  147. package/dist/src/runtime-admission.js +1 -0
  148. package/dist/src/runtime.js +1 -1
  149. package/dist/src/runtime10.js +2 -2
  150. package/dist/src/runtime2.js +2 -2
  151. package/dist/src/runtime3.js +1 -1
  152. package/dist/src/runtime4.js +5 -5
  153. package/dist/src/runtime5.js +1 -1
  154. package/dist/src/runtime6.js +1 -1
  155. package/dist/src/runtime7.js +1 -1
  156. package/dist/src/runtime8.js +1 -1
  157. package/dist/src/runtime9.js +1 -1
  158. package/dist/src/screen-recording-resource-recovery.js +1 -1
  159. package/dist/src/screenshot-result.js +1 -1
  160. package/dist/src/screenshot-runtime.js +1 -1
  161. package/dist/src/screenshot3.js +1 -1
  162. package/dist/src/script.js +1 -1
  163. package/dist/src/scroll-gesture.js +1 -1
  164. package/dist/src/sdk-batch-runner.js +2 -2
  165. package/dist/src/sdk-batch.js +1 -1
  166. package/dist/src/sdk-contracts.d.ts +18 -2
  167. package/dist/src/sdk-contracts.js +2 -2
  168. package/dist/src/sdk-finders.js +1 -1
  169. package/dist/src/sdk-selectors.d.ts +13 -4
  170. package/dist/src/sdk-selectors.js +1 -1
  171. package/dist/src/selection.js +0 -0
  172. package/dist/src/selector-pipeline-policy.js +1 -0
  173. package/dist/src/selector-runtime.js +1 -1
  174. package/dist/src/selectors.js +1 -1
  175. package/dist/src/server.js +1 -1
  176. package/dist/src/session-runtime-admission.js +1 -1
  177. package/dist/src/session-snapshot.js +1 -1
  178. package/dist/src/session-store.js +3 -3
  179. package/dist/src/session2.js +5 -5
  180. package/dist/src/simulator-boot.js +1 -1
  181. package/dist/src/simulator.js +1 -1
  182. package/dist/src/snapshot-desktop-projection.js +1 -1
  183. package/dist/src/snapshot-runtime-binding.js +1 -1
  184. package/dist/src/snapshot-runtime.js +1 -1
  185. package/dist/src/snapshot-state.js +1 -1
  186. package/dist/src/snapshot4.js +1 -1
  187. package/dist/src/src.js +1 -1
  188. package/dist/src/src7.js +1 -1
  189. package/dist/src/target-evidence.js +1 -1
  190. package/dist/src/text-entry-focus.js +1 -1
  191. package/dist/src/tool-provider.js +3 -3
  192. package/dist/src/tool-provider2.js +1 -1
  193. package/dist/src/tool-provider3.js +1 -1
  194. package/dist/src/toolchain-probe.js +1 -1
  195. package/dist/src/touch-runtime.js +1 -1
  196. package/dist/src/touch-runtime2.js +1 -0
  197. package/dist/src/tree.js +1 -1
  198. package/dist/src/type-text-runtime.js +1 -1
  199. package/dist/src/update-check.js +1 -1
  200. package/dist/src/video.js +1 -1
  201. package/package.json +1 -1
  202. package/server.json +2 -2
  203. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.18.apk.sha256 +0 -1
  204. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.18.apk.sha256 +0 -1
  205. package/dist/src/runner-command-traits.js +0 -1
@@ -1,38 +1,38 @@
1
- import{D as e,M as t,N as n,O as r,T as i,g as a,p as o,t as s,x as c}from"./sdk-contracts.js";import{a as ee,d as te,f as ne,m as re,n as ie,p as ae,t as oe,u as se}from"./capture.js";import{_ as l,c as ce,d as le,f as ue,k as de,l as fe,m as pe,p as me,s as he,u as ge}from"./sdk-batch-runner.js";import{t as _e}from"./viewport.js";import{a as ve,i as ye,n as be,t as xe}from"./sdk-device.js";import{a as Se,c as Ce}from"./lease-scope.js";import{$r as we,Fn as Te,Lr as Ee,Mr as De,Sr as Oe,cn as ke,dr as Ae,gr as je,i as Me,jn as Ne,kn as Pe,lr as Fe,m as Ie,mr as Le,on as Re,p as ze,s as Be,ur as Ve}from"./sdk-batch.js";import{n as He}from"./recording-export-quality.js";import{t as Ue}from"./recording-scope.js";import{a as We,n as Ge,o as Ke,r as qe,s as Je}from"./scroll-gesture.js";import{E as Ye,T as Xe,b as Ze,v as Qe,w as $e}from"./script.js";import{a as et,i as tt,r as nt}from"./vars.js";import{n as rt,r as it,t as at}from"./format.js";import{n as u,t as ot}from"./catalog.js";import{i as st,r as ct,t as lt}from"./back-mode.js";import{a as ut}from"./sdk-remote-config.js";import{t as dt}from"./session.js";import{a as ft,c as pt,d as mt,f as ht,g as gt,h as _t,i as vt,l as yt,n as bt,o as xt,p as St,s as Ct,t as wt,u as Tt}from"./observability.js";import{n as Et,t as Dt}from"./success-text.js";import{a as d,i as Ot,n as kt,r as f}from"./output-common.js";import{t as At}from"./alert-contract.js";import{a as jt,i as Mt,l as Nt,o as Pt,s as Ft,t as It,u as Lt,x as Rt}from"./settings.js";import{t as zt}from"./location-coordinates.js";import{t as Bt}from"./snapshot-quality-backend-capabilities.js";import{f as Vt,m as Ht,p as Ut,r as Wt,s as Gt}from"./overlay.js";import{t as Kt}from"./mobile-snapshot-semantics.js";import{t as qt}from"./click-button.js";import{n as Jt}from"./scroll-command.js";import{n as Yt,t as Xt}from"./interaction-positionals.js";import{t as Zt}from"./app-inventory.js";import"./device.js";import{a as Qt,d as $t,f as en,i as tn,o as nn,r as rn,t as an,u as on}from"./device-rotation.js";import"./app-inventory-contract.js";import{t as sn}from"./prepare-kind.js";import{n as cn,t as ln}from"./path-resolution.js";import"./file.js";import{n as un,r as dn,s as fn,t as pn}from"./tv-remote.js";import p from"node:path";import mn from"node:fs";const hn=[`path`,`start`,`stop`,`doctor`,`mark`,`clear`],gn=new Set(ct().map(e=>e.key));function _n(t){let n=Se(t);return de({stateDir:t.stateDir,daemonBaseUrl:t.daemonBaseUrl,daemonTransport:t.daemonTransport,daemonServerMode:t.daemonServerMode,...Ce(n),provider:t.provider,providerSessionId:t.providerSessionId,providerApp:t.providerApp,providerOsVersion:t.providerOsVersion,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,a),...se(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,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 vn(e,t){return{..._n(e),...t}}function yn(e,t){let n=e.inputSchema.properties;if(!n)return{};let r={},i=t;for(let e of Object.keys(n)){if(!gn.has(e))continue;let t=i[e];bn(t)&&(r[e]=t)}return r}function bn(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`}function xn(e){return{kind:`operator`,source:e}}function Sn(e,t){return`${e} is not accepted as a tool argument. ${Cn(e,t)}`}function Cn(e,t){if(`operatorPath`in t)return t.operatorPath;let n=`for the process serving these tools.`,r=(t.envFlagKeys??[e]).map(ut).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 wn(e){if(e==null)return{};if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected object arguments.`);return e}function Tn(e,t){let r=e[t];if(!r||typeof r!=`object`||Array.isArray(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be an object.`);return r}function En(e,t){let r=e[t];if(typeof r!=`string`||r.length===0)throw new n(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return r}function Dn(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`string`)throw new n(`INVALID_ARGS`,`Expected ${t} to be a string.`);return r}}function m(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`string`||r.length===0)throw new n(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return r}}function On(e,t){let r=e[t];if(typeof r!=`number`||!Number.isFinite(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be a finite number.`);return r}function kn(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`boolean`)throw new n(`INVALID_ARGS`,`Expected ${t} to be a boolean.`);return r}}function An(e,t,r){let i=e[t];if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected ${t} to be one of: ${r.join(`, `)}.`);return i}function jn(e,t,r){let i=e[t];if(i!==void 0){if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected ${t} to be one of: ${r.join(`, `)}.`);return i}}function Mn(e,t){let r=e[t];if(r!==void 0){if(!r||typeof r!=`object`||Array.isArray(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be an object.`);return r}}function Nn(e,t){let r=e[t];if(r!==void 0){if(!Array.isArray(r)||r.some(e=>typeof e!=`string`))throw new n(`INVALID_ARGS`,`Expected ${t} to be an array of strings.`);return r}}function Pn(e,t,r,i){let a=new Set(t),o=Object.keys(e).filter(e=>!a.has(e));if(o.length>0)throw new n(`INVALID_ARGS`,`${r} has unknown field(s): ${o.join(`, `)}.`,i===void 0?void 0:{hint:i})}function h(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}const Fn=xn({operatorConfig:!0}),In={session:{schema:{type:`string`,description:`Agent-device session name.`},read:e=>m(e,`session`),flagKey:`session`,flagIn:[`input`]},platform:{schema:{type:`string`,enum:ye,description:`Platform selector used to resolve a device.`},read:e=>jn(e,`platform`,ye),flagKey:`platform`,flagIn:[`input`,`selection`]},deviceTarget:{schema:{type:`string`,enum:be,description:`Device target form. Maps to the CLI --target flag.`},read:Hn,clientKey:`target`,flagKey:`target`,flagIn:[`input`,`selection`]},target:{schema:{type:`string`,enum:be,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=>m(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=>m(e,`udid`),flagKey:`udid`,flagIn:[`input`,`selection`]},serial:{schema:{type:`string`,description:`Android, HarmonyOS, or Vega VVD serial selector.`},read:e=>m(e,`serial`),flagKey:`serial`,flagIn:[`input`,`selection`]},iosSimulatorDeviceSet:{schema:{type:`string`,description:`iOS simulator device-set path used for device resolution.`},read:e=>m(e,`iosSimulatorDeviceSet`),audience:xn({envFlagKeys:[],operatorConfig:!0}),flagKey:`iosSimulatorDeviceSet`,flagIn:[`input`,`selection`]},iosXctestrunFile:{schema:{type:`string`,description:`Externally built iOS XCTest runner .xctestrun artifact path.`},read:e=>m(e,`iosXctestrunFile`),audience:Fn,flagKey:`iosXctestrunFile`,flagIn:[`input`]},iosXctestDerivedDataPath:{schema:{type:`string`,description:`Derived data path for external iOS XCTest runner execution.`},read:e=>m(e,`iosXctestDerivedDataPath`),audience:Fn,flagKey:`iosXctestDerivedDataPath`,flagIn:[`input`]},iosXctestEnvDir:{schema:{type:`string`,description:`Writable directory for iOS XCTest runner env overlays.`},read:e=>m(e,`iosXctestEnvDir`),audience:Fn,flagKey:`iosXctestEnvDir`,flagIn:[`input`]},androidDeviceAllowlist:{schema:{type:`string`,description:`Android serial allowlist used for device resolution.`},read:e=>m(e,`androidDeviceAllowlist`),flagKey:`androidDeviceAllowlist`,flagIn:[`input`,`selection`]},noRecord:{read:e=>kn(e,`noRecord`),flagKey:`noRecord`,flagIn:[`input`,`selection`]},daemonBaseUrl:{schema:{type:`string`,description:`Remote daemon base URL.`},read:e=>m(e,`daemonBaseUrl`),audience:Fn},daemonAuthToken:{schema:{type:`string`,description:`Remote daemon auth token.`},read:e=>m(e,`daemonAuthToken`),audience:Fn},tenant:{schema:{type:`string`,description:`Remote tenant identifier.`},read:e=>m(e,`tenant`)},runId:{schema:{type:`string`,description:`Lease run identifier.`},read:e=>m(e,`runId`)},leaseId:{schema:{type:`string`,description:`Existing lease identifier.`},read:e=>m(e,`leaseId`)},cwd:{schema:{type:`string`,description:`Working directory for command execution.`},read:e=>m(e,`cwd`),audience:xn({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=>kn(e,`debug`)}},Ln=Object.entries(In),Rn=Object.fromEntries(Ln.flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]));function zn(){return Object.fromEntries(Ln.flatMap(([e,t])=>t.schema?[[e,t.schema]]:[]))}function Bn(e,t={}){let n={};for(let[r,i]of Ln)i.read&&(n[r]=i.read(e,t));return n}function g(e){let t={};for(let[n,r]of Ln)r.read&&(t[r.clientKey??n]=e[n]);return h(t)}function Vn(e,t){let n={};for(let[r,i]of Ln){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 Hn(e,t){let r=jn(e,`deviceTarget`,be);if(t.readTargetAlias===!1||e.target===void 0)return r;let i=jn(e,`target`,be);if(r!==void 0&&i!==r)throw new n(`INVALID_ARGS`,`Expected target alias to match deviceTarget when both are set.`);return r??i}function _(e,t){return n=>v(e,t?t(n):[],n)}function v(e,t,n,r){return{command:e,positionals:t,...r?{input:r}:{},options:Un(n)}}function Un(e){let t=Wn(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 Wn(e){return e===`mobile`||e===`tv`||e===`desktop`?e:void 0}function y(e){return h(Vn(e,`input`))}function Gn(e){return h({record:e.record})}function Kn(e){return Vn(e,`selection`)}function qn(e){return h({depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw})}function Jn(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function Yn(e){return h({settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs})}function Xn(e){return h({count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap})}function Zn(e){if(`ref`in e&&e.ref!==void 0)return h({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 Qn(e){let t=er(e);if(typeof t.ref==`string`)return[t.ref,...nr(t.label)];if(typeof t.selector==`string`)return[t.selector];if(t.kind===`point`||t.x!==void 0||t.y!==void 0)return[String(tr(t.x,`x`)),String(tr(t.y,`y`))];throw new n(`INVALID_ARGS`,`interaction requires @ref, selector, or point target`)}function $n(e){let t=er(e);if(typeof t.ref==`string`)return[t.ref,...nr(t.label)];if(typeof t.selector==`string`)return[t.selector];throw new n(`INVALID_ARGS`,`element command requires @ref or selector target`)}function er(e){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected target object.`);let t=e,r=t.target;return r&&typeof r==`object`&&!Array.isArray(r)?r:t}function tr(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw new n(`INVALID_ARGS`,`point target requires numeric ${t}.`);return e}function nr(e){return typeof e==`string`&&e.length>0?[e]:[]}function rr(e){let t=Ve(e);if(!t.ok)throw new n(t.code,t.message);return`ref`in t?{ref:t.ref,label:sr(e.slice(1))}:{selector:t.selector}}function ir(e){let t=Ae(e);if(!t.ok)throw new n(t.code,t.message);return t.format}function ar(e,t={}){let r=Oe(e,t);if(!r)throw new n(`INVALID_ARGS`,Fe);return r}function or(e,t){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}throw new n(`INVALID_ARGS`,`${t} must be a JSON object`)}function sr(e){return e.join(` `).trim()||void 0}function b(...e){return new Set(e)}function x(e,t){return e!==void 0&&t.has(e)}function cr(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function lr(e,t){if(e===void 0)return;let r=Number(e);if(Number.isFinite(r))return r;throw new n(`INVALID_ARGS`,`${t} must be a finite number.`)}function ur(e){return e===void 0?void 0:Number(e)}function S(e){return e===void 0?[]:[e]}function C(e){return e===void 0?[]:[String(e)]}function w(e,t){if(e===void 0||e===``)throw new n(`INVALID_ARGS`,t);return e}function T(e,t){if(typeof e!=`string`||e.length===0)throw new n(`INVALID_ARGS`,t);return e}function dr(e){return mr(e.description,e.cliDetail)}function fr(e){return mr(e.description,e.mcpDetail)}function pr(e,t){return{...e,description:t}}function mr(e,t){return t?`${e} ${t}`:e}function hr(e){return e}const gr=[`ref`,`selector`,`point`];function _r(e,t=[]){return{type:`object`,properties:{...zn(),...e},...t.length>0?{required:t}:{},additionalProperties:!1}}function E(e,t=[],n){return{type:`object`,...n?{description:n}:{},properties:e,...t.length>0?{required:t}:{}}}function vr(e){return{type:`object`,description:e,properties:{x:{type:`number`},y:{type:`number`}},required:[`x`,`y`],additionalProperties:!1}}function D(e,t){return{type:`string`,enum:e,...t?{description:t}:{}}}function O(e){return{type:`string`,const:e}}function k(e){return{type:`string`,...e?{description:e}:{}}}function yr(e){return{type:[`string`,`null`],...e?{description:e}:{}}}function A(e,t={}){return{type:`number`,...e?{description:e}:{},...t.min===void 0?{}:{minimum:t.min},...t.max===void 0?{}:{maximum:t.max}}}function br(e){return{type:`integer`,...e?{description:e}:{}}}function j(e){return{type:`boolean`,...e?{description:e}:{}}}function xr(e){return{type:`array`,items:{type:`string`},...e?{description:e}:{}}}function M(e){return{type:`object`,additionalProperties:!0,...e?{description:e}:{}}}function N(e){return{...e,required:!0}}function P(e,t={}){return B(k(e),t.allowEmpty===!0?Dn:m)}function Sr(e){return{schema:{type:`null`},required:!1,audience:{kind:`retired`,message:e},read:(t,r)=>{if(Object.hasOwn(t,r))throw new n(`INVALID_ARGS`,e)}}}function Cr(e,t){return{...e,audience:{kind:`operator`,source:t}}}function F(e,t={}){return B(A(e,t),(e,n)=>pe(e,n,t))}function I(e,t={}){return B(Gr(e,t),(e,n)=>me(e,n,t))}function L(e){return B(j(e),kn)}function wr(e){return Er(Tr(e))}function Tr(e){let[t,...n]=st(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 Er(e){let t=e.inputDescription,n={min:e.min,max:e.max};switch(e.type){case`boolean`:return L(t);case`int`:return I(t,n);case`number`:return F(t,n);case`string`:return P(t);case`enum`:return R(Dr(e),t);case`booleanOrString`:throw Error(`Flag ${e.key} is booleanOrString; declare its field shape explicitly with jsonSchemaField`)}}function Dr(e){let t=e.enumValues;if(!t)throw Error(`Flag ${e.key} is an enum with no enumValues`);return t}function R(e,t){return B(D(e,t),(t,n)=>jn(t,n,e))}function Or(e){return B(M(e),Mn)}function kr(e){return B(xr(e),Nn)}function z(e){return B(e,(e,t)=>e[t])}function Ar(e,t){return B(e,t)}function jr(){return B(Yr(),(e,t)=>e[t]===void 0?void 0:Rr(e,t))}function Mr(){return B(Xr(),(e,t)=>e[t]===void 0?void 0:zr(e,t))}function Nr(e){return B(vr(e),(e,t)=>e[t]===void 0?void 0:Br(e,t))}function Pr(){return{depth:I(`Snapshot traversal depth.`,{min:0}),scope:P(`Snapshot scope selector used before resolution.`),raw:L(`Use raw snapshot data during selector resolution.`)}}function Fr(){return{count:I(`Number of press/click repetitions.`,{min:1}),intervalMs:I(`Delay between repeated press/click actions.`,{min:0}),holdMs:I(`Hold duration for each action.`,{min:0}),jitterPx:I(`Randomization radius in pixels.`,{min:0}),doubleTap:L(`Request a double-tap action.`)}}function Ir(e){return _r(Kr(e),qr(e))}function Lr(e,t){let r=wn(e),i=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{let i=t.read(r,e);if(t.required&&i===void 0)throw new n(`INVALID_ARGS`,`Expected ${e} to be set.`);return i===void 0?[]:[[e,i]]})),a=Bn(r,{readTargetAlias:!Object.hasOwn(t,`target`)});return h({...a,...g(a),...i})}function Rr(e,t){let n=Tn(e,t),r=An(n,`kind`,gr);switch(r){case`ref`:return{kind:r,ref:En(n,`ref`),label:m(n,`label`)};case`selector`:return{kind:r,selector:En(n,`selector`)};case`point`:return{kind:r,x:On(n,`x`),y:On(n,`y`)}}}function zr(e,t){let n=Tn(e,t),r=An(n,`kind`,[`ref`,`selector`]);return r===`ref`?{kind:r,ref:En(n,`ref`),label:m(n,`label`)}:{kind:r,selector:En(n,`selector`)}}function Br(e,t){let n=Tn(e,t);return{x:On(n,`x`),y:On(n,`y`)}}function Vr(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 Hr(e){switch(e.kind){case`ref`:return{ref:e.ref,label:e.label};case`selector`:return{selector:e.selector}}}function Ur(e){return{count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap}}function Wr(e){return{depth:e.depth,scope:e.scope,raw:e.raw}}function B(e,t){return{schema:e,required:!1,read:t}}function Gr(e,t){return{...br(e),...t.min===void 0?{}:{minimum:t.min},...t.max===void 0?{}:{maximum:t.max}}}function Kr(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 Jr(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]))}function Yr(){return{oneOf:[...Zr(),{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 Xr(){return{oneOf:Zr(),description:`UI element target by snapshot ref or selector expression.`}}function Zr(){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 V(e,t,n,r){return hr({name:e,description:t,inputSchema:Ir(n),readInput:r?.readInput??(e=>Lr(e,n)),inputAudience:Jr(n),...r?.parseableOutput?{parseableOutput:!0}:{}})}function H(e){let t=pr(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 Qr(e){return H({name:e.name,text:e.text,metadata:V(e.name,e.description,{}),run:e.run,cliSchema:{},cliReader:(e,t)=>y(t),daemonWriter:_(e.name),cliOutputFormatter:e.cliOutputFormatter})}function U(e){let t={},n={},r={},i={};for(let a of e.commands)$r(t,`CLI schema`,a.name,a.cliSchema),$r(n,`CLI reader`,a.name,a.cliReader),a.daemonWriter&&$r(r,`daemon writer`,a.name,a.daemonWriter),a.cliOutputFormatter&&$r(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 $r(e,t,n,r){if(Object.hasOwn(e,n))throw Error(`Duplicate command family ${t}: ${n}`);e[n]=r}function ei(e){let t=[`Batch completed: ${e.executed}/${e.total} steps in ${e.totalDurationMs}ms`];for(let n of e.results)t.push(ni(n));return{data:e,text:t.join(`
2
- `)}}const ti={batch:d(ei)};function ni(e){let t=Dt(e.data)??e.command;return`${e.step}. OK ${t} (${e.durationMs}ms)`}function ri(e=Me){let t=ii(e);return V(`batch`,`Execute multiple commands in one daemon request.`,t,{readInput:e=>oi(e,t)})}function ii(e){return{steps:N(Ar({type:`array`,description:`Structured batch steps. Each step uses a command name and the same input object as that command tool.`,items:ai(e)},(t,n)=>si(t[n],e))),onError:R([`stop`],`Batch failure policy.`),maxSteps:I(`Maximum number of steps accepted for this batch.`,{min:1,max:1e3}),out:P(`Optional output path for command artifacts.`)}}function ai(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 oi(e,t){let r=Lr(e,t),i=r.maxSteps??100;if(!fe(i))throw new n(`INVALID_ARGS`,`Invalid batch maxSteps: ${String(r.maxSteps)}`);return ce(r.steps.length,i),{...r}}function si(e,t){if(!Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected steps to be an array.`);return e.map((e,n)=>ci(e,n+1,t))}function ci(e,t,n){let r=ue(e,t);return Pn(r,[`command`,`input`,`runtime`],`Batch step ${t}`,he),{command:li(r,t,n),input:le(r,t),...ui(r,t)}}function li(e,t,r){if(r===Me)return Be(e.command,t);let i=e.command;if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected command to be one of: ${r.join(`, `)}.`);return i}function ui(e,t){let n=ge(e.runtime,t);return n===void 0?{}:{runtime:n}}function di(e){return async t=>v(u.batch,[],{...t,batchSteps:await fi(t.steps,e),batchOnError:t.onError,batchMaxSteps:t.maxSteps})}async function fi(e,t){if(!Array.isArray(e)||e.length===0)throw new n(`INVALID_ARGS`,`batch requires a non-empty steps array.`);let r=[];for(let[n,i]of e.entries())r.push(await pi(i,n+1,t));return r}async function pi(e,t,n){let r=ue(e,t),i=mi(r,t),a=le(r,t),o=ge(r.runtime,t),s=await n(i,a,t);return{command:s.command,positionals:s.positionals,...s.input?{input:s.input}:{},flags:vn(s.options,s.metadataFlags),runtime:o??s.options.runtime}}function mi(e,t){return Be(e.command,t)}const hi=ri(),gi={usageOverride:`batch [--steps <json> | --steps-file <path>]`,usageFlags:[],listUsageOverride:`batch --steps <json> | --steps-file <path>`,allowedFlags:[`steps`,`stepsFile`,`batchOnError`,`batchMaxSteps`,`out`]},_i=(e,t)=>({...y(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out}),vi=[{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 yi(){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: ${[...Me].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(vi)}'`,` agent-device batch --steps-file ./steps.json --json`].join(`
3
- `)}`}const bi=U({name:`batch`,clientSurface:!1,commands:[H({name:`batch`,text:{summary:`Run multiple commands`,cliDetail:yi()},metadata:hi,run:(e,t)=>e.batch.run(xi(t)),cliSchema:gi,cliReader:_i,cliOutputFormatter:ti.batch})]});function xi(e){return{...g(e),steps:e.steps,onError:e.onError,maxSteps:e.maxSteps,out:e.out}}const Si=`alert`,Ci=H({name:Si,text:{summary:`Inspect, accept, or dismiss a platform alert`},metadata:V(Si,`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. Inspect again after an unconfirmed action; never assume a timeout means nothing happened.`,{action:R(At),timeoutMs:I()}),run:(e,t)=>e.command.alert(t),cliSchema:{usageOverride:`alert [get|accept|dismiss|wait] [timeout]`,positionalArgs:[`action?`,`timeout?`]},cliReader:(e,t)=>({...y(t),...Ti(e)}),daemonWriter:_(u.alert,e=>wi(e)),cliOutputFormatter:f});function wi(e){return[e.action??`get`,...C(e.timeoutMs)]}function Ti(e){if(e.length>2)throw new n(`INVALID_ARGS`,`alert accepts at most action and timeout arguments.`);return h({action:Ei(e[0]),timeoutMs:lr(e[1],`alert timeout`)})}function Ei(e){let t=e?.toLowerCase();if(t===void 0||t===`get`||t===`accept`||t===`dismiss`||t===`wait`)return t;throw new n(`INVALID_ARGS`,`alert action must be get, accept, dismiss, or wait.`)}function W(...e){return e}const Di=W(`keyframes`),Oi=W(`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`),ki=W(`snapshotDepth`,`snapshotScope`,`snapshotRaw`),Ai=W(`metroProjectRoot`,`kind`,`metroKind`,`metroPublicBaseUrl`,`metroProxyBaseUrl`,`metroBearerToken`,`metroPreparePort`,`metroListenHost`,`metroStatusHost`,`metroStartupTimeoutMs`,`metroProbeTimeoutMs`,`metroRuntimeFile`,`metroNoReuseExisting`,`metroNoInstallDeps`),ji=W(`metroHost`,`metroPort`,`bundleUrl`),Mi=W(`count`,`intervalMs`,`holdMs`,`jitterPx`,`doubleTap`),Ni=W(`settle`,`settleQuietMs`,`timeoutMs`),Pi=W(`replayUpdate`,`replayEnv`),Fi=W(`remoteConfig`,`stateDir`,`daemonBaseUrl`,`daemonAuthToken`,`daemonTransport`,`daemonServerMode`,`tenant`,`sessionIsolation`,`runId`,`leaseId`,`leaseBackend`,`sessionLock`,`platform`,`target`,`device`,`providerApp`,`providerOsVersion`,`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`),Ii=new Set([`platform`,`device`,`udid`,`serial`,`session`]),Li=new Set([`json`,`config`,`help`,`version`,`verbose`,`cost`,`responseLevel`]),Ri=`diff`,zi={diff:E({mode:O(`snapshot`),baselineInitialized:j(),summary:E({additions:A(),removals:A(),unchanged:A()},[`additions`,`removals`,`unchanged`]),lines:{type:`array`,items:E({kind:D([`added`,`removed`,`unchanged`]),text:k(),ref:k()},[`kind`,`text`])},warnings:xr()},[`mode`,`baselineInitialized`,`summary`,`lines`])},Bi=H({name:Ri,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:V(Ri,`Compare accessibility snapshots or screenshots to identify UI changes. Use snapshot comparisons for semantic tree changes and screenshot comparisons for pixel differences.`,{kind:N(z({type:`string`,const:`snapshot`})),out:P(),interactiveOnly:L(),depth:I(),scope:P(),raw:L()}),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:[...Oi,`baseline`,`threshold`,`out`,`overlayRefs`]},cliReader:(e,t)=>{if(e[0]!==`snapshot`)throw new n(`INVALID_ARGS`,`Only diff snapshot is available through this parser.`);return{...y(t),kind:`snapshot`,out:t.out,interactiveOnly:t.snapshotInteractiveOnly,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw}},daemonWriter:_(u.diff,e=>[T(e.kind,`diff requires kind`)])}),Vi=`screenshot`,Hi=H({name:Vi,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 and Android emulators), --overlay-refs to annotate current refs, --normalize-status-bar for deterministic iOS simulator chrome, or --no-stabilize for low-latency Android capture loops. On macOS, any --surface other than app (desktop, menubar, frontmost-app) always captures the main display and refuses an explicit --fullscreen.`},metadata:V(Vi,`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:P(`Output path.`),cropOn:P(`Selector expression; the capture is cropped to the frame the selector resolves on the same screen.`),overlayRefs:L(),pixelDensity:I(`Output screenshot pixel density in pixels per logical point.`,{min:1}),fullscreen:L(),scale:F(`Screenshot scale factor.`,ee),maxSize:Sr(oe.migration.screenshot),stabilize:L(),normalizeStatusBar:L(),surface:R(dt)}),run:(e,t)=>e.capture.screenshot(t),cliSchema:{positionalArgs:[`path?`],allowedFlags:ie},cliReader:(e,t)=>({...y(t),path:e[0]??t.out,...ne(t)}),daemonWriter:e=>(ae(`screenshot`,e),re(e),v(u.screenshot,S(e.path),{...e,...te(e)}))}),Ui=`settings`,Wi=V(Ui,`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:N(P()),state:P(),app:P(),latitude:F(),longitude:F(),permission:P(),mode:R([...Ft])}),Gi={usageOverride:Lt,listUsageOverride:`settings [area] [options]`,positionalArgs:[`setting`,`state?`,`target?`,`mode?`]},Ki=(e,t)=>Yi(e,t),qi=_(u.settings,e=>Xi(e)),Ji=H({name:Ui,text:{summary:`Change OS settings and app permissions`,cliDetail:`macOS supports only settings appearance <light|dark|toggle> and settings ${Nt}; wifi|airplane|location|animations|text-size remain unsupported on macOS. Mobile permission actions use the active session app. On Android, deny|reset of a permission the app currently holds kills a running app; the response reports priorGrantState (granted|not_granted|unknown) and warns for granted and unknown, with open <app> --relaunch to restore it. Permission changes require a resolvable foreground user and fail without mutating if adb cannot report one. Android settings airplane on|off is applied by the connectivity service (Android 11+) and reports the airplaneMode that service holds; older builds fail without changing device state. settings reset-keychain clear is iOS-simulator-only and resets the whole simulator keychain, not just the selected app: simctl exposes no per-app keychain reset, so every app on that simulator loses its keychain-backed credentials (e.g. Firebase auth). clear-app-state does not touch the keychain, so a full fresh-install reset needs both; relaunch the app afterward to observe the signed-out state. settings text-size reads the preferred text size the target holds and settings text-size <category> applies one, on iPhone and iPad simulators (simctl content size) and on Android targets (system font_scale); tvOS and visionOS simulators, physical Apple devices, and the macOS host refuse it. Android has no category ladder of its own, so the read names the nearest rung and reports the exact multiplier as platformValue; an already-running app adopts a changed size at its next configuration change, so relaunch the app under test to observe it.`},metadata:Wi,run:(e,t)=>e.settings.update(t),cliSchema:Gi,cliReader:Ki,daemonWriter:qi,cliOutputFormatter:f});function Yi(e,t){let r=Kn(t),i=e[0],a=e[1];if(x(i,$i)&&x(a,ea))return{...r,setting:i,state:a};if(i===`location`&&a===`set`)return{...r,setting:i,state:a,latitude:zt(e[2],`latitude`),longitude:zt(e[3],`longitude`)};if(i===`appearance`&&x(a,ta))return{...r,setting:i,state:a};if(i===`text-size`)return a===void 0?{...r,setting:i}:{...r,setting:i,state:Rt(a)};if(x(i,na)&&x(a,ra)||i===`fingerprint`&&x(a,ia))return{...r,setting:i,state:a};if(i===`permission`&&x(a,oa))return{...r,setting:i,state:a,permission:Zi(e[2]),mode:Qi(e[3])};if(i===`clear-app-state`){let t=a===`clear`?e[2]:a;return{...r,setting:i,state:`clear`,app:t}}if(i===`reset-keychain`&&a===`clear`&&e.length===2)return{...r,setting:i,state:a};throw new n(`INVALID_ARGS`,`Invalid settings arguments.`)}function Xi(e){return e.setting===`clear-app-state`?[e.setting,...S(e.app)]:e.setting===`text-size`?[e.setting,...S(e.state)]:e.setting===`location`&&e.state===`set`?[e.setting,e.state,String(e.latitude),String(e.longitude)]:e.setting===`permission`?[e.setting,e.state,e.permission,...S(e.mode)]:[e.setting,e.state]}function Zi(e){if(x(e,sa))return e;throw new n(`INVALID_ARGS`,`settings permission requires a permission target.`)}function Qi(e){if(e===void 0||x(e,aa))return e;throw new n(`INVALID_ARGS`,`settings permission mode must be full or limited.`)}const $i=b(`wifi`,`airplane`,`location`,`animations`),ea=b(`on`,`off`),ta=b(...It),na=b(`faceid`,`touchid`),ra=b(`match`,`nonmatch`,`enroll`,`unenroll`),ia=b(`match`,`nonmatch`),aa=b(...Ft),oa=b(...Pt),sa=b(...jt,...Mt);function ca(e){if(!Array.isArray(e)||e.length===0)return e;let t=Ee(e);return e.map(e=>{let n=la(e,t,e=>e.label),r=la(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 la(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 ua(e){return e.width>0&&e.height>0}function da(e,t){return!e||!t?!1:e.x>=t.x-2&&e.y>=t.y-2&&e.x+e.width<=t.x+t.width+2&&e.y+e.height<=t.y+t.height+2}function fa(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 pa(e){return typeof e.parentIndex!=`number`}function ma(e){let t=(e.type??``).toLowerCase(),n=(e.identifier??``).trim().toLowerCase();return t.includes(`edittext`)||t.includes(`textfield`)||n===`composer`}function ha(e){let t=(e.type??``).toLowerCase();return t.includes(`scroll`)||t.includes(`list`)||t.includes(`recyclerview`)}function ga(e){let t=De(e);if(!t||t!==e.identifier?.trim()||!va(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 _a(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||/^(true|false|\d+)$/.test(t)?null:t}function va(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function ya(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 ba(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 xa(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 Sa=[`button`,`switch`,`checkbox`,`radio`],Ca=[`button`,`image`,`textview`,`view`];function wa(e,t,n){for(let r of e){if(t.has(r.index)||!Da(r))continue;let i=Oa(ba(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)xa(e,n,t)}}}function Ta(e,t,n){let r=new Map;for(let i of e){if(t.has(i.index)||!Ia(i))continue;let a=_a(ga(i));if(!a)continue;let o=r.get(a);if(o&&Na(o,i,t)){let s=Pa(e,o,i,t,n);r.set(a,s);continue}r.set(a,i)}}function Ea(e,t){for(let n of e){if(t.has(n.index)||!ja(n))continue;let r=_a(ga(n));if(!r)continue;let i=ba(e,n.index).filter(e=>!t.has(e.index)&&Ma(n,e,r));for(let n of i.filter(Aa))xa(e,n.index,t);let a=i.filter(e=>!Aa(e)),o=new Set(a.map(e=>_a(ga(e))).filter(e=>!!e));if(!(a.length<2||o.size<2))for(let n of a)xa(e,n.index,t)}}function Da(e){return e.hittable===!0&&!ma(e)&&!!(e.rect&&ua(e.rect))&&ga(e).trim().length===0}function Oa(e,t,n){let r=[],i=[],a=new Set;for(let o of e){if(n.has(o.index)||!ka(o,e)||!da(o.rect,t.rect))continue;let s=ga(o).trim().replaceAll(/\s+/g,` `),c=_a(s);i.push(o.index),!(!s||!c||a.has(c))&&(a.add(c),r.push(s))}return{label:r.join(`, `),removableIndexes:i}}function ka(e,t){if(Aa(e))return!0;let n=(e.type??``).toLowerCase();return e.hittable!==!0&&!ma(e)&&n.includes(`view`)&&ga(e).trim().length>0&&!t.some(t=>t.parentIndex===e.index)}function Aa(e){if(e.hittable===!0||ma(e))return!1;let t=(e.type??``).toLowerCase();return t.includes(`text`)||t.includes(`image`)||t.includes(`icon`)}function ja(e){return e.hittable===!0&&!ma(e)&&!!(e.rect&&ua(e.rect))&&!!_a(ga(e))}function Ma(e,t,n){if(!Ia(t)||!da(t.rect,e.rect))return!1;let r=_a(ga(t));return!!(r&&n!==r&&n.includes(r))}function Na(e,t,n){return!n.has(e.index)&&fa(e.rect,t.rect)&&(Va(e,t)||Ba(e,t))}function Pa(e,t,n,r,i){let a=La(t,n),o=a.index===t.index?n:t,s=(o.type??``).toLowerCase().includes(`image`)?`has image`:null,c=i.get(a.index)??a,ee=i.get(o.index)?.presentationHints??o.presentationHints;return i.set(a.index,{...c,presentationHints:Fa(c.presentationHints,ee,s)}),xa(e,o.index,r),i.get(a.index)??a}function Fa(e,t,n){return[...new Set([...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...n?[n]:[]])]}function Ia(e){if(!e.rect||!ua(e.rect)||pa(e)||ma(e))return!1;let t=(e.type??``).toLowerCase();return t===`text`||za(t,Ca)}function La(e,t){let n=Ra(e);return Ra(t)>n?t:e}function Ra(e){let t=(e.type??``).toLowerCase(),n=0;return za(t,Sa)?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 za(e,t){return t.some(t=>e.includes(t))}function Ba(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:La(n,r).index===n.index}function Va(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 Ha(e,t,n){if(n.raw||!Ua(e))return{nodes:t,filteredCount:0};let r=Wa(t);return{nodes:r,filteredCount:t.length-r.length}}function Ua(e){let t=e.androidSnapshot;return!t||typeof t!=`object`?!1:t.backend===`android-helper`}function Wa(e){if(e.length===0)return e;let t=new Set,n=new Map,r=new Map(e.map(e=>[e.index,e]));return Ga(e,t),Ka(e,r,t,n),wa(e,t,n),Ea(e,t),Ta(e,t,n),e.filter(e=>!t.has(e.index)).map(e=>n.get(e.index)??e)}function Ga(e,t){for(let n of e)!n.rect||ua(n.rect)||pa(n)||xa(e,n.index,t)}function Ka(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||pa(i))continue;let a=ya(i,t,ha);a&&Ja(r,a,qa(i,e)),xa(e,i.index,n)}}function qa(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&ua(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 Ja(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 Ya(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??``).toLowerCase(),r=Xa(De(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||!Qa(e)||(n+=e.length);return n>=8}function Xa(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||Za(t)?null:t}function Za(e){return/\S+@\S+\.\S+/.test(e)}function Qa(e){for(let t=0;t<e.length;t+=1)for(let n=t+1;n<e.length;n+=1)if($a(e[t]?.rect,e[n]?.rect))return!0;return!1}function $a(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 eo(e,n={}){let r=e.nodes,a=Array.isArray(r)?r:[],o=i(e.backend)?e.backend:void 0,s=t(o),c=Ha(e,a,n),ee=io(e),te=mo(e,a,n,c),ne=te.length>0?`${te.join(`
4
- `)}\n`:``,re=n.raw?null:to(e);if(re)return`${ee}${ne}${no(re)}\n`;let ie=n.raw||!s?null:Kt(c.nodes),ae=!!e.truncated,oe=ie?.nodes??a,se=n.raw||!s?null:uo(e,ie,oe.length,a.length,c.filteredCount),l=ao(a.length,se,ae);return a.length===0?`${ee}${l}\n${ne}`:n.raw?`${ee}${l}\n${ne}${oo(a)}\n`:n.flatten?`${ee}${l}\n${ne}${so(oe)}${lo(ie)}\n`:`${ee}${l}\n${ne}${co(oe)}${lo(ie)}\n`}function to(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 no(e){let t=ro(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(`
1
+ import{D as e,M as t,N as n,O as r,T as i,g as a,p as o,t as s,x as c}from"./sdk-contracts.js";import{a as ee,d as te,f as ne,m as re,n as ie,p as ae,t as oe,u as se}from"./capture.js";import{_ as l,c as ce,d as le,f as ue,k as de,l as fe,m as pe,p as me,s as he,u as ge}from"./sdk-batch-runner.js";import{t as _e}from"./viewport.js";import{a as ve,i as ye,n as be,t as xe}from"./sdk-device.js";import{a as Se,c as Ce}from"./lease-scope.js";import{An as we,Cr as Te,In as Ee,Mn as De,Nr as Oe,Rr as ke,_r as Ae,d as je,dr as Me,ei as Ne,fr as Pe,h as Fe,hr as Ie,i as Le,ln as Re,m as ze,s as Be,sn as Ve,ur as He}from"./sdk-batch.js";import{n as Ue}from"./recording-export-quality.js";import{t as We}from"./recording-scope.js";import{a as Ge,n as Ke,o as qe,r as Je,s as Ye}from"./scroll-gesture.js";import{E as Xe,T as Ze,b as Qe,v as $e,w as et}from"./script.js";import{a as tt,i as nt,r as rt}from"./vars.js";import{n as it,r as at,t as ot}from"./format.js";import{n as u,t as st}from"./catalog.js";import{i as ct,r as lt,t as ut}from"./back-mode.js";import{a as dt}from"./sdk-remote-config.js";import{t as ft}from"./session.js";import{a as pt,c as mt,d as ht,f as gt,g as _t,h as vt,i as yt,l as bt,n as xt,o as St,p as Ct,s as wt,t as Tt,u as Et}from"./observability.js";import{n as Dt,t as Ot}from"./success-text.js";import{a as d,i as kt,n as At,r as f}from"./output-common.js";import{t as jt}from"./alert-contract.js";import{a as Mt,i as Nt,l as Pt,o as Ft,s as It,t as Lt,u as Rt,x as zt}from"./settings.js";import{t as Bt}from"./location-coordinates.js";import{t as Vt}from"./snapshot-quality-backend-capabilities.js";import{f as Ht,m as Ut,p as Wt,r as Gt,s as Kt}from"./overlay.js";import{t as qt}from"./mobile-snapshot-semantics.js";import{t as Jt}from"./click-button.js";import{n as Yt}from"./scroll-command.js";import{n as Xt,t as Zt}from"./interaction-positionals.js";import{t as Qt}from"./app-inventory.js";import"./device.js";import{a as $t,f as en,i as tn,m as nn,o as rn,p as an,r as on,t as sn}from"./device-rotation.js";import"./app-inventory-contract.js";import{t as cn}from"./prepare-kind.js";import{n as ln,t as un}from"./path-resolution.js";import"./file.js";import{n as dn,r as fn,s as pn,t as mn}from"./tv-remote.js";import p from"node:path";import hn from"node:fs";const gn=[`path`,`start`,`stop`,`doctor`,`mark`,`clear`],_n=new Set(lt().map(e=>e.key));function vn(t){let n=Se(t);return de({stateDir:t.stateDir,daemonBaseUrl:t.daemonBaseUrl,daemonTransport:t.daemonTransport,daemonServerMode:t.daemonServerMode,...Ce(n),provider:t.provider,providerSessionId:t.providerSessionId,providerApp:t.providerApp,providerOsVersion:t.providerOsVersion,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,a),...se(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,readinessTimeoutMs:t.readinessTimeoutMs,pixels:t.pixels,until:t.until,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 yn(e,t){return{...vn(e),...t}}function bn(e,t){let n=e.inputSchema.properties;if(!n)return{};let r={},i=t;for(let e of Object.keys(n)){if(!_n.has(e))continue;let t=i[e];xn(t)&&(r[e]=t)}return r}function xn(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`}function Sn(e){return{kind:`operator`,source:e}}function Cn(e,t){return`${e} is not accepted as a tool argument. ${wn(e,t)}`}function wn(e,t){if(`operatorPath`in t)return t.operatorPath;let n=`for the process serving these tools.`,r=(t.envFlagKeys??[e]).map(dt).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 Tn(e){if(e==null)return{};if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected object arguments.`);return e}function En(e,t){let r=e[t];if(!r||typeof r!=`object`||Array.isArray(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be an object.`);return r}function Dn(e,t){let r=e[t];if(typeof r!=`string`||r.length===0)throw new n(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return r}function On(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`string`)throw new n(`INVALID_ARGS`,`Expected ${t} to be a string.`);return r}}function m(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`string`||r.length===0)throw new n(`INVALID_ARGS`,`Expected ${t} to be a non-empty string.`);return r}}function kn(e,t){let r=e[t];if(typeof r!=`number`||!Number.isFinite(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be a finite number.`);return r}function An(e,t){let r=e[t];if(r!==void 0){if(typeof r!=`boolean`)throw new n(`INVALID_ARGS`,`Expected ${t} to be a boolean.`);return r}}function jn(e,t,r){let i=e[t];if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected ${t} to be one of: ${r.join(`, `)}.`);return i}function Mn(e,t,r){let i=e[t];if(i!==void 0){if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected ${t} to be one of: ${r.join(`, `)}.`);return i}}function Nn(e,t){let r=e[t];if(r!==void 0){if(!r||typeof r!=`object`||Array.isArray(r))throw new n(`INVALID_ARGS`,`Expected ${t} to be an object.`);return r}}function Pn(e,t){let r=e[t];if(r!==void 0){if(!Array.isArray(r)||r.some(e=>typeof e!=`string`))throw new n(`INVALID_ARGS`,`Expected ${t} to be an array of strings.`);return r}}function Fn(e,t,r,i){let a=new Set(t),o=Object.keys(e).filter(e=>!a.has(e));if(o.length>0)throw new n(`INVALID_ARGS`,`${r} has unknown field(s): ${o.join(`, `)}.`,i===void 0?void 0:{hint:i})}function h(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}const In=Sn({operatorConfig:!0}),Ln={session:{schema:{type:`string`,description:`Agent-device session name.`},read:e=>m(e,`session`),flagKey:`session`,flagIn:[`input`]},platform:{schema:{type:`string`,enum:ye,description:`Platform selector used to resolve a device.`},read:e=>Mn(e,`platform`,ye),flagKey:`platform`,flagIn:[`input`,`selection`]},deviceTarget:{schema:{type:`string`,enum:be,description:`Device target form. Maps to the CLI --target flag.`},read:Un,clientKey:`target`,flagKey:`target`,flagIn:[`input`,`selection`]},target:{schema:{type:`string`,enum:be,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=>m(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=>m(e,`udid`),flagKey:`udid`,flagIn:[`input`,`selection`]},serial:{schema:{type:`string`,description:`Android, HarmonyOS, or Vega VVD serial selector.`},read:e=>m(e,`serial`),flagKey:`serial`,flagIn:[`input`,`selection`]},iosSimulatorDeviceSet:{schema:{type:`string`,description:`iOS simulator device-set path used for device resolution.`},read:e=>m(e,`iosSimulatorDeviceSet`),audience:Sn({envFlagKeys:[],operatorConfig:!0}),flagKey:`iosSimulatorDeviceSet`,flagIn:[`input`,`selection`]},iosXctestrunFile:{schema:{type:`string`,description:`Externally built iOS XCTest runner .xctestrun artifact path.`},read:e=>m(e,`iosXctestrunFile`),audience:In,flagKey:`iosXctestrunFile`,flagIn:[`input`]},iosXctestDerivedDataPath:{schema:{type:`string`,description:`Derived data path for external iOS XCTest runner execution.`},read:e=>m(e,`iosXctestDerivedDataPath`),audience:In,flagKey:`iosXctestDerivedDataPath`,flagIn:[`input`]},iosXctestEnvDir:{schema:{type:`string`,description:`Writable directory for iOS XCTest runner env overlays.`},read:e=>m(e,`iosXctestEnvDir`),audience:In,flagKey:`iosXctestEnvDir`,flagIn:[`input`]},androidDeviceAllowlist:{schema:{type:`string`,description:`Android serial allowlist used for device resolution.`},read:e=>m(e,`androidDeviceAllowlist`),flagKey:`androidDeviceAllowlist`,flagIn:[`input`,`selection`]},noRecord:{read:e=>An(e,`noRecord`),flagKey:`noRecord`,flagIn:[`input`,`selection`]},readinessTimeoutMs:{read:Wn},daemonBaseUrl:{schema:{type:`string`,description:`Remote daemon base URL.`},read:e=>m(e,`daemonBaseUrl`),audience:In},daemonAuthToken:{schema:{type:`string`,description:`Remote daemon auth token.`},read:e=>m(e,`daemonAuthToken`),audience:In},tenant:{schema:{type:`string`,description:`Remote tenant identifier.`},read:e=>m(e,`tenant`)},runId:{schema:{type:`string`,description:`Lease run identifier.`},read:e=>m(e,`runId`)},leaseId:{schema:{type:`string`,description:`Existing lease identifier.`},read:e=>m(e,`leaseId`)},cwd:{schema:{type:`string`,description:`Working directory for command execution.`},read:e=>m(e,`cwd`),audience:Sn({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=>An(e,`debug`)}},Rn=Object.entries(Ln),zn=Object.fromEntries(Rn.flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]));function Bn(){return Object.fromEntries(Rn.flatMap(([e,t])=>t.schema?[[e,t.schema]]:[]))}function Vn(e,t={}){let n={};for(let[r,i]of Rn)i.read&&(n[r]=i.read(e,t));return n}function g(e){let t={};for(let[n,r]of Rn)r.read&&(t[r.clientKey??n]=e[n]);return h(t)}function Hn(e,t){let n={};for(let[r,i]of Rn){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 Un(e,t){let r=Mn(e,`deviceTarget`,be);if(t.readTargetAlias===!1||e.target===void 0)return r;let i=Mn(e,`target`,be);if(r!==void 0&&i!==r)throw new n(`INVALID_ARGS`,`Expected target alias to match deviceTarget when both are set.`);return r??i}function Wn(e,t){if(!(t.readinessBudgetDeclared===!0||!Object.hasOwn(e,`readinessTimeoutMs`)))throw new n(`INVALID_ARGS`,`readinessTimeoutMs applies only to commands that wait for their target: press, click, and longpress.`)}function _(e,t){return n=>v(e,t?t(n):[],n)}function v(e,t,n,r){return{command:e,positionals:t,...r?{input:r}:{},options:Gn(n)}}function Gn(e){let t=Kn(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 Kn(e){return e===`mobile`||e===`tv`||e===`desktop`?e:void 0}function y(e){return h(Hn(e,`input`))}function qn(e){return h({record:e.record})}function Jn(e){return Hn(e,`selection`)}function Yn(e){return h({depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw})}function Xn(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function Zn(e){return h({settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs})}function Qn(e){return h({count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap})}function $n(e){if(`ref`in e&&e.ref!==void 0)return h({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 er(e){let t=nr(e);if(typeof t.ref==`string`)return[t.ref,...ir(t.label)];if(typeof t.selector==`string`)return[t.selector];if(t.kind===`point`||t.x!==void 0||t.y!==void 0)return[String(rr(t.x,`x`)),String(rr(t.y,`y`))];throw new n(`INVALID_ARGS`,`interaction requires @ref, selector, or point target`)}function tr(e){let t=nr(e);if(typeof t.ref==`string`)return[t.ref,...ir(t.label)];if(typeof t.selector==`string`)return[t.selector];throw new n(`INVALID_ARGS`,`element command requires @ref or selector target`)}function nr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected target object.`);let t=e,r=t.target;return r&&typeof r==`object`&&!Array.isArray(r)?r:t}function rr(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw new n(`INVALID_ARGS`,`point target requires numeric ${t}.`);return e}function ir(e){return typeof e==`string`&&e.length>0?[e]:[]}function ar(e){let t=Me(e);if(!t.ok)throw new n(t.code,t.message);return`ref`in t?{ref:t.ref,label:lr(e.slice(1))}:{selector:t.selector}}function or(e){let t=Pe(e);if(!t.ok)throw new n(t.code,t.message);return t.format}function sr(e,t={}){let r=Te(e,t);if(!r)throw new n(`INVALID_ARGS`,He);return r}function cr(e,t){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}throw new n(`INVALID_ARGS`,`${t} must be a JSON object`)}function lr(e){return e.join(` `).trim()||void 0}function b(...e){return new Set(e)}function x(e,t){return e!==void 0&&t.has(e)}function ur(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function dr(e,t){if(e===void 0)return;let r=Number(e);if(Number.isFinite(r))return r;throw new n(`INVALID_ARGS`,`${t} must be a finite number.`)}function fr(e){return e===void 0?void 0:Number(e)}function S(e){return e===void 0?[]:[e]}function C(e){return e===void 0?[]:[String(e)]}function w(e,t){if(e===void 0||e===``)throw new n(`INVALID_ARGS`,t);return e}function T(e,t){if(typeof e!=`string`||e.length===0)throw new n(`INVALID_ARGS`,t);return e}function pr(e){return gr(e.description,e.cliDetail)}function mr(e){return gr(e.description,e.mcpDetail)}function hr(e,t){return{...e,description:t}}function gr(e,t){return t?`${e} ${t}`:e}function _r(e){return e}const vr=[`ref`,`selector`,`point`];function yr(e,t=[]){return{type:`object`,properties:{...Bn(),...e},...t.length>0?{required:t}:{},additionalProperties:!1}}function E(e,t=[],n){return{type:`object`,...n?{description:n}:{},properties:e,...t.length>0?{required:t}:{}}}function br(e){return{type:`object`,description:e,properties:{x:{type:`number`},y:{type:`number`}},required:[`x`,`y`],additionalProperties:!1}}function D(e,t){return{type:`string`,enum:e,...t?{description:t}:{}}}function O(e){return{type:`string`,const:e}}function k(e){return{type:`string`,...e?{description:e}:{}}}function xr(e){return{type:[`string`,`null`],...e?{description:e}:{}}}function A(e,t={}){return{type:`number`,...e?{description:e}:{},...t.min===void 0?{}:{minimum:t.min},...t.max===void 0?{}:{maximum:t.max}}}function Sr(e){return{type:`integer`,...e?{description:e}:{}}}function j(e){return{type:`boolean`,...e?{description:e}:{}}}function Cr(e){return{type:`array`,items:{type:`string`},...e?{description:e}:{}}}function M(e){return{type:`object`,additionalProperties:!0,...e?{description:e}:{}}}function N(e){return{...e,required:!0}}function P(e,t={}){return B(k(e),t.allowEmpty===!0?On:m)}function wr(e){return{schema:{type:`null`},required:!1,audience:{kind:`retired`,message:e},read:(t,r)=>{if(Object.hasOwn(t,r))throw new n(`INVALID_ARGS`,e)}}}function Tr(e,t){return{...e,audience:{kind:`operator`,source:t}}}function F(e,t={}){return B(A(e,t),(e,n)=>pe(e,n,t))}function I(e,t={}){return B(qr(e,t),(e,n)=>me(e,n,t))}function L(e){return B(j(e),An)}function Er(e){return Or(Dr(e))}function Dr(e){let[t,...n]=ct(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 Or(e){let t=e.inputDescription,n={min:e.min,max:e.max};switch(e.type){case`boolean`:return L(t);case`int`:return I(t,n);case`number`:return F(t,n);case`string`:return P(t);case`enum`:return R(kr(e),t);case`booleanOrString`:throw Error(`Flag ${e.key} is booleanOrString; declare its field shape explicitly with jsonSchemaField`)}}function kr(e){let t=e.enumValues;if(!t)throw Error(`Flag ${e.key} is an enum with no enumValues`);return t}function R(e,t){return B(D(e,t),(t,n)=>Mn(t,n,e))}function Ar(e){return B(M(e),Nn)}function jr(e){return B(Cr(e),Pn)}function z(e){return B(e,(e,t)=>e[t])}function Mr(e,t){return B(e,t)}function Nr(){return B(Zr(),(e,t)=>e[t]===void 0?void 0:Br(e,t))}function Pr(){return B(Qr(),(e,t)=>e[t]===void 0?void 0:Vr(e,t))}function Fr(e){return B(br(e),(e,t)=>e[t]===void 0?void 0:Hr(e,t))}function Ir(){return{depth:I(`Snapshot traversal depth.`,{min:0}),scope:P(`Snapshot scope selector used before resolution.`),raw:L(`Use raw snapshot data during selector resolution.`)}}function Lr(){return{count:I(`Number of press/click repetitions.`,{min:1}),intervalMs:I(`Delay between repeated press/click actions.`,{min:0}),holdMs:I(`Hold duration for each action.`,{min:0}),jitterPx:I(`Randomization radius in pixels.`,{min:0}),doubleTap:L(`Request a double-tap action.`)}}function Rr(e){return yr(Jr(e),Yr(e))}function zr(e,t){let r=Tn(e),i=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{let i=t.read(r,e);if(t.required&&i===void 0)throw new n(`INVALID_ARGS`,`Expected ${e} to be set.`);return i===void 0?[]:[[e,i]]})),a=Vn(r,{readTargetAlias:!Object.hasOwn(t,`target`),readinessBudgetDeclared:Object.hasOwn(t,`readinessTimeoutMs`)});return h({...a,...g(a),...i})}function Br(e,t){let n=En(e,t),r=jn(n,`kind`,vr);switch(r){case`ref`:return{kind:r,ref:Dn(n,`ref`),label:m(n,`label`)};case`selector`:return{kind:r,selector:Dn(n,`selector`)};case`point`:return{kind:r,x:kn(n,`x`),y:kn(n,`y`)}}}function Vr(e,t){let n=En(e,t),r=jn(n,`kind`,[`ref`,`selector`]);return r===`ref`?{kind:r,ref:Dn(n,`ref`),label:m(n,`label`)}:{kind:r,selector:Dn(n,`selector`)}}function Hr(e,t){let n=En(e,t);return{x:kn(n,`x`),y:kn(n,`y`)}}function Ur(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 Wr(e){switch(e.kind){case`ref`:return{ref:e.ref,label:e.label};case`selector`:return{selector:e.selector}}}function Gr(e){return{count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap}}function Kr(e){return{depth:e.depth,scope:e.scope,raw:e.raw}}function B(e,t){return{schema:e,required:!1,read:t}}function qr(e,t){return{...Sr(e),...t.min===void 0?{}:{minimum:t.min},...t.max===void 0?{}:{maximum:t.max}}}function Jr(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.audience?.kind!==`retired`).map(([e,t])=>[e,t.schema]))}function Yr(e){return Object.entries(e).flatMap(([e,t])=>t.required?[e]:[])}function Xr(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>t.audience?[[e,t.audience]]:[]))}function Zr(){return{oneOf:[...$r(),{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 Qr(){return{oneOf:$r(),description:`UI element target by snapshot ref or selector expression.`}}function $r(){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 V(e,t,n,r){return _r({name:e,description:t,inputSchema:Rr(n),readInput:r?.readInput??(e=>zr(e,n)),inputAudience:Xr(n),...r?.parseableOutput?{parseableOutput:!0}:{}})}function H(e){let t=hr(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 ei(e){return H({name:e.name,text:e.text,metadata:V(e.name,e.description,{}),run:e.run,cliSchema:{},cliReader:(e,t)=>y(t),daemonWriter:_(e.name),cliOutputFormatter:e.cliOutputFormatter})}function U(e){let t={},n={},r={},i={};for(let a of e.commands)ti(t,`CLI schema`,a.name,a.cliSchema),ti(n,`CLI reader`,a.name,a.cliReader),a.daemonWriter&&ti(r,`daemon writer`,a.name,a.daemonWriter),a.cliOutputFormatter&&ti(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 ti(e,t,n,r){if(Object.hasOwn(e,n))throw Error(`Duplicate command family ${t}: ${n}`);e[n]=r}function ni(e){let t=[`Batch completed: ${e.executed}/${e.total} steps in ${e.totalDurationMs}ms`];for(let n of e.results)t.push(ii(n));return{data:e,text:t.join(`
2
+ `)}}const ri={batch:d(ni)};function ii(e){let t=Ot(e.data)??e.command;return`${e.step}. OK ${t} (${e.durationMs}ms)`}function ai(e=Le){let t=oi(e);return V(`batch`,`Execute multiple commands in one daemon request.`,t,{readInput:e=>ci(e,t)})}function oi(e){return{steps:N(Mr({type:`array`,description:`Structured batch steps. Each step uses a command name and the same input object as that command tool.`,items:si(e)},(t,n)=>li(t[n],e))),onError:R([`stop`],`Batch failure policy.`),maxSteps:I(`Maximum number of steps accepted for this batch.`,{min:1,max:1e3}),out:P(`Optional output path for command artifacts.`)}}function si(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 ci(e,t){let r=zr(e,t),i=r.maxSteps??100;if(!fe(i))throw new n(`INVALID_ARGS`,`Invalid batch maxSteps: ${String(r.maxSteps)}`);return ce(r.steps.length,i),{...r}}function li(e,t){if(!Array.isArray(e))throw new n(`INVALID_ARGS`,`Expected steps to be an array.`);return e.map((e,n)=>ui(e,n+1,t))}function ui(e,t,n){let r=ue(e,t);return Fn(r,[`command`,`input`,`runtime`],`Batch step ${t}`,he),{command:di(r,t,n),input:le(r,t),...fi(r,t)}}function di(e,t,r){if(r===Le)return Be(e.command,t);let i=e.command;if(typeof i!=`string`||!r.includes(i))throw new n(`INVALID_ARGS`,`Expected command to be one of: ${r.join(`, `)}.`);return i}function fi(e,t){let n=ge(e.runtime,t);return n===void 0?{}:{runtime:n}}function pi(e){return async t=>v(u.batch,[],{...t,batchSteps:await mi(t.steps,e),batchOnError:t.onError,batchMaxSteps:t.maxSteps})}async function mi(e,t){if(!Array.isArray(e)||e.length===0)throw new n(`INVALID_ARGS`,`batch requires a non-empty steps array.`);let r=[];for(let[n,i]of e.entries())r.push(await hi(i,n+1,t));return r}async function hi(e,t,n){let r=ue(e,t),i=gi(r,t),a=le(r,t),o=ge(r.runtime,t),s=await n(i,a,t);return{command:s.command,positionals:s.positionals,...s.input?{input:s.input}:{},flags:yn(s.options,s.metadataFlags),runtime:o??s.options.runtime}}function gi(e,t){return Be(e.command,t)}const _i=ai(),vi={usageOverride:`batch [--steps <json> | --steps-file <path>]`,usageFlags:[],listUsageOverride:`batch --steps <json> | --steps-file <path>`,allowedFlags:[`steps`,`stepsFile`,`batchOnError`,`batchMaxSteps`,`out`]},yi=(e,t)=>({...y(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out}),bi=[{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 xi(){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: ${[...Le].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(bi)}'`,` agent-device batch --steps-file ./steps.json --json`].join(`
3
+ `)}`}const Si=U({name:`batch`,clientSurface:!1,commands:[H({name:`batch`,text:{summary:`Run multiple commands`,cliDetail:xi()},metadata:_i,run:(e,t)=>e.batch.run(Ci(t)),cliSchema:vi,cliReader:yi,cliOutputFormatter:ri.batch})]});function Ci(e){return{...g(e),steps:e.steps,onError:e.onError,maxSteps:e.maxSteps,out:e.out}}const wi=`alert`,Ti=H({name:wi,text:{summary:`Inspect, accept, or dismiss a platform alert`},metadata:V(wi,`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. Inspect again after an unconfirmed action; never assume a timeout means nothing happened.`,{action:R(jt),timeoutMs:I()}),run:(e,t)=>e.command.alert(t),cliSchema:{usageOverride:`alert [get|accept|dismiss|wait] [timeout]`,positionalArgs:[`action?`,`timeout?`]},cliReader:(e,t)=>({...y(t),...Di(e)}),daemonWriter:_(u.alert,e=>Ei(e)),cliOutputFormatter:f});function Ei(e){return[e.action??`get`,...C(e.timeoutMs)]}function Di(e){if(e.length>2)throw new n(`INVALID_ARGS`,`alert accepts at most action and timeout arguments.`);return h({action:Oi(e[0]),timeoutMs:dr(e[1],`alert timeout`)})}function Oi(e){let t=e?.toLowerCase();if(t===void 0||t===`get`||t===`accept`||t===`dismiss`||t===`wait`)return t;throw new n(`INVALID_ARGS`,`alert action must be get, accept, dismiss, or wait.`)}function W(...e){return e}const ki=W(`keyframes`),Ai=W(`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`),ji=W(`snapshotDepth`,`snapshotScope`,`snapshotRaw`),Mi=W(`metroProjectRoot`,`kind`,`metroKind`,`metroPublicBaseUrl`,`metroProxyBaseUrl`,`metroBearerToken`,`metroPreparePort`,`metroListenHost`,`metroStatusHost`,`metroStartupTimeoutMs`,`metroProbeTimeoutMs`,`metroRuntimeFile`,`metroNoReuseExisting`,`metroNoInstallDeps`),Ni=W(`metroHost`,`metroPort`,`bundleUrl`),Pi=W(`count`,`intervalMs`,`holdMs`,`jitterPx`,`doubleTap`),Fi=W(`settle`,`settleQuietMs`,`timeoutMs`),Ii=W(`replayUpdate`,`replayEnv`),Li=W(`remoteConfig`,`stateDir`,`daemonBaseUrl`,`daemonAuthToken`,`daemonTransport`,`daemonServerMode`,`tenant`,`sessionIsolation`,`runId`,`leaseId`,`leaseBackend`,`sessionLock`,`platform`,`target`,`device`,`providerApp`,`providerOsVersion`,`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`),Ri=new Set([`platform`,`device`,`udid`,`serial`,`session`]),zi=new Set([`json`,`config`,`help`,`version`,`verbose`,`cost`,`responseLevel`]),Bi=`diff`,Vi={diff:E({mode:O(`snapshot`),baselineInitialized:j(),summary:E({additions:A(),removals:A(),unchanged:A()},[`additions`,`removals`,`unchanged`]),lines:{type:`array`,items:E({kind:D([`added`,`removed`,`unchanged`]),text:k(),ref:k()},[`kind`,`text`])},warnings:Cr()},[`mode`,`baselineInitialized`,`summary`,`lines`])},Hi=H({name:Bi,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:V(Bi,`Compare accessibility snapshots or screenshots to identify UI changes. Use snapshot comparisons for semantic tree changes and screenshot comparisons for pixel differences.`,{kind:N(z({type:`string`,const:`snapshot`})),out:P(),interactiveOnly:L(),depth:I(),scope:P(),raw:L()}),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:[...Ai,`baseline`,`threshold`,`out`,`overlayRefs`]},cliReader:(e,t)=>{if(e[0]!==`snapshot`)throw new n(`INVALID_ARGS`,`Only diff snapshot is available through this parser.`);return{...y(t),kind:`snapshot`,out:t.out,interactiveOnly:t.snapshotInteractiveOnly,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw}},daemonWriter:_(u.diff,e=>[T(e.kind,`diff requires kind`)])}),Ui=`screenshot`,Wi=H({name:Ui,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 and Android emulators), --overlay-refs to annotate current refs, --normalize-status-bar for deterministic iOS simulator chrome, or --no-stabilize for low-latency Android capture loops. 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:V(Ui,`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:P(`Output path.`),cropOn:P(`Selector expression; the capture is cropped to the frame the selector resolves on the same screen.`),overlayRefs:L(),pixelDensity:I(`Output screenshot pixel density in pixels per logical point.`,{min:1}),fullscreen:L(),scale:F(`Screenshot scale factor.`,ee),maxSize:wr(oe.migration.screenshot),stabilize:L(),normalizeStatusBar:L(),surface:R(ft)}),run:(e,t)=>e.capture.screenshot(t),cliSchema:{positionalArgs:[`path?`],allowedFlags:ie},cliReader:(e,t)=>({...y(t),path:e[0]??t.out,...ne(t)}),daemonWriter:e=>(ae(`screenshot`,e),re(e),v(u.screenshot,S(e.path),{...e,...te(e)}))}),Gi=`settings`,Ki=V(Gi,`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:N(P()),state:P(),app:P(),latitude:F(),longitude:F(),permission:P(),mode:R([...It])}),qi={usageOverride:Rt,listUsageOverride:`settings [area] [options]`,positionalArgs:[`setting`,`state?`,`target?`,`mode?`]},Ji=(e,t)=>Zi(e,t),Yi=_(u.settings,e=>Qi(e)),Xi=H({name:Gi,text:{summary:`Change OS settings and app permissions`,cliDetail:`macOS supports only settings appearance <light|dark|toggle> and settings ${Pt}; wifi|airplane|location|animations|text-size remain unsupported on macOS. Mobile permission actions use the active session app. On Android, deny|reset of a permission the app currently holds kills a running app; the response reports priorGrantState (granted|not_granted|unknown) and warns for granted and unknown, with open <app> --relaunch to restore it. Permission changes require a resolvable foreground user and fail without mutating if adb cannot report one. Android settings airplane on|off is applied by the connectivity service (Android 11+) and reports the airplaneMode that service holds; older builds fail without changing device state. settings reset-keychain clear is iOS-simulator-only and resets the whole simulator keychain, not just the selected app: simctl exposes no per-app keychain reset, so every app on that simulator loses its keychain-backed credentials (e.g. Firebase auth). clear-app-state does not touch the keychain, so a full fresh-install reset needs both; relaunch the app afterward to observe the signed-out state. settings text-size reads the preferred text size the target holds and settings text-size <category> applies one, on iPhone and iPad simulators (simctl content size) and on Android targets (system font_scale); tvOS and visionOS simulators, physical Apple devices, and the macOS host refuse it. Android has no category ladder of its own, so the read names the nearest rung and reports the exact multiplier as platformValue; an already-running app adopts a changed size at its next configuration change, so relaunch the app under test to observe it.`},metadata:Ki,run:(e,t)=>e.settings.update(t),cliSchema:qi,cliReader:Ji,daemonWriter:Yi,cliOutputFormatter:f});function Zi(e,t){let r=Jn(t),i=e[0],a=e[1];if(x(i,ta)&&x(a,na))return{...r,setting:i,state:a};if(i===`location`&&a===`set`)return{...r,setting:i,state:a,latitude:Bt(e[2],`latitude`),longitude:Bt(e[3],`longitude`)};if(i===`appearance`&&x(a,ra))return{...r,setting:i,state:a};if(i===`text-size`)return a===void 0?{...r,setting:i}:{...r,setting:i,state:zt(a)};if(x(i,ia)&&x(a,aa)||i===`fingerprint`&&x(a,oa))return{...r,setting:i,state:a};if(i===`permission`&&x(a,ca))return{...r,setting:i,state:a,permission:$i(e[2]),mode:ea(e[3])};if(i===`clear-app-state`){let t=a===`clear`?e[2]:a;return{...r,setting:i,state:`clear`,app:t}}if(i===`reset-keychain`&&a===`clear`&&e.length===2)return{...r,setting:i,state:a};throw new n(`INVALID_ARGS`,`Invalid settings arguments.`)}function Qi(e){return e.setting===`clear-app-state`?[e.setting,...S(e.app)]:e.setting===`text-size`?[e.setting,...S(e.state)]:e.setting===`location`&&e.state===`set`?[e.setting,e.state,String(e.latitude),String(e.longitude)]:e.setting===`permission`?[e.setting,e.state,e.permission,...S(e.mode)]:[e.setting,e.state]}function $i(e){if(x(e,la))return e;throw new n(`INVALID_ARGS`,`settings permission requires a permission target.`)}function ea(e){if(e===void 0||x(e,sa))return e;throw new n(`INVALID_ARGS`,`settings permission mode must be full or limited.`)}const ta=b(`wifi`,`airplane`,`location`,`animations`),na=b(`on`,`off`),ra=b(...Lt),ia=b(`faceid`,`touchid`),aa=b(`match`,`nonmatch`,`enroll`,`unenroll`),oa=b(`match`,`nonmatch`),sa=b(...It),ca=b(...Ft),la=b(...Mt,...Nt);function ua(e){if(!Array.isArray(e)||e.length===0)return e;let t=ke(e);return e.map(e=>{let n=da(e,t,e=>e.label),r=da(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 da(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 fa(e){return e.width>0&&e.height>0}function pa(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 ma(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 ha(e){return typeof e.parentIndex!=`number`}function ga(e){let t=(e.type??``).toLowerCase(),n=(e.identifier??``).trim().toLowerCase();return t.includes(`edittext`)||t.includes(`textfield`)||n===`composer`}function _a(e){let t=(e.type??``).toLowerCase();return t.includes(`scroll`)||t.includes(`list`)||t.includes(`recyclerview`)}function va(e){let t=Oe(e);if(!t||t!==e.identifier?.trim()||!ba(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 ya(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||/^(true|false|\d+)$/.test(t)?null:t}function ba(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function xa(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 Sa(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 Ca(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 wa=[`button`,`switch`,`checkbox`,`radio`],Ta=[`button`,`image`,`textview`,`view`];function Ea(e,t,n){for(let r of e){if(t.has(r.index)||!ka(r))continue;let i=Aa(Sa(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)Ca(e,n,t)}}}function Da(e,t,n){let r=new Map;for(let i of e){if(t.has(i.index)||!Ra(i))continue;let a=ya(va(i));if(!a)continue;let o=r.get(a);if(o&&Fa(o,i,t)){let s=Ia(e,o,i,t,n);r.set(a,s);continue}r.set(a,i)}}function Oa(e,t){for(let n of e){if(t.has(n.index)||!Na(n))continue;let r=ya(va(n));if(!r)continue;let i=Sa(e,n.index).filter(e=>!t.has(e.index)&&Pa(n,e,r));for(let n of i.filter(Ma))Ca(e,n.index,t);let a=i.filter(e=>!Ma(e)),o=new Set(a.map(e=>ya(va(e))).filter(e=>!!e));if(!(a.length<2||o.size<2))for(let n of a)Ca(e,n.index,t)}}function ka(e){return e.hittable===!0&&!ga(e)&&!!(e.rect&&fa(e.rect))&&va(e).trim().length===0}function Aa(e,t,n){let r=[],i=[],a=new Set;for(let o of e){if(n.has(o.index)||!ja(o,e)||!pa(o.rect,t.rect))continue;let s=va(o).trim().replaceAll(/\s+/g,` `),c=ya(s);i.push(o.index),!(!s||!c||a.has(c))&&(a.add(c),r.push(s))}return{label:r.join(`, `),removableIndexes:i}}function ja(e,t){if(Ma(e))return!0;let n=(e.type??``).toLowerCase();return e.hittable!==!0&&!ga(e)&&n.includes(`view`)&&va(e).trim().length>0&&!t.some(t=>t.parentIndex===e.index)}function Ma(e){if(e.hittable===!0||ga(e))return!1;let t=(e.type??``).toLowerCase();return t.includes(`text`)||t.includes(`image`)||t.includes(`icon`)}function Na(e){return e.hittable===!0&&!ga(e)&&!!(e.rect&&fa(e.rect))&&!!ya(va(e))}function Pa(e,t,n){if(!Ra(t)||!pa(t.rect,e.rect))return!1;let r=ya(va(t));return!!(r&&n!==r&&n.includes(r))}function Fa(e,t,n){return!n.has(e.index)&&ma(e.rect,t.rect)&&(Ua(e,t)||Ha(e,t))}function Ia(e,t,n,r,i){let a=za(t,n),o=a.index===t.index?n:t,s=(o.type??``).toLowerCase().includes(`image`)?`has image`:null,c=i.get(a.index)??a,ee=i.get(o.index)?.presentationHints??o.presentationHints;return i.set(a.index,{...c,presentationHints:La(c.presentationHints,ee,s)}),Ca(e,o.index,r),i.get(a.index)??a}function La(e,t,n){return[...new Set([...Array.isArray(e)?e:[],...Array.isArray(t)?t:[],...n?[n]:[]])]}function Ra(e){if(!e.rect||!fa(e.rect)||ha(e)||ga(e))return!1;let t=(e.type??``).toLowerCase();return t===`text`||Va(t,Ta)}function za(e,t){let n=Ba(e);return Ba(t)>n?t:e}function Ba(e){let t=(e.type??``).toLowerCase(),n=0;return Va(t,wa)?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 Va(e,t){return t.some(t=>e.includes(t))}function Ha(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:za(n,r).index===n.index}function Ua(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 Wa(e,t,n){if(n.raw||!Ga(e))return{nodes:t,filteredCount:0};let r=Ka(t);return{nodes:r,filteredCount:t.length-r.length}}function Ga(e){let t=e.androidSnapshot;return!t||typeof t!=`object`?!1:t.backend===`android-helper`}function Ka(e){if(e.length===0)return e;let t=new Set,n=new Map,r=new Map(e.map(e=>[e.index,e]));return qa(e,t),Ja(e,r,t,n),Ea(e,t,n),Oa(e,t),Da(e,t,n),e.filter(e=>!t.has(e.index)).map(e=>n.get(e.index)??e)}function qa(e,t){for(let n of e)!n.rect||fa(n.rect)||ha(n)||Ca(e,n.index,t)}function Ja(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||ha(i))continue;let a=xa(i,t,_a);a&&Xa(r,a,Ya(i,e)),Ca(e,i.index,n)}}function Ya(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&fa(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 Xa(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 Za(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??``).toLowerCase(),r=Qa(Oe(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 Qa(e){let t=e.trim().replaceAll(/\s+/g,` `).toLowerCase();return!t||$a(t)?null:t}function $a(e){return/\S+@\S+\.\S+/.test(e)}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,n={}){let r=e.nodes,a=Array.isArray(r)?r:[],o=i(e.backend)?e.backend:void 0,s=t(o),c=Wa(e,a,n),ee=oo(e),te=go(e,a,n,c),ne=te.length>0?`${te.join(`
4
+ `)}\n`:``,re=n.raw?null:ro(e);if(re)return`${ee}${ne}${io(re)}\n`;let ie=n.raw||!s?null:qt(c.nodes),ae=!!e.truncated,oe=ie?.nodes??a,se=n.raw||!s?null:po(e,ie,oe.length,a.length,c.filteredCount),l=so(a.length,se,ae);return a.length===0?`${ee}${l}\n${ne}`:n.raw?`${ee}${l}\n${ne}${co(a)}\n`:n.flatten?`${ee}${l}\n${ne}${lo(oe)}${fo(ie)}\n`:`${ee}${l}\n${ne}${uo(oe)}${fo(ie)}\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
5
  `):e.interactiveOnly?[`Interactive snapshot unchanged since previous read ${t} ago.`,`${e.nodeCount} visible nodes are unchanged. Previous @e refs are still valid. Use find/get/is for a targeted query, or --force-full to re-emit.`].join(`
6
6
  `):[`Snapshot unchanged since previous read ${t} ago.`,`Refs from the previous snapshot are still valid. Use --force-full to re-emit the tree, or use find/get/is for a targeted query.`].join(`
7
- `)}function ro(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 io(e){let t=typeof e.appName==`string`?e.appName:void 0,n=typeof e.appBundleId==`string`?e.appBundleId:void 0,r=[];return t&&r.push(`Page: ${t}`),n&&r.push(`App: ${n}`),r.length>0?`${r.join(`
8
- `)}\n`:``}function ao(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 oo(e){return e.map(e=>JSON.stringify(e)).join(`
9
- `)}function so(e){return Co(e).join(`
10
- `)}function co(e){return bo(Vt(e,{summarizeTextSurfaces:!0})).join(`
11
- `)}function lo(e){return e&&e.summaryLines.length>0?`\n${e.summaryLines.join(`
12
- `)}`:``}function uo(e,t,n,r,i=0){let a=fo(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:po([...a?.reasons??[],`offscreen-nodes`])}:a||(s?{partial:!0,visibleNodeCount:n,totalNodeCount:n,reasons:[]}:null)}function fo(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 po(e){return[...new Set(e)]}function mo(e,t,n,r={nodes:t,filteredCount:0}){let i=[...yo(e),...ho(e)];if(go(e)){let e=vo(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&&Ya(a)&&i.push(`Warning: possible repeated nav subtree detected.`),i}function ho(e){let t=e.fallbackScreenshotPath;return typeof t==`string`&&t.length>0?[`Captured a screenshot of this screen automatically as visual truth: ${t}`]:[]}function go(e){return!e.snapshotQuality&&!_o(e)}function _o(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 vo(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 yo(e){return Et(e).filter(e=>e.length>0)}function bo(e){let t=[],n=[],r=new Map(e.map(e=>[e.node.index,e.node])),i=e=>{for(;n.length>0&&(!e||xo(e,n.at(-1),r));)t.push(...wo(n.pop(),`below`))};for(let r of e)i(r),t.push(r.text),t.push(...wo(r,`above`)),r.node.hiddenContentBelow&&n.push(r);return i(),t}function xo(e,t,n){return!So(e.node,t.node,n)&&e.depth<=t.depth}function So(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 Co(e){return Vt(e,{summarizeTextSurfaces:!0}).flatMap(e=>[Ht(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...wo({...e,depth:0})])}function wo(e,t){let n=To(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 To(e){return e===`scroll-area`||e===`list`||e===`collection`||e===`table`?e:null}async function Eo(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:ca(e.result.nodes)});return{data:n,jsonData:Oo(n),stderr:e.result.snapshotDiagnostics?.warning?`${e.result.snapshotDiagnostics.warning}\n`:void 0,text:eo(n,{raw:e.raw,flatten:e.interactiveOnly,scoped:typeof e.scope==`string`&&e.scope.trim().length>0,depthLimited:typeof e.depth==`number`})}}const Do={snapshot:async({input:e,result:t})=>await Eo({result:t,raw:e.raw,interactiveOnly:e.interactiveOnly,scope:e.scope,depth:e.depth}),wait:f,alert:f};function Oo(e){let{unchanged:t,...n}=e;return n}const ko=`snapshot`,Ao=Object.entries(Bt).map(([e,t])=>{let n=t.knownGaps.map(e=>`known gap ${e}`);return`${e}: hittable=${t.hittable}, regular-depth=${t.regularDepth}, deep-extension=${t.deepExtension}, depth-ladder=${t.depthLadder}${n.length>0?`, ${n.join(`, `)}`:``}`}).join(`; `),jo=V(ko,`Capture the accessibility tree or compare it with the previous session baseline. Use the returned refs for subsequent semantic interactions and the diff option to verify UI changes.`,{interactiveOnly:L(),depth:I(),scope:P(),raw:L(),customActions:wr(`snapshotCustomActions`),forceFull:L(),timeoutMs:I(`Maximum wall-clock time for the snapshot command.`),noRecord:L(`Do not record this action.`),record:L(`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.`)}),Mo={allowedFlags:[`snapshotDiff`,...Oi,`snapshotCustomActions`,`snapshotForceFull`,`timeoutMs`,`record`]},No=(e,t)=>({...y(t),...Gn(t),...r(t,a),timeoutMs:t.timeoutMs}),Po=_(u.snapshot),Fo=H({name:ko,text:{summary:`Capture or diff the accessibility tree`,cliDetail:`Repeated equivalent unfiltered Android snapshots return a compact unchanged acknowledgement. Use --force-full to re-emit the tree; --json and --raw retain full output. 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: ${Ao}.`},metadata:jo,run:(e,t)=>e.capture.snapshot(t),cliSchema:Mo,cliReader:No,daemonWriter:Po,cliOutputFormatter:Do.snapshot}),Io=[`duration`,`text`,`ref`,`selector`,`absent`,`stable`],Lo=`wait`,Ro={wait:E({waitedMs:A(),kind:O(`selector`),text:k(),selector:k(),captures:A(),nodeCount:A(),hint:k(),warning:k()},[`waitedMs`])},zo=H({name:Lo,text:{summary:`Wait for a duration, text, selector, strict absence, or stable UI`},metadata:V(Lo,`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:R(Io),durationMs:I(),text:P(),ref:P(),selector:P(),absent:P(),stable:L(),quietMs:I(),timeoutMs:I(),depth:I(),scope:P(),raw:L()}),run:(e,t)=>e.command.wait(Bo(t)),cliSchema:{usageOverride:`wait <ms>|text <text>|@ref|<selector>|absent <selector> [timeoutMs]|stable [quietMs] [timeoutMs]`,usageFlags:[],positionalArgs:[`durationOrSelector`,`timeoutMs?`],allowsExtraPositionals:!0,allowedFlags:[...ki]},cliReader:(e,t)=>Vo(e,t),daemonWriter:_(u.wait,e=>Wo(e)),cliOutputFormatter:f});function Bo(e){jn(e,`kind`,Io);let t={...e};return delete t.kind,t}function Vo(e,t){let r=Re(e);if(!r)throw new n(`INVALID_ARGS`,`wait requires <ms>, text <text>, @ref, <selector> [timeoutMs], absent <selector> [timeoutMs], or stable [quietMs] [timeoutMs].`);let i={...Kn(t),...Jn(t)};switch(r.kind){case`absent`:return Ho(i,r);case`sleep`:return{...i,durationMs:r.durationMs};case`text`:return Uo(i,r);case`ref`:return{...i,ref:r.rawRef,...Go(r.timeoutMs)};case`stable`:return{...i,stable:!0,...Ko(r.quietMs),...Go(r.timeoutMs)};case`invalid`:throw new n(`INVALID_ARGS`,r.message);case`selector`:return{...i,selector:r.selectorExpression,...Go(r.timeoutMs)};default:return qo(r)}}function Ho(e,t){let n=Gt(e);if(n)throw Wt(n,`wait`);return{...e,absent:t.selectorExpression,...Go(t.timeoutMs)}}function Uo(e,t){if(!t.text)throw new n(`INVALID_ARGS`,`wait requires text.`);return{...e,text:t.text,...Go(t.timeoutMs)}}function Wo(e){if([e.durationMs===void 0?void 0:`durationMs`,e.text===void 0?void 0:`text`,e.ref===void 0?void 0:`ref`,e.selector===void 0?void 0:`selector`,e.absent===void 0?void 0:`absent`,e.stable===void 0?void 0:`stable`].filter(Boolean).length!==1)throw new n(`INVALID_ARGS`,`wait command requires exactly one of durationMs, text, ref, selector, absent, or stable.`);if(e.durationMs!==void 0)return[String(e.durationMs)];let t=C(e.timeoutMs);if(e.text!==void 0)return[`text`,e.text,...t];if(e.ref!==void 0)return[e.ref,...t];if(e.absent!==void 0){let r=Gt(e);if(r)throw Wt(r,`wait`);if(!ke(e.absent))throw new n(`INVALID_ARGS`,`Invalid wait absent selector: ${e.absent}`);return[`absent`,e.absent,...t]}if(e.stable!==void 0){let r=C(e.quietMs);if(r.length===0&&t.length>0)throw new n(`INVALID_ARGS`,`wait stable requires quietMs before timeoutMs.`);return[`stable`,...r,...t]}let r=e.selector;if(!ke(r))throw new n(`INVALID_ARGS`,`Invalid wait selector: ${r}`);return[r,...t]}function Go(e){return e===null?{}:{timeoutMs:e}}function Ko(e){return e===null?{}:{quietMs:e}}function qo(e){throw Error(`Unsupported wait positional target: ${String(e)}`)}const Jo=U({name:`capture`,commands:[Fo,Hi,Bi,zo,Ci,Ji]});function Yo(e){let t=[e.outPath,e.message];t.push(...Zo(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(`
13
- `)}}const Xo={debug:d(Yo)};function Zo(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 Qo=`debug`,$o=U({name:`debugging`,commands:[H({name:Qo,text:{summary:`Symbolicate Apple crash artifacts`},metadata:V(Qo,`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 profiles.`,{action:N(R([`symbols`])),artifact:N(P(`Apple crash artifact path (.ips, .crash, or .log).`)),dsym:P(`Path to a matching .dSYM bundle.`),searchPath:P(`Directory to scan for matching .dSYM bundles.`),out:P(`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)=>({...y(t),action:es(e[0]),artifact:t.artifact,dsym:t.dsym,searchPath:t.searchPath,out:t.out}),cliOutputFormatter:Xo.debug})]});function es(e){if(e===`symbols`)return e;throw new n(`INVALID_ARGS`,`debug supports only symbols; use logs, network, perf, record, trace, or react-devtools for other diagnostics`)}const ts=()=>L(`Capture cheap post-action evidence (AX digest, node counts, changedFromBefore) instead of a follow-up snapshot.`),ns=()=>({settle:L(`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:I(`Settle: quiet window in milliseconds (default 500).`,{min:0}),timeoutMs:I(`Settle: wait deadline in milliseconds (default 10000).`,{min:1})});function rs(e){return{...Ie(e)?{verify:ts()}:{},...ze(e)?ns():{}}}function is(e){let t=[];return Ie(e)&&t.push(`verify`),ze(e)&&t.push(...Ni),t}function as(e,t){return ze(e)?Yn(t):{}}const os=[`click`,`focus`,`exists`,`list`,`getText`,`getAttrs`,`wait`,`fill`,`type`],ss={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; use settle or verify to confirm the result without a follow-up snapshot.`,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.`,fill:`Replace text in a UI input selected by snapshot ref, selector, or coordinates. Pass an empty text to clear the field. 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`,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.`},cs={target:N(jr()),button:R(qt,`Pointer button for platforms that support mouse buttons.`),...Pr(),...Fr(),...rs(`click`)},ls={target:N(jr()),...Pr(),...Fr(),...rs(`press`)},us={target:N(jr()),text:N(P(`Text to enter into the target. Pass "" to clear it.`,{allowEmpty:!0})),delayMs:I(`Delay between typed characters.`,{min:0}),recordAs:P("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."),...Pr(),...rs(`fill`)},ds={target:N(jr()),durationMs:I(`Long press duration in milliseconds.`,{min:0}),...Pr(),...rs(`longpress`)},fs={target:N(jr()),...Pr(),...rs(`hover`)},ps={from:N(Nr(`Swipe start point.`)),to:N(Nr(`Swipe end point.`)),count:I(`Number of swipe repetitions.`,{min:1,max:200}),pauseMs:I(`Pause between repeated swipes.`,{min:0,max:Ke}),pattern:R(We)},ms={x:N(F(`X coordinate.`)),y:N(F(`Y coordinate.`))},hs={text:N(P(`Text to type.`)),delayMs:I(`Delay between typed characters.`,{min:0})},gs={direction:N(R(qe)),amount:F(`Platform scroll amount.`),pixels:I(`Pixel scroll amount.`,{min:0}),until:P(`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.`),durationMs:I(`Scroll duration in milliseconds when the backend supports pacing.`,{min:0,max:Jt}),...rs(`scroll`)},_s=()=>({noRecord:L(`Do not record this action.`),record:L(`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.`)}),vs={format:N(R([`text`,`attrs`])),target:N(Mr()),...Pr(),..._s()},ys={predicate:N(R(we)),selector:N(P()),value:P(),...Pr(),..._s()},bs={locator:R(Pe),query:N(P()),action:R(os),value:P(void 0,{allowEmpty:!0}),timeoutMs:I(),first:L(),last:L(),depth:I(),raw:L(),..._s()},xs={kind:N(R(Xe,`Gesture variant.`)),direction:R(Ge,`Fling direction.`),preset:R(Je,`Swipe preset.`),origin:Nr(`Gesture origin point.`),delta:Nr(`Movement delta for pan or transform gestures.`),distance:I(`Fling distance.`,{min:0}),scale:F(`Pinch or transform scale.`),degrees:F(`Rotation in degrees.`),durationMs:I(`Pan/transform duration.`,{min:16,max:1e4}),pointerCount:I(`Pan touch pointer count (1 or 2).`,{min:1,max:2}),source:P(`Drag source @ref or selector.`),destination:P(`Drag destination @ref or selector.`),sourceHoldMs:I(`Drag activation hold duration.`,{min:1,max:1e4}),moveMs:I(`Drag movement duration.`,{min:16,max:1e4}),destinationHoldMs:I(`Hold before releasing at the destination.`,{min:0,max:1e4})},Ss=[G(`click`,cs),G(`press`,ls),G(`fill`,us),G(`longpress`,ds),G(`hover`,fs),G(`swipe`,ps),G(`focus`,ms),G(`type`,hs),G(`scroll`,gs),G(`get`,vs,{parseableOutput:!0}),G(`is`,ys),G(`find`,bs,{parseableOutput:!0}),V(`gesture`,ss.gesture,xs,{readInput:Cs})];function Cs(e){let t=wn(e);return{...Bn(t),...Ye(t)}}function G(e,t,n){return V(e,ss[e],t,n)}const ws={gesture:Es},Ts={gesture:e=>{let t=Cs(e);return v(u.gesture,[],e,h(t))}};function Es(e,t){return{...y(t),...Ze(e,t.pointerCount)}}const K={click:(e,t)=>({...y(t),...qn(t),...Xn(t),target:Zn(Yt(e)),button:t.clickButton,verify:t.verify}),press:(e,t)=>({...y(t),...qn(t),...Xn(t),target:Zn(Yt(e)),verify:t.verify}),longpress:(e,t)=>{let n=Ds(e);return{...y(t),...qn(t),target:Zn(n),durationMs:n.durationMs}},hover:(e,t)=>({...y(t),...qn(t),target:Zn(Yt(e))}),swipe:(e,t)=>({...y(t),...$e(e,{count:t.count,pauseMs:t.pauseMs,pattern:t.pattern})}),focus:(e,t)=>({...y(t),x:Number(e[0]),y:Number(e[1])}),type:(e,t)=>({...y(t),text:e.join(` `),delayMs:t.delayMs}),fill:(e,t)=>{let n=Xt(e);return{...y(t),...qn(t),target:Zn(n.target),text:n.text,delayMs:t.delayMs,recordAs:t.recordAs,verify:t.verify}},scroll:(e,t)=>({...y(t),direction:js(e[0]),amount:ur(e[1]),pixels:t.pixels,durationMs:t.durationMs,until:t.until}),get:(e,t)=>({...y(t),...Gn(t),...qn(t),format:ir(e[0]),target:Zn(rr(e.slice(1)))})},q={click:e=>v(u.click,Qn(e),{...e,clickButton:e.button}),press:_(u.press,e=>Qn(e)),longpress:_(u.longPress,e=>Os(e)),hover:_(u.hover,e=>Qn(e)),swipe:e=>(Qe(e),v(u.swipe,[],e,{from:e.from,to:e.to,count:e.count,pauseMs:e.pauseMs,pattern:e.pattern})),focus:_(u.focus,e=>[String(e.x),String(e.y)]),type:_(u.type,e=>ks(e)),fill:_(u.fill,e=>As(e)),scroll:_(u.scroll,e=>[T(e.direction,`scroll requires direction`),...C(e.amount)]),get:_(u.get,e=>[T(e.format,`get requires format`),...$n(e)])};function Ds(e){let t=Ms(e);return{...Yt(t.target),...t.durationMs===void 0?{}:{durationMs:t.durationMs}}}function Os(e){return[...Qn(e),...C(e.durationMs)]}function ks(e){return[e.text]}function As(e){return[...Qn(e),e.text]}function js(e){if(e===`up`||e===`down`||e===`left`||e===`right`||e===`top`||e===`bottom`)return e;throw new n(`INVALID_ARGS`,`Unknown direction: ${String(e)}`,{hint:`scroll takes a direction first, then an optional amount: scroll <up|down|left|right|top|bottom> [amount]. It takes no @ref or selector — scroll the whole viewport, then retry the target with a selector.`})}function Ms(e){if(cr(e[0])&&cr(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&&cr(t)?{target:e.slice(0,-1),durationMs:Number(t)}:{target:e}}function Ns(e){return({input:t,result:n})=>{let r=e({input:t,result:n});return r instanceof Promise?r.then(Ps):Ps(r)}}function Ps(e){return{data:e.data,text:Is(e.text,e.data)}}function Fs(e){let t={...e};for(let[n,r]of Object.entries(e))ze(n)&&(t[n]=Ns(r));return t}function Is(e,t){return`${e??``}${Ls(t.settle)}`}function Ls(e){if(!e||typeof e!=`object`)return``;let t=e,n=[Vs(t),...Rs(t),...Bs(t)];return t.hint&&n.push(`hint: ${t.hint}`),`\n${n.join(`
14
- `)}`}function Rs(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=Ot(e.ref,t);if(!r||!e.ref)return n;let i=`@${e.ref}`;return n.startsWith(`${i} `)?`${r}${n.slice(i.length)}`:n}function Bs(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=Ot(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 Vs(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 Hs(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 Us(e){let t=e,n=Dt(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:Ws(t.matches,t.refsGeneration)};let r=Ot(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)}:kt(t)}function Ws(e,t){return[`${e.length} match${e.length===1?``:`es`}:`,...e.map(e=>Gs(e,t))].join(`
15
- `)}function Gs(e,t){let n=e.ref??``,r=n.startsWith(`@`)?n.slice(1):n,i=Ot(n,t)??`@${r}`,a=c(e.node?.type??`Element`),o=e.node?Ut(e.node,a):``;return`= ${i} [${a}]${o?` "${o}"`:``}`}function Ks(e){let t=e;return{data:t,text:`Passed: is ${t.predicate??`assertion`}`}}function qs(e){let t=e,n=t.ref??``,r=t.x,i=t.y;return!n||typeof r!=`number`||typeof i!=`number`?kt(t):{data:t,text:`Tapped @${n} (${r}, ${i})`}}const J=Fs({click:d(qs),press:d(qs),fill:f,longpress:f,hover:f,scroll:f,get:({input:e,result:t})=>Hs({result:t,format:e.format===`attrs`?`attrs`:`text`}),is:d(Ks),find:d(Us)}),Js={find:(e,t)=>Qs(e,t),is:(e,t)=>$s(e,t)},Ys={is:_(u.is,e=>Xs(e)),find:e=>v(u.find,Zs(e),{...e,findFirst:e.first,findLast:e.last})};function Xs(e){return[e.predicate,e.selector,...e.predicate===`text`?[e.value]:[]]}function Zs(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`,...C(e.timeoutMs)];case`fill`:case`type`:return[...t,e.action,e.value]}}function Qs(e,t){let r={...rc(t),...Kn(t),...Gn(t),first:t.findFirst,last:t.findLast},i=nc(e[0]),a=i!==void 0,o=a?e[1]:e[0],s=a?2:1,c=Te(e[s]);if(c===void 0)return{...r,locator:i,query:ic(o)};if(c===`get`){let t=e[s+1];if(t===`text`)return{...r,locator:i,query:ic(o),action:`getText`};if(t===`attrs`)return{...r,locator:i,query:ic(o),action:`getAttrs`};throw new n(`INVALID_ARGS`,`find get only supports text or attrs`)}if(c===`wait`)return{...r,locator:i,query:ic(o),action:`wait`,timeoutMs:ur(e[s+1])};if(c===`fill`||c===`type`){let t=e.slice(s+1);if(t.length===0)throw new n(`INVALID_ARGS`,c===`fill`?`find fill requires text (use "" to clear the field)`:`find type requires text`);return{...r,locator:i,query:ic(o),action:c,value:t.join(` `)}}if(c===`click`||c===`focus`||c===`exists`||c===`list`)return{...r,locator:i,query:ic(o),action:c};throw new n(`INVALID_ARGS`,`Unsupported find action: ${e[s]}`,{hint:Ne})}function $s(e,t){let r={...Jn(t),...Kn(t),...Gn(t)},i=je(e),a=Le(i[0]??``);if(!a.ok)throw new n(a.code,a.message,{hint:a.hint});let o=a.predicate;if(o===`absent`){let e=ec(r);if(e)throw tc(e)}let s=ar(i.slice(1),{preferTrailingValue:o===`text`});return o===`text`?{...r,predicate:o,selector:s.selectorExpression,value:s.rest.join(` `)}:{...r,predicate:o,selector:s.selectorExpression}}function ec(e){if(e.scope!==void 0)return`scope`;if(e.depth!==void 0)return`depth`}function tc(e){return new n(`INVALID_ARGS`,e===`scope`?`is absent does not support --scope; it requires an unscoped capture`:`is absent does not support --depth; it requires a full-depth capture`,{command:`is`,predicate:`absent`,rejectedOption:e})}function nc(e){if(e===`text`||e===`label`||e===`value`||e===`role`||e===`id`)return e}function rc(e){return{depth:e.snapshotDepth,raw:e.snapshotRaw}}function ic(e){if(e===void 0||e===``)throw new n(`INVALID_ARGS`,`find requires query`);return e}const ac=E({from:k(`Surface the pre-action baseline described: a host bundle id, or app.`),to:k(`Surface the post-action capture describes: a host bundle id, or app.`),disclosure:k(`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.`),oc=E({foregroundApp:k(`Foreground app bundle id or name, when the capture carries it.`),nodeCount:A(`Node count in the post-action interactive-only capture.`),interactiveNodeCount:A(`Subset of nodeCount the platform reports as hittable.`),digest:k(`Order-independent digest of the post-action node multiset.`),changedFromBefore:j(`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:ac},[`nodeCount`,`interactiveNodeCount`,`digest`,`changedFromBefore`]),sc=E({wallClockMs:A(`Total wall-clock time for the request in milliseconds.`),runnerRoundTrips:A(`Number of real runner round-trips made while serving the request.`),nodeCount:A(`Number of nodes in the original node tree when the response carries one.`)},[`wallClockMs`,`runnerRoundTrips`]),cc=E({diagnosticRef:k(`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:k(`UTF-8 truncated to 256 bytes.`),label:k(`UTF-8 truncated to 256 bytes.`)},[`diagnosticRef`]),lc={type:`object`,description:`Pre-action disclosure of how the acting path resolved its target. Absent when resolutionDisclosure is inapplicable for the path.`,oneOf:[E({source:O(`runtime`),phase:O(`pre-action`),kind:O(`unique`)},[`source`,`phase`,`kind`]),E({source:O(`runtime`),phase:O(`pre-action`),kind:O(`disambiguated`),matchCount:A(`Total matches resolveSelectorChain found before disambiguation.`),winnerDiagnostic:cc,tiebreak:D([`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:cc}},[`source`,`phase`,`kind`,`matchCount`,`winnerDiagnostic`,`tiebreak`]),E({source:O(`ref`),phase:O(`pre-action`),kind:O(`exact`)},[`source`,`phase`,`kind`]),E({source:O(`ref`),phase:O(`pre-action`),kind:O(`label-fallback`)},[`source`,`phase`,`kind`]),E({source:O(`direct-ios`),kind:O(`not-observed`)},[`source`,`kind`])]};function uc(e={}){let t=e.properties??{},n=e.required??[];return E({targetKind:D([`point`,`ref`,`selector`],`Resolved interaction target kind.`),x:A(`Resolved interaction x coordinate when available.`),y:A(`Resolved interaction y coordinate when available.`),referenceWidth:A(`Reference frame width for visualizing the interaction point.`),referenceHeight:A(`Reference frame height for visualizing the interaction point.`),ref:k(`Snapshot ref without the @ prefix when the target was an @ref.`),selector:k(`Selector expression when the target was a selector.`),selectorChain:xr(),refLabel:k(),targetHittable:j(),hint:k(),warning:k(),message:k(),evidence:oc,resolution:lc,cost:sc,maestroNonHittableCoordinateFallbackAllowed:j(`Whether the direct iOS Maestro coordinate fallback was allowed for this selector.`),maestroNonHittableCoordinateFallbackUsed:j(`Whether the direct iOS Maestro coordinate fallback was actually used.`),maestroFallbackReason:O(`non-hittable-coordinate`),...t},[`targetKind`,...n])}const dc=uc({properties:{evidence:oc,button:D([`secondary`,`middle`]),count:A(`Number of press/click repetitions.`),intervalMs:A(`Delay between repeated press/click actions.`),holdMs:A(`Hold duration for each action.`),jitterPx:A(`Randomization radius in pixels.`),doubleTap:j(`Whether the command requested a double-tap action.`)}}),fc={text:k(`Text submitted to the field.`),delayMs:A(`Delay between typed characters in milliseconds.`),evidence:oc},pc=E({resourceId:yr(`Android resource id of the exact field that changed.`),className:yr(`Android class name of the exact field that changed.`),packageName:yr(`Android package name that owns the exact field.`),rect:E({x:A(),y:A(),width:A(),height:A()},[`x`,`y`,`width`,`height`],`Screen-space rectangle of the exact field that changed.`)},[`resourceId`,`className`,`packageName`,`rect`],`Target identity captured before fill and matched after fill.`),mc={press:dc,click:dc,fill:{type:`object`,description:`Fill response. Android may return target-bound unconfirmed evidence when the exact app-owned field changed but formatting prevented raw equality.`,oneOf:[{...uc({properties:fc,required:[`text`]}),not:E({},[`verification`])},uc({properties:{...fc,verification:O(`unconfirmed`),requested:k(`Literal text requested by the fill command.`),before:yr(`Raw target text captured before the fill.`),after:yr(`Raw target text captured after the fill.`),target:pc},required:[`text`,`verification`,`requested`,`before`,`after`,`target`]})]},longpress:uc({properties:{durationMs:A(),gesture:O(`longpress`)}}),hover:uc({properties:{gesture:O(`hover`)}}),find:E({ref:k(`Snapshot ref without the @ prefix when the find action returns one.`),refsGeneration:A(`ADR 0014 ref frame epoch for read-only find actions.`),found:j(`Whether a wait/exists/read-only find satisfied its condition.`),waitedMs:A(`Milliseconds waited for a read-only find condition.`),text:k(`Text value returned by find get_text.`),node:M(`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:M(`One listed match with its snapshot ref and node.`)},locator:k(`Locator kind used for the find action.`),query:k(`Query argument used for the find action.`),x:A(`Resolved x coordinate for mutating find actions.`),y:A(`Resolved y coordinate for mutating find actions.`),message:k(`Diagnostic message for mutating find actions.`),cost:sc},[],`Daemon response data for the find command.`)},Y={get:{usageOverride:`get text|attrs <@ref|selector>`,usageFlags:[],positionalArgs:[`subcommand`,`target`],allowsExtraPositionals:!0,allowedFlags:[...ki,`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:[...ki,`record`]},click:{usageOverride:`click <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`target`],allowsExtraPositionals:!0,allowedFlags:[...Mi,`clickButton`,...is(`click`),...ki]},press:{usageOverride:`press <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...Mi,...is(`press`),...ki]},longpress:{usageOverride:`longpress <x y|@ref|selector> [durationMs]`,usageFlags:[],positionalArgs:[`targetOrX`,`yOrDurationMs?`,`durationMs?`],allowsExtraPositionals:!0,allowedFlags:[...is(`longpress`),...ki]},hover:{usageOverride:`hover <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...is(`hover`),...ki]},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>`,usageFlags:[],positionalArgs:[`targetOrX`,`yOrText`,`text?`],allowsExtraPositionals:!0,allowedFlags:[...ki,`delayMs`,`recordAs`,...is(`fill`)]},scroll:{usageOverride:`scroll <direction|top|bottom> [amount]`,usageFlags:[`until`,`pixels`,`durationMs`,`settle`],positionalArgs:[`directionOrEdge`,`amount?`],allowedFlags:[`pixels`,`durationMs`,`until`,...is(`scroll`)]}},hc=U({name:`interaction`,clientSurface:!1,commands:[H({name:`click`,text:{summary:`Click or tap a UI target`},metadata:X(`click`),run:(e,t)=>e.interactions.click(gc(t)),cliSchema:Y.click,cliReader:K.click,daemonWriter:q.click,cliOutputFormatter:J.click}),H({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(_c(t)),cliSchema:Y.press,cliReader:K.press,daemonWriter:q.press,cliOutputFormatter:J.press}),H({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".`},metadata:X(`fill`),run:(e,t)=>e.interactions.fill(vc(t)),cliSchema:Y.fill,cliReader:K.fill,daemonWriter:q.fill,cliOutputFormatter:J.fill}),H({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(yc(t)),cliSchema:Y.longpress,cliReader:K.longpress,daemonWriter:q.longpress,cliOutputFormatter:J.longpress}),H({name:`hover`,text:{summary:`Hover the pointer over a UI target (web only)`,cliDetail:`The pointer stays where hover left it: read the revealed UI (--settle or snapshot -i) and act on it before another click or hover moves the pointer away.`},metadata:X(`hover`),run:(e,t)=>e.interactions.hover(bc(t)),cliSchema:Y.hover,cliReader:K.hover,daemonWriter:q.hover,cliOutputFormatter:J.hover}),H({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}),H({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}),H({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}),H({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}),H({name:`get`,text:{summary:`Read element text or attributes`},metadata:X(`get`),run:(e,t)=>e.interactions.get(Sc(t)),cliSchema:Y.get,cliReader:K.get,daemonWriter:q.get,cliOutputFormatter:J.get}),H({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:Js.is,daemonWriter:Ys.is,cliOutputFormatter:J.is}),H({name:`find`,text:{summary:`Find an element and act`},metadata:X(`find`),run:(e,t)=>e.interactions.find(t),cliSchema:Y.find,cliReader:Js.find,daemonWriter:Ys.find,cliOutputFormatter:J.find}),H({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(Cc(t));case`fling`:return await e.interactions.fling(Tc(t));case`swipe`:return await e.interactions.swipeGesture(Ec(t));case`pinch`:return await e.interactions.pinch(Dc(t));case`rotate`:return await e.interactions.rotateGesture(Oc(t));case`transform`:return await e.interactions.transformGesture(kc(t));case`drag`:return await e.interactions.drag(wc(t))}},cliSchema:Y.gesture,cliReader:ws.gesture,daemonWriter:Ts.gesture})]});function X(e){let t=Ss.find(t=>t.name===e);if(!t)throw Error(`Missing interaction command metadata for ${e}`);return t}function gc(e){return{...g(e),...Vr(e.target),...Wr(e),...Ur(e),button:e.button,verify:e.verify,...xc(e)}}function _c(e){return{...g(e),...Vr(e.target),...Wr(e),...Ur(e),verify:e.verify,...xc(e)}}function vc(e){return{...g(e),...Vr(e.target),...Wr(e),text:e.text,delayMs:e.delayMs,recordAs:e.recordAs,verify:e.verify,...xc(e)}}function yc(e){return{...g(e),...Vr(e.target),...Wr(e),durationMs:e.durationMs,...xc(e)}}function bc(e){return{...g(e),...Vr(e.target),...Wr(e),...xc(e)}}function xc(e){return{settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs}}function Sc(e){return{...g(e),...Hr(e.target),...Wr(e),format:e.format,record:e.record}}function Cc(e){return{...g(e),x:e.origin.x,y:e.origin.y,dx:e.delta.x,dy:e.delta.y,pointerCount:e.pointerCount,durationMs:e.durationMs}}function wc(e){return{...g(e),source:e.source,destination:e.destination,sourceHoldMs:e.sourceHoldMs,moveMs:e.moveMs,destinationHoldMs:e.destinationHoldMs}}function Tc(e){return{...g(e),direction:e.direction,x:e.origin.x,y:e.origin.y,distance:e.distance}}function Ec(e){return{...g(e),preset:e.preset}}function Dc(e){return{...g(e),scale:e.scale,x:e.origin?.x,y:e.origin?.y}}function Oc(e){return{...g(e),degrees:e.degrees,x:e.origin?.x,y:e.origin?.y}}function kc(e){return{...g(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 Ac(e){let{serializeDevice:t}=await import(`./result-serialization.js`).then(e=>e.t);return{data:{devices:e.map(t)},text:e.map(Wc).join(`
16
- `)}}async function jc(e){let{serializeDevice:t}=await import(`./result-serialization.js`).then(e=>e.t);return{data:{device:t(e.device),availableCommands:e.availableCommands},text:[`${Wc(e.device)} supports ${e.availableCommands.length} commands:`,e.availableCommands.join(` `)].join(`
17
- `)}}function Mc(e){return{data:{apps:e.result},stderr:e.appsFilter===`all`?`Showing all apps, including system apps.
7
+ `)}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(`
8
+ `)}\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(`
9
+ `)}function lo(e){return To(e).join(`
10
+ `)}function uo(e){return So(Ht(e,{summarizeTextSurfaces:!0})).join(`
11
+ `)}function fo(e){return e&&e.summaryLines.length>0?`\n${e.summaryLines.join(`
12
+ `)}`:``}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&&Za(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 Dt(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 Ht(e,{summarizeTextSurfaces:!0}).flatMap(e=>[Ut(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:ua(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:f,alert:f};function Ao(e){let{unchanged:t,...n}=e;return n}const jo=`snapshot`,Mo=Object.entries(Vt).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=V(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:L(),depth:I(),scope:P(),raw:L(),customActions:Er(`snapshotCustomActions`),forceFull:L(),timeoutMs:I(`Maximum wall-clock time for the snapshot command.`),noRecord:L(`Do not record this action.`),record:L(`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`,...Ai,`snapshotCustomActions`,`snapshotForceFull`,`timeoutMs`,`record`]},Fo=(e,t)=>({...y(t),...qn(t),...r(t,a),timeoutMs:t.timeoutMs}),Io=_(u.snapshot),Lo=H({name:jo,text:{summary:`Capture or diff the accessibility tree`,cliDetail:`Repeated equivalent unfiltered Android snapshots return a compact unchanged acknowledgement. Use --force-full to re-emit the tree; --json and --raw retain full output. 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:E({waitedMs:A(),kind:O(`selector`),text:k(),selector:k(),captures:A(),nodeCount:A(),hint:k(),warning:k()},[`waitedMs`])},Vo=H({name:zo,text:{summary:`Wait for a duration, text, selector, strict absence, or stable UI`},metadata:V(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:R(Ro),durationMs:I(),text:P(),ref:P(),selector:P(),absent:P(),stable:L(),quietMs:I(),timeoutMs:I(),depth:I(),scope:P(),raw:L()}),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:[...ji]},cliReader:(e,t)=>Uo(e,t),daemonWriter:_(u.wait,e=>Ko(e)),cliOutputFormatter:f});function Ho(e){Mn(e,`kind`,Ro);let t={...e};return delete t.kind,t}function Uo(e,t){let r=Ve(e);if(!r)throw new n(`INVALID_ARGS`,`wait requires <ms>, text <text>, @ref, <selector> [timeoutMs], absent <selector> [timeoutMs], or stable [quietMs] [timeoutMs].`);let i={...Jn(t),...Xn(t)};switch(r.kind){case`absent`:return Wo(i,r);case`sleep`:return{...i,durationMs:r.durationMs};case`text`:return Go(i,r);case`ref`:return{...i,ref:r.rawRef,...qo(r.timeoutMs)};case`stable`:return{...i,stable:!0,...Jo(r.quietMs),...qo(r.timeoutMs)};case`invalid`:throw new n(`INVALID_ARGS`,r.message);case`selector`:return{...i,selector:r.selectorExpression,...qo(r.timeoutMs)};default:return Yo(r)}}function Wo(e,t){let n=Kt(e);if(n)throw Gt(n,`wait`);return{...e,absent:t.selectorExpression,...qo(t.timeoutMs)}}function Go(e,t){if(!t.text)throw new n(`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 n(`INVALID_ARGS`,`wait command requires exactly one of durationMs, text, ref, selector, absent, or stable.`);if(e.durationMs!==void 0)return[String(e.durationMs)];let t=C(e.timeoutMs);if(e.text!==void 0)return[`text`,e.text,...t];if(e.ref!==void 0)return[e.ref,...t];if(e.absent!==void 0){let r=Kt(e);if(r)throw Gt(r,`wait`);if(!Re(e.absent))throw new n(`INVALID_ARGS`,`Invalid wait absent selector: ${e.absent}`);return[`absent`,e.absent,...t]}if(e.stable!==void 0){let r=C(e.quietMs);if(r.length===0&&t.length>0)throw new n(`INVALID_ARGS`,`wait stable requires quietMs before timeoutMs.`);return[`stable`,...r,...t]}let r=e.selector;if(!Re(r))throw new n(`INVALID_ARGS`,`Invalid wait selector: ${r}`);return[r,...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=U({name:`capture`,commands:[Lo,Wi,Hi,Vo,Ti,Xi]});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(`
13
+ `)}}const Qo={debug:d(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=U({name:`debugging`,commands:[H({name:es,text:{summary:`Symbolicate Apple crash artifacts`},metadata:V(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 profiles.`,{action:N(R([`symbols`])),artifact:N(P(`Apple crash artifact path (.ips, .crash, or .log).`)),dsym:P(`Path to a matching .dSYM bundle.`),searchPath:P(`Directory to scan for matching .dSYM bundles.`),out:P(`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)=>({...y(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 n(`INVALID_ARGS`,`debug supports only symbols; use logs, network, perf, record, trace, or react-devtools for other diagnostics`)}const rs=()=>L(`Capture cheap post-action evidence (AX digest, node counts, changedFromBefore) instead of a follow-up snapshot.`),is=()=>({settle:L(`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:I(`Settle: quiet window in milliseconds (default 500).`,{min:0}),timeoutMs:I(`Settle: wait deadline in milliseconds (default 10000).`,{min:1})});function as(e){return{...Fe(e)?{verify:rs()}:{},...ze(e)?is():{}}}function os(e){let t=[];return Fe(e)&&t.push(`verify`),ze(e)&&t.push(...Fi),t}function ss(e,t){return ze(e)?Zn(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; use settle or verify to confirm the result without a follow-up snapshot.`,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.`,fill:`Replace text in a UI input selected by snapshot ref, selector, or coordinates. Pass an empty text to clear the field. 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`,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.`};function us(e){if(!je(e))throw Error(`${e} does not declare targetReadiness: 'budgeted'`);return{readinessTimeoutMs:Tr(I(`Operator-only: how long the command may poll for a target that does not exist yet, in milliseconds. Capped at the promotedTarget row's maxTimeoutMs; omitted takes the one-attempt resolution path.`,{min:1}),{operatorPath:`Pass readinessTimeoutMs directly as CLI/Node.js command input; it is not exposed to model-facing tools.`})}}const ds={target:N(Nr()),button:R(Jt,`Pointer button for platforms that support mouse buttons.`),...Ir(),...Lr(),...as(`click`),...us(`click`)},fs={target:N(Nr()),...Ir(),...Lr(),...as(`press`),...us(`press`)},ps={target:N(Nr()),text:N(P(`Text to enter into the target. Pass "" to clear it.`,{allowEmpty:!0})),delayMs:I(`Delay between typed characters.`,{min:0}),recordAs:P("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."),...Ir(),...as(`fill`)},ms={target:N(Nr()),durationMs:I(`Long press duration in milliseconds.`,{min:0}),...Ir(),...as(`longpress`),...us(`longpress`)},hs={target:N(Nr()),...Ir(),...as(`hover`)},gs={from:N(Fr(`Swipe start point.`)),to:N(Fr(`Swipe end point.`)),count:I(`Number of swipe repetitions.`,{min:1,max:200}),pauseMs:I(`Pause between repeated swipes.`,{min:0,max:qe}),pattern:R(Ge)},_s={x:N(F(`X coordinate.`)),y:N(F(`Y coordinate.`))},vs={text:N(P(`Text to type.`)),delayMs:I(`Delay between typed characters.`,{min:0})},ys={direction:N(R(Je)),amount:F(`Platform scroll amount.`),pixels:I(`Pixel scroll amount.`,{min:0}),until:P(`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.`),durationMs:I(`Scroll duration in milliseconds when the backend supports pacing.`,{min:0,max:Yt}),...as(`scroll`)},bs=()=>({noRecord:L(`Do not record this action.`),record:L(`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.`)}),xs={format:N(R([`text`,`attrs`])),target:N(Pr()),...Ir(),...bs()},Ss={predicate:N(R(Ne)),selector:N(P()),value:P(),...Ir(),...bs()},Cs={locator:R(we),query:N(P()),action:R(cs),value:P(void 0,{allowEmpty:!0}),timeoutMs:I(),first:L(),last:L(),depth:I(),raw:L(),...bs()},ws={kind:N(R(Ze,`Gesture variant.`)),direction:R(Ke,`Fling direction.`),preset:R(Ye,`Swipe preset.`),origin:Fr(`Gesture origin point.`),delta:Fr(`Movement delta for pan or transform gestures.`),distance:I(`Fling distance.`,{min:0}),scale:F(`Pinch or transform scale.`),degrees:F(`Rotation in degrees.`),durationMs:I(`Pan/transform duration.`,{min:16,max:1e4}),pointerCount:I(`Pan touch pointer count (1 or 2).`,{min:1,max:2}),source:P(`Drag source @ref or selector.`),destination:P(`Drag destination @ref or selector.`),sourceHoldMs:I(`Drag activation hold duration.`,{min:1,max:1e4}),moveMs:I(`Drag movement duration.`,{min:16,max:1e4}),destinationHoldMs:I(`Hold before releasing at the destination.`,{min:0,max:1e4})},Ts=[G(`click`,ds),G(`press`,fs),G(`fill`,ps),G(`longpress`,ms),G(`hover`,hs),G(`swipe`,gs),G(`focus`,_s),G(`type`,vs),G(`scroll`,ys),G(`get`,xs,{parseableOutput:!0}),G(`is`,Ss),G(`find`,Cs,{parseableOutput:!0}),V(`gesture`,ls.gesture,ws,{readInput:Es})];function Es(e){let t=Tn(e);return{...Vn(t),...Xe(t)}}function G(e,t,n){return V(e,ls[e],t,n)}const Ds={gesture:ks},Os={gesture:e=>{let t=Es(e);return v(u.gesture,[],e,h(t))}};function ks(e,t){return{...y(t),...Qe(e,t.pointerCount)}}const K={click:(e,t)=>({...y(t),...Yn(t),...Qn(t),target:$n(Xt(e)),button:t.clickButton,verify:t.verify}),press:(e,t)=>({...y(t),...Yn(t),...Qn(t),target:$n(Xt(e)),verify:t.verify}),longpress:(e,t)=>{let n=As(e);return{...y(t),...Yn(t),target:$n(n),durationMs:n.durationMs}},hover:(e,t)=>({...y(t),...Yn(t),target:$n(Xt(e))}),swipe:(e,t)=>({...y(t),...et(e,{count:t.count,pauseMs:t.pauseMs,pattern:t.pattern})}),focus:(e,t)=>({...y(t),x:Number(e[0]),y:Number(e[1])}),type:(e,t)=>({...y(t),text:e.join(` `),delayMs:t.delayMs}),fill:(e,t)=>{let n=Zt(e);return{...y(t),...Yn(t),target:$n(n.target),text:n.text,delayMs:t.delayMs,recordAs:t.recordAs,verify:t.verify}},scroll:(e,t)=>({...y(t),direction:Ps(e[0]),amount:fr(e[1]),pixels:t.pixels,durationMs:t.durationMs,until:t.until}),get:(e,t)=>({...y(t),...qn(t),...Yn(t),format:or(e[0]),target:$n(ar(e.slice(1)))})},q={click:e=>v(u.click,er(e),{...e,clickButton:e.button}),press:_(u.press,e=>er(e)),longpress:_(u.longPress,e=>js(e)),hover:_(u.hover,e=>er(e)),swipe:e=>($e(e),v(u.swipe,[],e,{from:e.from,to:e.to,count:e.count,pauseMs:e.pauseMs,pattern:e.pattern})),focus:_(u.focus,e=>[String(e.x),String(e.y)]),type:_(u.type,e=>Ms(e)),fill:_(u.fill,e=>Ns(e)),scroll:_(u.scroll,e=>[T(e.direction,`scroll requires direction`),...C(e.amount)]),get:_(u.get,e=>[T(e.format,`get requires format`),...tr(e)])};function As(e){let t=Fs(e);return{...Xt(t.target),...t.durationMs===void 0?{}:{durationMs:t.durationMs}}}function js(e){return[...er(e),...C(e.durationMs)]}function Ms(e){return[e.text]}function Ns(e){return[...er(e),e.text]}function Ps(e){if(e===`up`||e===`down`||e===`left`||e===`right`||e===`top`||e===`bottom`)return e;throw new n(`INVALID_ARGS`,`Unknown direction: ${String(e)}`,{hint:`scroll takes a direction first, then an optional amount: scroll <up|down|left|right|top|bottom> [amount]. It takes no @ref or selector — scroll the whole viewport, then retry the target with a selector.`})}function Fs(e){if(ur(e[0])&&ur(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&&ur(t)?{target:e.slice(0,-1),durationMs:Number(t)}:{target:e}}function Is(e){return({input:t,result:n})=>{let r=e({input:t,result:n});return r instanceof Promise?r.then(Ls):Ls(r)}}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))ze(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(`
14
+ `)}`}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=kt(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=kt(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=Ot(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=kt(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)}:At(t)}function qs(e,t){return[`${e.length} match${e.length===1?``:`es`}:`,...e.map(e=>Js(e,t))].join(`
15
+ `)}function Js(e,t){let n=e.ref??``,r=n.startsWith(`@`)?n.slice(1):n,i=kt(n,t)??`@${r}`,a=c(e.node?.type??`Element`),o=e.node?Wt(e.node,a):``;return`= ${i} [${a}]${o?` "${o}"`:``}`}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`?At(t):{data:t,text:`Tapped @${n} (${r}, ${i})`}}const J=Rs({click:d(Xs),press:d(Xs),fill:f,longpress:f,hover:f,scroll:f,get:({input:e,result:t})=>Gs({result:t,format:e.format===`attrs`?`attrs`:`text`}),is:d(Ys),find:d(Ks)}),Zs={find:(e,t)=>tc(e,t),is:(e,t)=>nc(e,t)},Qs={is:_(u.is,e=>$s(e)),find:e=>v(u.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`,...C(e.timeoutMs)];case`fill`:case`type`:return[...t,e.action,e.value]}}function tc(e,t){let r={...oc(t),...Jn(t),...qn(t),first:t.findFirst,last:t.findLast},i=ac(e[0]),a=i!==void 0,o=a?e[1]:e[0],s=a?2:1,c=Ee(e[s]);if(c===void 0)return{...r,locator:i,query:sc(o)};if(c===`get`){let t=e[s+1];if(t===`text`)return{...r,locator:i,query:sc(o),action:`getText`};if(t===`attrs`)return{...r,locator:i,query:sc(o),action:`getAttrs`};throw new n(`INVALID_ARGS`,`find get only supports text or attrs`)}if(c===`wait`)return{...r,locator:i,query:sc(o),action:`wait`,timeoutMs:fr(e[s+1])};if(c===`fill`||c===`type`){let t=e.slice(s+1);if(t.length===0)throw new n(`INVALID_ARGS`,c===`fill`?`find fill requires text (use "" to clear the field)`:`find type requires text`);return{...r,locator:i,query:sc(o),action:c,value:t.join(` `)}}if(c===`click`||c===`focus`||c===`exists`||c===`list`)return{...r,locator:i,query:sc(o),action:c};throw new n(`INVALID_ARGS`,`Unsupported find action: ${e[s]}`,{hint:De})}function nc(e,t){let r={...Xn(t),...Jn(t),...qn(t)},i=Ae(e),a=Ie(i[0]??``);if(!a.ok)throw new n(a.code,a.message,{hint:a.hint});let o=a.predicate;if(o===`absent`){let e=rc(r);if(e)throw ic(e)}let s=sr(i.slice(1),{preferTrailingValue:o===`text`});return o===`text`?{...r,predicate:o,selector:s.selectorExpression,value:s.rest.join(` `)}:{...r,predicate:o,selector:s.selectorExpression}}function rc(e){if(e.scope!==void 0)return`scope`;if(e.depth!==void 0)return`depth`}function ic(e){return new n(`INVALID_ARGS`,e===`scope`?`is absent does not support --scope; it requires an unscoped capture`:`is absent does not support --depth; it requires a full-depth capture`,{command:`is`,predicate:`absent`,rejectedOption:e})}function 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 n(`INVALID_ARGS`,`find requires query`);return e}const cc=E({from:k(`Surface the pre-action baseline described: a host bundle id, or app.`),to:k(`Surface the post-action capture describes: a host bundle id, or app.`),disclosure:k(`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=E({foregroundApp:k(`Foreground app bundle id or name, when the capture carries it.`),nodeCount:A(`Node count in the post-action interactive-only capture.`),interactiveNodeCount:A(`Subset of nodeCount the platform reports as hittable.`),digest:k(`Order-independent digest of the post-action node multiset.`),changedFromBefore:j(`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=E({wallClockMs:A(`Total wall-clock time for the request in milliseconds.`),runnerRoundTrips:A(`Number of real runner round-trips made while serving the request.`),nodeCount:A(`Number of nodes in the original node tree when the response carries one.`)},[`wallClockMs`,`runnerRoundTrips`]),dc=E({diagnosticRef:k(`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:k(`UTF-8 truncated to 256 bytes.`),label:k(`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:[E({source:O(`runtime`),phase:O(`pre-action`),kind:O(`unique`)},[`source`,`phase`,`kind`]),E({source:O(`runtime`),phase:O(`pre-action`),kind:O(`disambiguated`),matchCount:A(`Total matches resolveSelectorChain found before disambiguation.`),winnerDiagnostic:dc,tiebreak:D([`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`]),E({source:O(`ref`),phase:O(`pre-action`),kind:O(`exact`)},[`source`,`phase`,`kind`]),E({source:O(`ref`),phase:O(`pre-action`),kind:O(`label-fallback`)},[`source`,`phase`,`kind`]),E({source:O(`direct-ios`),kind:O(`not-observed`)},[`source`,`kind`])]};function pc(e={}){let t=e.properties??{},n=e.required??[];return E({targetKind:D([`point`,`ref`,`selector`],`Resolved interaction target kind.`),x:A(`Resolved interaction x coordinate when available.`),y:A(`Resolved interaction y coordinate when available.`),referenceWidth:A(`Reference frame width for visualizing the interaction point.`),referenceHeight:A(`Reference frame height for visualizing the interaction point.`),ref:k(`Snapshot ref without the @ prefix when the target was an @ref.`),selector:k(`Selector expression when the target was a selector.`),selectorChain:Cr(),refLabel:k(),targetHittable:j(),hint:k(),warning:k(),message:k(),evidence:lc,resolution:fc,cost:uc,maestroNonHittableCoordinateFallbackAllowed:j(`Whether the direct iOS Maestro coordinate fallback was allowed for this selector.`),maestroNonHittableCoordinateFallbackUsed:j(`Whether the direct iOS Maestro coordinate fallback was actually used.`),maestroFallbackReason:O(`non-hittable-coordinate`),...t},[`targetKind`,...n])}const mc=pc({properties:{evidence:lc,button:D([`secondary`,`middle`]),count:A(`Number of press/click repetitions.`),intervalMs:A(`Delay between repeated press/click actions.`),holdMs:A(`Hold duration for each action.`),jitterPx:A(`Randomization radius in pixels.`),doubleTap:j(`Whether the command requested a double-tap action.`)}}),hc={text:k(`Text submitted to the field.`),delayMs:A(`Delay between typed characters in milliseconds.`),evidence:lc},gc=E({resourceId:xr(`Android resource id of the exact field that changed.`),className:xr(`Android class name of the exact field that changed.`),packageName:xr(`Android package name that owns the exact field.`),rect:E({x:A(),y:A(),width:A(),height:A()},[`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. Android may return target-bound unconfirmed evidence when the exact app-owned field changed but formatting prevented raw equality.`,oneOf:[{...pc({properties:hc,required:[`text`]}),not:E({},[`verification`])},pc({properties:{...hc,verification:O(`unconfirmed`),requested:k(`Literal text requested by the fill command.`),before:xr(`Raw target text captured before the fill.`),after:xr(`Raw target text captured after the fill.`),target:gc},required:[`text`,`verification`,`requested`,`before`,`after`,`target`]})]},longpress:pc({properties:{durationMs:A(),gesture:O(`longpress`)}}),hover:pc({properties:{gesture:O(`hover`)}}),find:E({ref:k(`Snapshot ref without the @ prefix when the find action returns one.`),refsGeneration:A(`ADR 0014 ref frame epoch for read-only find actions.`),found:j(`Whether a wait/exists/read-only find satisfied its condition.`),waitedMs:A(`Milliseconds waited for a read-only find condition.`),text:k(`Text value returned by find get_text.`),node:M(`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:M(`One listed match with its snapshot ref and node.`)},locator:k(`Locator kind used for the find action.`),query:k(`Query argument used for the find action.`),x:A(`Resolved x coordinate for mutating find actions.`),y:A(`Resolved y coordinate for mutating find actions.`),message:k(`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:[...ji,`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:[...ji,`record`]},click:{usageOverride:`click <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`target`],allowsExtraPositionals:!0,allowedFlags:[...Pi,`clickButton`,...os(`click`),...ji]},press:{usageOverride:`press <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...Pi,...os(`press`),...ji]},longpress:{usageOverride:`longpress <x y|@ref|selector> [durationMs]`,usageFlags:[],positionalArgs:[`targetOrX`,`yOrDurationMs?`,`durationMs?`],allowsExtraPositionals:!0,allowedFlags:[...os(`longpress`),...ji]},hover:{usageOverride:`hover <x y|@ref|selector>`,usageFlags:[],positionalArgs:[`targetOrX`,`y?`],allowsExtraPositionals:!0,allowedFlags:[...os(`hover`),...ji]},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>`,usageFlags:[],positionalArgs:[`targetOrX`,`yOrText`,`text?`],allowsExtraPositionals:!0,allowedFlags:[...ji,`delayMs`,`recordAs`,...os(`fill`)]},scroll:{usageOverride:`scroll <direction|top|bottom> [amount]`,usageFlags:[`until`,`pixels`,`durationMs`,`settle`],positionalArgs:[`directionOrEdge`,`amount?`],allowedFlags:[`pixels`,`durationMs`,`until`,...os(`scroll`)]}},vc=U({name:`interaction`,clientSurface:!1,commands:[H({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}),H({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}),H({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".`},metadata:X(`fill`),run:(e,t)=>e.interactions.fill(xc(t)),cliSchema:Y.fill,cliReader:K.fill,daemonWriter:q.fill,cliOutputFormatter:J.fill}),H({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}),H({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}),H({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}),H({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}),H({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}),H({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}),H({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}),H({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}),H({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}),H({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:Ds.gesture,daemonWriter:Os.gesture})]});function X(e){let t=Ts.find(t=>t.name===e);if(!t)throw Error(`Missing interaction command metadata for ${e}`);return t}function yc(e){return{...g(e),...Ur(e.target),...Kr(e),...Gr(e),button:e.button,verify:e.verify,readinessTimeoutMs:e.readinessTimeoutMs,...wc(e)}}function bc(e){return{...g(e),...Ur(e.target),...Kr(e),...Gr(e),verify:e.verify,readinessTimeoutMs:e.readinessTimeoutMs,...wc(e)}}function xc(e){return{...g(e),...Ur(e.target),...Kr(e),text:e.text,delayMs:e.delayMs,recordAs:e.recordAs,verify:e.verify,...wc(e)}}function Sc(e){return{...g(e),...Ur(e.target),...Kr(e),durationMs:e.durationMs,readinessTimeoutMs:e.readinessTimeoutMs,...wc(e)}}function Cc(e){return{...g(e),...Ur(e.target),...Kr(e),...wc(e)}}function wc(e){return{settle:e.settle,settleQuietMs:e.settleQuietMs,timeoutMs:e.timeoutMs}}function Tc(e){return{...g(e),...Wr(e.target),...Kr(e),format:e.format,record:e.record}}function Ec(e){return{...g(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{...g(e),source:e.source,destination:e.destination,sourceHoldMs:e.sourceHoldMs,moveMs:e.moveMs,destinationHoldMs:e.destinationHoldMs}}function Oc(e){return{...g(e),direction:e.direction,x:e.origin.x,y:e.origin.y,distance:e.distance}}function kc(e){return{...g(e),preset:e.preset}}function Ac(e){return{...g(e),scale:e.scale,x:e.origin?.x,y:e.origin?.y}}function jc(e){return{...g(e),degrees:e.degrees,x:e.origin?.x,y:e.origin?.y}}function Mc(e){return{...g(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(`
16
+ `)}}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(`
17
+ `)}}function Fc(e){return{data:{apps:e.result},stderr:e.appsFilter===`all`?`Showing all apps, including system apps.
18
18
  `:`Showing user-installed apps or deferred provider app assets. Use --all to include system apps on a live device.
19
19
  `,text:e.result.length>0?e.result.join(`
20
- `):e.appsFilter===`all`?`No apps found.`:`No user apps or provider app assets found.`}}async function Nc(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 Pc(e){let{serializeOpenResult:t}=await import(`./result-serialization.js`).then(e=>e.t),n=t(e),r=[Dt(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 Fc(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(`
21
- `)||null}}async function Fc(e){return!e||!Array.isArray(e.nodes)?null:await Eo({result:e,interactiveOnly:!0})}async function Ic(e){let{serializeCloseResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return kt(t(e))}function Lc(e){if(Rc(e))return{data:e,text:e.artifacts.length>0?e.artifacts.map(Kc).join(`
22
- `):e.message??`No daemon artifacts available.`};let t=[e.message??`No cloud artifacts available for ${e.provider}.`],n=qc(e);return n&&t.push(`Retry: ${n}`),{data:e,text:e.cloudArtifacts.length>0?e.cloudArtifacts.map(Gc).join(`
20
+ `):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=[Ot(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(`
21
+ `)||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 At(t(e))}function Bc(e){if(Vc(e))return{data:e,text:e.artifacts.length>0?e.artifacts.map(Yc).join(`
22
+ `):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(`
23
23
  `):t.join(`
24
- `)}}function Rc(e){return`source`in e&&e.source===`daemon`}async function zc(e){let{serializeDeployResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return kt(t(e))}async function Bc(e){let{serializeInstallFromSourceResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return kt(t(e))}function Vc(e){let t=e,n=t.platform??`unknown`;return{data:t,text:`Boot ready: ${t.device??t.id??`unknown`} (${n})`}}function Hc(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 Uc(e,t){let{formatDoctorCheckDetailLines:n,formatDoctorCheckSummaryLine:r}=await import(`./doctor-output.js`).then(e=>e.t),i=e,a=[`Doctor: ${typeof i.status==`string`?i.status:`unknown`}`],o=Jc(i.checks);if(t?.renderedToStderr){let e=typeof i.summary==`string`?i.summary:void 0;e&&a.push(e)}else if(o.length===0){let e=typeof i.summary==`string`?i.summary:`No blockers found.`;a.push(e)}else for(let e of o)a.push(r(e)),a.push(...n(e));return{data:i,text:a.join(`
25
- `)}}const Z={boot:d(Vc),shutdown:d(Hc),devices:d(Ac),capabilities:d(jc),doctor:({result:e,progress:t})=>Uc(e,t),apps:({input:e,result:t})=>Mc({result:t,appsFilter:e.appsFilter}),session:d(Nc),artifacts:d(Lc),open:d(Pc),close:d(Ic),install:d(zc),reinstall:d(zc),"install-from-source":d(Bc),prepare:f,viewport:f};function Wc(e){let t=e.kind?` ${e.kind}`:``,n=e.target?` target=${e.target}`:``,r=typeof e.booted==`boolean`?` booted=${e.booted}`:``,i=e.claimedBy?` claimed by session "${e.claimedBy.session}" in ${e.claimedBy.workspace}`:``;return`${e.name} (${e.platform}${t}${n})${r}${i}`}function Gc(e){let t=e.url?` ${e.url}`:``,n=e.availability?` ${e.availability}`:``;return`${e.kind}: ${e.name}${n}${t}`}function Kc(e){let t=e.artifactType?` (${e.artifactType})`:``;return`${e.filename}${t}: ${e.mimeType} ${e.sizeBytes} bytes id=${e.id}`}function qc(e){if(e.providerSessionId)return`agent-device artifacts ${e.providerSessionId} --provider ${e.provider} --json`}function Jc(e){return Array.isArray(e)?e.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e)):[]}const Yc=H({name:`artifacts`,text:{summary:`List daemon or cloud provider session artifacts`},metadata:V(`artifacts`,`List daemon or cloud provider artifacts for an active or completed session.`,{provider:P(`Cloud provider name, for example browserstack or aws-device-farm.`),providerSessionId:P(`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)=>({...y(t),provider:t.provider,providerSessionId:e[0]??t.providerSessionId}),daemonWriter:_(u.artifacts),cliOutputFormatter:Z.artifacts});function Xc(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 Zc(e){let{metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i,...a}=e,o=Xc({metroHost:t,metroPort:n,bundleUrl:r,launchUrl:i});return o?{...a,runtime:o}:a}const Qc=V(`apps`,`List the apps installed on the selected device. Include system or OEM apps only when they are needed as automation targets.`,{appsFilter:R([`user-installed`,`all`],`Restrict the listing to user-installed apps, or include system and OEM apps.`)}),$c=V(`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:P(`App name, bundle id, package, or URL.`),url:P(`Optional URL passed with an app shell.`),surface:R(dt,`macOS presentation surface to open: the app itself, the frontmost app, the desktop, or the menu bar.`),activity:P(`Android activity name.`),launchConsole:P(`Launch console mode.`),launchArgs:kr(`Launch arguments forwarded verbatim to the platform launch command.`),relaunch:L(`Force relaunch.`),timeoutMs:I(`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:wr(`waitMs`),foreground:wr(`foreground`),saveScript:z({oneOf:[j(),k()]}),force:L(`Overwrite an existing --save-script target instead of refusing (alias: --overwrite).`),testIme:L(`Activate the headless Android test IME for deterministic Unicode text entry (default on for emulators; opt-in on real devices).`),noRecord:L(`Do not record this action.`),metroHost:P(`Session-scoped Metro/debug host hint applied to the opened app.`),metroPort:I(`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:P(`Session-scoped bundle URL hint applied to the opened app.`),launchUrl:P(`Session-scoped launch URL hint applied to the opened app.`)}),el=V(`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.`,{app:P(`Optional app to close.`),shutdown:L(`Shutdown the session/device where supported.`),saveScript:z({oneOf:[j(),k()]}),force:L(`Overwrite an existing --save-script target instead of refusing (alias: --overwrite).`)});function tl(e){return Zc(e)}const nl={allowedFlags:[`appsFilter`]},rl={positionalArgs:[`appOrUrl?`,`url?`],allowedFlags:[`activity`,`launchConsole`,`launchArgs`,`testIme`,`saveScript`,`force`,`noRecord`,`relaunch`,`foreground`,`timeoutMs`,`waitMs`,`surface`,...ji,`launchUrl`]},il={positionalArgs:[`app?`],allowedFlags:[`saveScript`,`force`,`shutdown`]},al=(e,t)=>({...y(t),appsFilter:Zt(t.appsFilter)}),ol=(e,t)=>({...y(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}),sl=(e,t)=>({...y(t),app:e[0],shutdown:t.shutdown,saveScript:t.saveScript,force:t.force}),cl=_(u.apps),ll=_(u.open,hl),ul=_(u.close,e=>S(e.app)),dl=H({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:Qc,run:(e,t)=>e.apps.list(t),cliSchema:nl,cliReader:al,daemonWriter:cl,cliOutputFormatter:Z.apps}),fl=H({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/--launch-url set this session's Metro/debug runtime hints as part of open itself (applied to the app's dev-server prefs and recorded as the session's dev-server binding), so a fresh session has them before its first reload instead of needing a throwaway reload-first call just to seed hints; a later plain metro reload in the same session reuses whichever of these were set. A fresh open without these flags clears any leftover binding from a previous same-name session; close also clears it. 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:`Metro and debug runtime hints given here are recorded as the session's dev-server binding, so a later reload reuses them; a fresh open without them clears any binding left by a previous same-name session.`},metadata:$c,run:(e,t)=>e.apps.open(tl(t)),cliSchema:rl,cliReader:ol,daemonWriter:ll,cliOutputFormatter:Z.open}),pl=H({name:`close`,text:{summary:`Close an app or end the session`},metadata:el,run:(e,t)=>t.app?e.apps.close(t):e.sessions.close(ml(t)),cliSchema:il,cliReader:sl,daemonWriter:ul,cliOutputFormatter:Z.close});function ml(e){let{app:t,...n}=e;return n}function hl(e){return e.app?e.url?[e.app,e.url]:[e.app]:[]}const gl={platform:D(ve),target:D(be),device:k(`Human-readable device name.`),id:k(`Stable device id.`),kind:D(xe)},_l=[`platform`,`target`,`device`,`id`,`kind`],vl=E({success:j(),exitCode:A(),stdout:k(),stderr:k(),error:M(`Normalized error detail when shutdown failed.`)},[`success`,`exitCode`,`stdout`,`stderr`]),yl={boot:E({...gl,booted:{type:`boolean`,const:!0}},[..._l,`booted`]),shutdown:E({...gl,shutdown:vl},[..._l,`shutdown`])},bl=V(`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.`,{}),xl=V(`capabilities`,`List the commands supported by the selected device or active session. Use device-selection inputs when checking support before a session is open.`,{}),Sl=V(`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:L(`Boot without showing simulator UI when supported.`),timeoutMs:I(`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})}),Cl=V(`shutdown`,`Shutdown a selected simulator or emulator.`,{}),wl={allowedFlags:[`headless`,`timeoutMs`]},Tl={},El={},Dl={},Ol=(e,t)=>y(t),kl=(e,t)=>({...y(t),headless:t.headless,timeoutMs:t.timeoutMs}),Al=_(u.devices),jl=_(u.capabilities),Ml=_(u.boot),Nl=_(u.shutdown),Pl=[H({name:`devices`,text:{summary:`List available devices and simulators`},metadata:bl,run:(e,t)=>e.devices.list(t),cliSchema:Tl,cliReader:Ol,daemonWriter:Al,cliOutputFormatter:Z.devices}),H({name:`capabilities`,text:{summary:`List supported commands for the selected device`,cliDetail:`Select an explicit target with --platform/--device/--udid/--serial.`},metadata:xl,run:(e,t)=>e.devices.capabilities(t),cliSchema:El,cliReader:Ol,daemonWriter:jl,cliOutputFormatter:Z.capabilities}),H({name:`boot`,text:{summary:`Boot target device/simulator`},metadata:Sl,run:(e,t)=>e.devices.boot(t),cliSchema:wl,cliReader:kl,daemonWriter:Ml,cliOutputFormatter:Z.boot}),H({name:`shutdown`,text:{summary:`Shutdown target simulator/emulator`},metadata:Cl,run:(e,t)=>e.devices.shutdown(t),cliSchema:Dl,cliReader:Ol,daemonWriter:Nl,cliOutputFormatter:Z.shutdown})],Fl={doctor:E({status:D([`pass`,`warn`,`fail`,`info`]),summary:k(),kind:D([`auto`,`react-native`,`expo`,`repack`]),platform:k(),target:D(be),targetApp:k(),metro:E({host:k(),port:A()},[`host`,`port`]),checks:{type:`array`,items:E({id:k(),status:D([`pass`,`warn`,`fail`,`info`]),summary:k(),hint:k(),command:k(),evidence:M()},[`id`,`status`,`summary`])}},[`status`,`summary`,`kind`,`checks`])},Il=H({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:V(`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:P(`Installed app package/bundle id or app name to verify without opening a session.`),remote:L(`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)=>({...y(t),targetApp:t.targetApp,remote:t.remote}),daemonWriter:_(u.doctor),cliOutputFormatter:Z.doctor});function Ll(e,t=`--github-actions-artifact`){let r=e.indexOf(`:`);if(r<=0||r===e.length-1)throw new n(`INVALID_ARGS`,`${t} must use owner/repo:artifact, for example thymikee/RNCLI83:6635342232`);let{owner:i,repo:a}=Bl(e.slice(0,r),t);return zl(i,a,e.slice(r+1),`${t} artifact`)}function Rl(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`${t} installSource must be an object.`);let r=e;if(Hl(r.type,`${t} installSource.type`)!==`github-actions-artifact`)throw new n(`INVALID_ARGS`,`${t} installSource.type must be "github-actions-artifact".`);let{owner:i,repo:a}=Bl(Hl(r.repo,`${t} installSource.repo`),`${t} installSource.repo`);return zl(i,a,r.artifact,`${t} installSource.artifact`)}function zl(e,t,n,r){return typeof n==`number`||Wl(n)?{kind:`github-actions-artifact`,owner:e,repo:t,artifactId:Ul(n,r)}:{kind:`github-actions-artifact`,owner:e,repo:t,artifactName:Hl(n,r)}}function Bl(e,t){let r=e.indexOf(`/`);if(r<=0||r===e.length-1||e.indexOf(`/`,r+1)!==-1)throw new n(`INVALID_ARGS`,`${t} must use owner/repo.`);let i={owner:e.slice(0,r).trim(),repo:e.slice(r+1).trim()};if(!i.owner||!i.repo)throw new n(`INVALID_ARGS`,`${t} must use owner/repo.`);return i}function Vl(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Hl(e,t){let r=Vl(e);if(!r)throw new n(`INVALID_ARGS`,`${t} must be a non-empty string.`);return r}function Ul(e,t){let r=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;if(!Number.isInteger(r))throw new n(`INVALID_ARGS`,`${t} must be an integer.`);return r}function Wl(e){return typeof e==`string`&&/^\d+$/.test(e.trim())}const Gl=V(`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:P(`Optional app identifier hint.`),appPath:N(P(`Path to app binary.`))}),Kl=V(`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:N(P()),appPath:N(P(`Path to app binary.`))}),ql=V(`install-from-source`,`Install app builds from URLs, remote source specs, or CI artifacts resolved by a remote daemon.`,{source:N(z(M(`Install source object.`))),retainPaths:L(),retentionMs:I()}),Jl={usageOverride:`install <path> | install <app> <path>`,listUsageOverride:`install <path>`,positionalArgs:[`appOrPath`,`path?`]},Yl={positionalArgs:[`app`,`path`]},Xl={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`]},Zl=(e,t)=>ru(e,t),Ql=(e,t)=>iu(e,t),$l=(e,t)=>({...y(t),source:su(e,t),retainPaths:t.retainPaths,retentionMs:t.retentionMs}),eu=_(u.install,e=>au(e.app,e.appPath)),tu=_(u.reinstall,e=>ou(e.app,e.appPath)),nu=[H({name:`install`,text:{summary:`Install an app binary from a path`},metadata:Gl,run:(e,t)=>e.apps.install(t),cliSchema:Jl,cliReader:Zl,daemonWriter:eu,cliOutputFormatter:Z.install}),H({name:`reinstall`,text:{summary:`Replace an installed app with a new build`},metadata:Kl,run:(e,t)=>e.apps.reinstall(t),cliSchema:Yl,cliReader:Ql,daemonWriter:tu,cliOutputFormatter:Z.reinstall}),H({name:`install-from-source`,text:{summary:`Install app builds from URLs or CI artifacts`},metadata:ql,run:(e,t)=>e.apps.installFromSource(t),cliSchema:Xl,cliReader:$l,daemonWriter:e=>v(ot.installSource,[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),cliOutputFormatter:Z[`install-from-source`]})];function ru(e,t){let[n,r]=e,i=r!==void 0;return{...y(t),...i?{app:w(n,`install requires app`)}:{},appPath:w(i?r:n,`install requires path`)}}function iu(e,t){return{...y(t),app:w(e[0],`reinstall requires app`),appPath:w(e[1],`reinstall requires path`)}}function au(e,t){let n=T(t,`missing app path`);return typeof e==`string`&&e.length>0?[e,n]:[n]}function ou(e,t){return[T(e,`missing first positional`),T(t,`missing second positional`)]}function su(e,t){let r=e[0]?.trim();if(e.length>1)throw new n(`INVALID_ARGS`,`install-from-source accepts either one <url> positional or --github-actions-artifact`);let i=t.githubActionsArtifact?Ll(t.githubActionsArtifact):void 0,a=t.installSource;if(+!!r+ +!!i+ +!!a!=1)throw new n(`INVALID_ARGS`,`install-from-source requires exactly one source: <url>, --github-actions-artifact, or config installSource`);if(!r&&t.header&&t.header.length>0)throw new n(`INVALID_ARGS`,`install-from-source --header is only supported for URL sources`);return i||a||{kind:`url`,url:r,headers:cu(t.header)}}function cu(e){if(!e||e.length===0)return;let t={};for(let r of e){let e=r.indexOf(`:`);if(e<=0)throw new n(`INVALID_ARGS`,`Invalid --header value "${r}". Expected "name:value".`);let i=r.slice(0,e).trim(),a=r.slice(e+1).trim();if(!i)throw new n(`INVALID_ARGS`,`Invalid --header value "${r}". Header name cannot be empty.`);t[i]=a}return t}const lu=[`ios-runner`],uu={prepare:E({action:O(`ios-runner`),platform:D(ve),deviceId:k(),deviceName:k(),kind:D(xe),durationMs:A(),runner:E({},[]),cache:D([`exact`,`miss`,`external`]),artifact:D([`valid`,`rebuilt`]),buildMs:A(),connectMs:A(),healthCheckMs:A(),xctestrunPath:k(),recoveryReason:k(),failureReason:k(),timing:E({totalMs:A(),additiveParts:E({buildMs:A(),connectAfterBuildMs:A(),healthCheckMs:A()},[`connectAfterBuildMs`,`healthCheckMs`]),containment:E({connectMs:{type:`array`,items:O(`buildMs`)},healthCheckMs:{type:`array`,items:k()}},[`healthCheckMs`]),note:k()},[`totalMs`,`additiveParts`,`containment`,`note`]),message:k()},[`action`,`platform`,`deviceId`,`deviceName`,`kind`,`durationMs`,`runner`,`connectMs`,`healthCheckMs`,`timing`,`message`])},du=H({name:`prepare`,text:{summary:`Pre-warm platform helpers before automation`},metadata:V(`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:N(R(lu)),timeoutMs:I(`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)=>({...y(t),action:w(e[0],`prepare requires subcommand`),timeoutMs:t.timeoutMs}),daemonWriter:_(u.prepare,e=>[T(e.action,`prepare requires subcommand`)]),cliOutputFormatter:Z.prepare}),fu={push:{type:`object`,oneOf:[E({platform:O(`ios`),bundleId:k(),message:k()},[`platform`,`bundleId`,`message`]),E({platform:O(`android`),package:k(),action:k(),extrasCount:A(),message:k()},[`platform`,`package`,`action`,`extrasCount`,`message`])]},"trigger-app-event":E({event:k(),eventUrl:k(),transport:O(`deep-link`),message:k()},[`event`,`eventUrl`,`transport`,`message`])},pu=V(`push`,`Deliver push notification payloads to an installed app.`,{app:N(P()),payload:N(z({oneOf:[k(),M()]}))}),mu=V(`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:N(P(`Name of an app-defined automation or test event the app documents.`)),payload:wu(`Structured payload passed to the event, in the shape the app documents for it.`)}),hu={listUsageOverride:`push`,positionalArgs:[`bundleOrPackage`,`payloadOrJson`]},gu={usageOverride:`trigger-app-event <event> [payloadJson]`,listUsageOverride:`trigger-app-event`,positionalArgs:[`event`,`payloadJson?`]},_u=(e,t)=>({...y(t),app:w(e[0],`push requires bundleOrPackage`),payload:w(e[1],`push requires payloadOrJson`)}),vu=(e,t)=>({...y(t),event:w(e[0],`trigger-app-event requires event`),payload:e[1]?or(e[1],`trigger-app-event payload`):void 0}),yu=_(u.push,e=>Su(e)),bu=_(u.triggerAppEvent,e=>Cu(e)),xu=[H({name:`push`,text:{summary:`Deliver a push notification payload`},metadata:pu,run:(e,t)=>e.apps.push(t),cliSchema:hu,cliReader:_u,daemonWriter:yu}),H({name:`trigger-app-event`,text:{summary:`Invoke an app-defined automation event`},metadata:mu,run:(e,t)=>e.apps.triggerEvent(t),cliSchema:gu,cliReader:vu,daemonWriter:bu})];function Su(e){return[e.app,typeof e.payload==`string`?e.payload:JSON.stringify(e.payload)]}function Cu(e){return[e.event,...e.payload?[JSON.stringify(e.payload)]:[]]}function wu(e){return Or(e)}const Tu=H({name:`session`,text:{summary:`List sessions, show the state dir, or publish a script`},metadata:V(`session`,`List active sessions, print the effective daemon state directory, or publish an armed open-to-destination script without closing its session`,{action:R([`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:P(`Optional .ad output path for save-script.`),force:L(`Atomically replace an existing save-script target.`)}),run:async(e,{action:t,path:n,force:r,...i})=>{let a=t??`list`;return Du(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)=>({...y(t),action:Eu(e[0]),path:e[1],force:t.force}),cliOutputFormatter:Z.session});function Eu(e){let t=e??`list`;if(t===`list`||t===`state-dir`||t===`save-script`)return t;throw new n(`INVALID_ARGS`,`session only supports list, state-dir, or save-script`)}function Du(e,t,r){if(e!==`save-script`&&(t!==void 0||r===!0))throw new n(`INVALID_ARGS`,`session ${e} does not accept a path or --force; use session save-script [path] [--force] to publish a recording.`)}const Ou={viewport:E({width:A(),height:A(),message:k()},[`width`,`height`,`message`])},ku=H({name:`viewport`,text:{summary:`Resize the active web viewport for the current session`},metadata:V(`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:N(I(`Viewport width in CSS pixels.`,{min:1})),height:N(I(`Viewport height in CSS pixels.`,{min:1}))}),run:(e,t)=>e.command.viewport(t),cliSchema:{positionalArgs:[`width`,`height`]},cliReader:(e,t)=>({...y(t),..._e(e)}),daemonWriter:_(u.viewport,e=>{let{width:t,height:n}=e;return[String(t),String(n)]}),cliOutputFormatter:Z.viewport}),Au=U({name:`management`,commands:[...Pl,Yc,Il,du,dl,Tu,fl,pl,ku,...nu,...xu]});function ju(e){return{data:e.result,text:e.action===`reload`?`Reloaded React Native apps via ${e.result.reloadUrl}`:JSON.stringify(e.result,null,2)}}const Mu={metro:({input:e,result:t})=>ju({result:t,action:e.action})},Nu=`metro`,Pu=U({name:`metro`,commands:[H({name:Nu,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. The reload URL keeps the bound bundle URL mount prefix instead of collapsing to the host root, 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:V(Nu,`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:N(R([`prepare`,`reload`])),projectRoot:P(),kind:z(k()),publicBaseUrl:P(),proxyBaseUrl:Cr(P(),{operatorPath:`Configure the remote proxy in the remote-config profile or operator config for the process serving these tools.`}),bearerToken:Cr(P(),{envFlagKeys:[`metroBearerToken`,`daemonAuthToken`]}),bridgeScope:z({type:`object`,additionalProperties:!0}),launchUrl:P(),port:I(),listenHost:P(),statusHost:P(),startupTimeoutMs:I(),probeTimeoutMs:I(),reuseExisting:L(),installDependenciesIfNeeded:L(),runtimeFilePath:P(),logPath:P(),metroHost:P(),metroPort:I(),bundleUrl:P(),timeoutMs:I()}),run:async(e,t)=>t.action===`prepare`?await e.metro.prepare(Fu(t)):await e.metro.reload(Lu(t)),cliSchema:{usageOverride:`metro prepare (--public-base-url <url> | --proxy-base-url <url>) [--project-root <path>] [--port <port>] [--kind auto|react-native|expo|repack]
26
- agent-device metro reload [--metro-host <host>] [--metro-port <port>] [--bundle-url <url>]`,usageFlags:[],listUsageOverride:`metro`,positionalArgs:[`prepare|reload`],allowedFlags:[...ji,...Ai]},cliReader:(e,t)=>{let r=(e[0]??``).toLowerCase();if(r!==`prepare`&&r!==`reload`)throw new n(`INVALID_ARGS`,`metro requires a subcommand: prepare or reload`);if(r===`reload`)return{action:r,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,timeoutMs:t.metroProbeTimeoutMs};if(!t.metroPublicBaseUrl&&!t.metroProxyBaseUrl)throw new n(`INVALID_ARGS`,`metro prepare requires --public-base-url <url> or --proxy-base-url <url>.`);return{action:r,projectRoot:t.metroProjectRoot,kind:sn(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:Mu.metro})]});function Fu(e){return{projectRoot:e.projectRoot,kind:e.kind,publicBaseUrl:e.publicBaseUrl,proxyBaseUrl:e.proxyBaseUrl,bearerToken:e.bearerToken,bridgeScope:e.bridgeScope??Iu(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 Iu(e){return e.tenant&&e.runId&&e.leaseId?{tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId}:void 0}function Lu(e){return{metroHost:e.metroHost,metroPort:e.metroPort,bundleUrl:e.bundleUrl,timeoutMs:e.timeoutMs}}function Ru(e,t){return e.includes(t)}function zu(e,t,r={}){let i=t===void 0?void 0:r.normalize?.(t)??t;if(i!==void 0&&Ru(e,i))return i;let a=typeof r.message==`function`?r.message(t):r.message;throw new n(`INVALID_ARGS`,a??`Invalid value: ${t}. Use ${e.join(`|`)}.`)}const Bu=[`started`,`stopped`,`marked`,`cleared`,`restarted`,`removedRotatedFiles`];function Vu(e){return{data:e,text:e.path,stderr:hd([pd(e,[`active`,`state`,`backend`,`sizeBytes`]),ad(e),e.hint,md(e.notes)])}}function Hu(e){let t=e.events??[];return{data:e,text:t.length>0?Ku(t):`No session events found.`,stderr:hd([pd(e,[`path`,`cursor`,`nextCursor`,`limit`])])}}function Uu(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(...ud(e));return{data:e,text:t.join(`
27
- `),stderr:hd([pd(e,[`active`,`state`,`backend`,`include`,`scannedLines`,`matchedLines`]),md(e.notes)])}}function Wu(e){return{data:e,text:[`Audio probe: ${String(e.state??`stopped`)} heard=${String(e.heard===!0)}`,id(`rmsDbfs`,e.rmsDbfs),id(`peakDbfs`,e.peakDbfs)].filter(e=>!!e).join(`
28
- `),stderr:hd([pd(e,[`active`,`backend`,`source`,`durationMs`,`elapsedMs`,`bucketMs`,`sampleCount`,`sourceCount`,`mediaElementCount`]),md(e.notes)])}}const Gu={logs:d(Vu),events:d(Hu),network:d(Uu),audio:d(Wu)};function Ku(e){let t=e.map(qu),n=Math.min(Math.max(...t.map(e=>e.label.length),5),32);return t.map(e=>Ju(e,n)).join(`
29
- `)}function qu(e){return{timestamp:Yu(e.ts),label:Xu(e),summary:Zu(e)}}function Ju(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 Yu(e){return e?e.replace(`T`,` `):``}function Xu(e){let t=e.command??`command`;switch(e.kind){case`request.started`:return`start ${t}`;case`request.finished`:return sd([e.status===`error`?`error`:`ok`,t,rd(ld(e.details?.durationMs))]);case`action.recorded`:return`action ${t}`;default:return sd([e.kind??`event`,e.command])}}function Zu(e){let t=Qu(e.summary,e);return`${t}${$u(e,t)}`.trim()}function Qu(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 $u(e,t){if(e.kind!==`action.recorded`)return``;let n=e.details;if(!n)return``;let r=[ed(n,t),nd(ld(n.textLength))].filter(e=>!!e);return r.length>0?` (${r.join(`, `)})`:``}function ed(e,t){let n=cd(e.ref)??cd(e.selector)??td(e);if(!(!n||t.includes(n)))return`target=${n}`}function td(e){let t=ld(e.x),n=ld(e.y);return t===void 0||n===void 0?void 0:`(${t}, ${n})`}function nd(e){return e===void 0?void 0:`text=${e} chars`}function rd(e){return e===void 0?void 0:`${Math.round(e)}ms`}function id(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 ad(e){return Bu.map(t=>od(t,e[t])).filter(Boolean).join(` `)||void 0}function od(e,t){return t==null?``:`${e}=${t}`}function sd(e){return e.filter(e=>!!e).join(` `)}function cd(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function ld(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function ud(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?fd(o,`headers`,e.headers):(dd(o,`request headers`,e.requestHeaders),dd(o,`response headers`,e.responseHeaders)),fd(o,`request`,e.requestBody),fd(o,`response`,e.responseBody),o}function dd(e,t,n){!n||Object.keys(n).length===0||e.push(` ${t}: ${JSON.stringify(n)}`)}function fd(e,t,n){n!==void 0&&e.push(` ${t}: ${n}`)}function pd(e,t){return t.map(t=>e[t]!==void 0&&e[t]!==null?`${t}=${e[t]}`:``).filter(Boolean).join(` `)||void 0}function md(e){let t=e?.filter(e=>e.length>0)??[];return t.length>0?t.join(`
30
- `):void 0}function hd(e){return e.filter(e=>!!e).join(`
31
- `)||void 0}const gd=`logs`,_d=`events`,vd=`network`,yd=`audio`,bd=[`dump`,`log`],xd=[`probe`],Sd=[`start`,`status`,`stop`],Cd=V(gd,`Session app log info, start/stop streaming, diagnostics, and markers`,{action:R(hn),message:P(),restart:L()}),wd=V(_d,`Read the daemon-owned session event timeline as paged JSON-friendly entries`,{limit:I(),cursor:P()}),Td=V(vd,`Dump recent HTTP(s) traffic parsed from the session app log`,{action:R(bd),limit:I(),include:R(s)}),Ed=V(yd,`Measure browser or host-rendered simulator/emulator audio as compact dBFS buckets. Start a probe before requesting its status or stopping it.`,{action:R(xd),probeAction:R(Sd),durationMs:I(`Probe duration in milliseconds.`),bucketMs:I(`Audio level bucket size in milliseconds.`)}),Dd=U({name:`observability`,commands:[H({name:gd,text:{summary:`Manage session app logs`},metadata:Cd,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)=>({...y(t),action:Md(e[0]),message:e.slice(1).join(` `)||void 0,restart:t.restart}),daemonWriter:_(gd,e=>Od(e)),cliOutputFormatter:Gu.logs}),H({name:_d,text:{summary:`Read session event timeline`},metadata:wd,run:(e,t)=>e.observability.events(t),cliSchema:{usageOverride:`events [limit] [cursor]`,listUsageOverride:`events`,positionalArgs:[`limit?`,`cursor?`]},cliReader:(e,t)=>({...y(t),limit:e[0]?.trim()?ur(e[0]):void 0,cursor:e[1]}),daemonWriter:e=>v(_d,kd(e),e),cliOutputFormatter:Gu.events}),H({name:vd,text:{summary:`Inspect HTTP(S) traffic from session logs`},metadata:Td,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)=>({...y(t),action:Nd(e[0]),limit:ur(e[1]),include:t.networkInclude??Pd(e[2])}),daemonWriter:e=>v(vd,Ad(e),{...e,networkInclude:e.include}),cliOutputFormatter:Gu.network}),H({name:yd,text:{summary:`Probe audio levels`},metadata:Ed,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)=>({...y(t),action:Fd(e[0]),probeAction:Id(e[1]),durationMs:Ld(e[2]),bucketMs:ur(e[3])}),daemonWriter:e=>v(yd,jd(e),e),cliOutputFormatter:Gu.audio})]});function Od(e){return[e.action??`path`,...S(e.message)]}function kd(e){return e.cursor===void 0?C(e.limit):[e.limit===void 0?``:String(e.limit),e.cursor]}function Ad(e){return[...e.action?[e.action]:[],...C(e.limit)]}function jd(e){return[e.action??`probe`,e.probeAction??`status`,...C(e.durationMs),...C(e.bucketMs)]}function Md(e){if(e!==void 0)return zu(hn,e,{message:`logs requires path, start, stop, doctor, mark, or clear`})}function Nd(e){if(e!==void 0){if(e===`dump`||e===`log`)return e;throw new n(`INVALID_ARGS`,`network requires dump or log`)}}function Pd(e){if(e!==void 0)return zu(s,e,{message:`network include must be summary, headers, body, or all`})}function Fd(e){if(e!==void 0)return zu(xd,e,{message:`audio requires probe`})}function Id(e){if(e!==void 0)return zu(Sd,e,{message:`audio probe requires start, status, or stop`})}function Ld(e){let t=ur(e);return t===void 0?void 0:Math.round(t*1e3)}function Rd(e){let t=e;return{data:t,text:Bd(t)}}const zd={perf:d(Rd)};function Bd(e){return qd(e)??Vd(e)}function Vd(e){let t=l(e.artifact)?e.artifact:void 0;return t?Kd(t):Hd(l(e.metrics)?e.metrics:void 0)}function Hd(e){return l(e?.fps)?Wd(e):Ud(e)??`Memory: unavailable - missing memory metric`}function Ud(e){let t=l(e?.memory)?e.memory:void 0;if(!t)return;if(t.available===!1)return`Memory: unavailable - ${of(t)}`;let n=ff(t);return n?`Performance: ${n}`:`Memory: unavailable - missing memory metric`}function Wd(e){let t=l(e?.fps)?e.fps:void 0;if(!t)return af(`missing frame metric`);if(t.available===!1)return af(of(t));let n=sf(t);return n?Gd(t,n):af(`missing dropped-frame summary`)}function Gd(e,t){let n=[`Frame health: ${t}`],r=uf(e);return r.length>0&&n.push(`Worst windows:`,...r),n.join(`
32
- `)}function Kd(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?``:` (${gf(r)})`;return n?`Memory artifact (${t}): ${n}${i}`:`Memory artifact (${t}): captured${i}`}function qd(e){return e.kind===`xctrace`?Jd(e):Qd(e)}function Jd(e){let t=typeof e.perf==`string`?e.perf:void 0,n=Xd(e);if(!t||!n||e.kind!==`xctrace`)return;let r=Zd(n,typeof e.mode==`string`?e.mode:`capture`,t,e.template),i=Yd(e);return i.length>0?`${r}\nTop CPU self time:\n${i.join(`
33
- `)}`:r}function Yd(e){let t=l(e.summary)?e.summary:void 0;return Array.isArray(t?.topFunctions)?t.topFunctions.slice(0,5).flatMap(e=>{if(!l(e))return[];let t=nf(e.symbol),n=Q(e.selfSamplePercent);if(!t||n===void 0)return[];let r=nf(e.binary);return[`- ${pf(n)} ${t}${r?` (${r})`:``}`]}):[]}function Xd(e){return typeof e.outPath==`string`?e.outPath:typeof e.reportPath==`string`?e.reportPath:void 0}function Zd(e,t,n,r){let i=[e,`Perf ${t}: ${n}`];return typeof r==`string`&&i.push(`Template: ${r}`),i.join(`
34
- `)}function Qd(e){let t=$d(e);if(!t)return;let n=`Perf ${t.action}: ${t.kind} ${t.type}${ef(e)}${tf(e)}${rf(e)}`,r=Yd(e);return r.length>0?`${n}\nTop CPU self time:\n${r.join(`
35
- `)}`:n}function $d(e){let t=nf(e.action),n=nf(e.kind),r=nf(e.type);return t&&n&&r?{action:t,kind:n,type:r}:void 0}function ef(e){let t=nf(e.state);return t?` state=${t}`:``}function tf(e){let t=nf(e.outPath);if(!t)return``;let n=Q(e.sizeBytes);return`\n${t}${n===void 0?``:` (${gf(n)})`}`}function nf(e){return typeof e==`string`?e:void 0}function rf(e){let t=l(e.summary)?e.summary:void 0,n=l(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 ${pf(r)} (${Math.round(i)}/${Math.round(a)} frames)`}function af(e){return`Frame health: unavailable - ${e}`}function of(e){return typeof e.reason==`string`&&e.reason.length>0?e.reason:`not available`}function sf(e){let t=Q(e.droppedFramePercent),n=Q(e.droppedFrameCount);if(t!==void 0&&n!==void 0)return[`dropped ${pf(t)}`,cf(n,Q(e.totalFrameCount)),lf(Q(e.sampleWindowMs))].filter(Boolean).join(` `)}function cf(e,t){return t===void 0?`(${Math.round(e)} dropped frames)`:`(${Math.round(e)}/${Math.round(t)} frames)`}function lf(e){return e===void 0?``:`window ${mf(e)}`}function uf(e){return Array.isArray(e.worstWindows)?e.worstWindows.flatMap(e=>{if(!l(e))return[];let t=df(e);return t?[t]:[]}):[]}function df(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 ${mf(i)}`;return`- +${mf(t)}-+${mf(n)}: ${Math.round(r)} missed-deadline frames${a}`}function ff(e){if(e?.available!==!0)return;let t=Q(e.residentMemoryKb)??Q(e.totalPssKb)??Q(e.totalRssKb);return t===void 0?void 0:`memory ${hf(t)}`}function Q(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function pf(e){return`${Number.isInteger(e)?e:e.toFixed(1)}%`}function mf(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 hf(e){let t=e/1024;return`${t>=10?Math.round(t):t.toFixed(1)}MB`}function gf(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 _f=`perf`,vf=U({name:`perf`,commands:[H({name:_f,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 internals, use agent-device react-devtools.`,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:V(_f,`Collect frame health, memory diagnostics, and platform profiling artifacts with compact agent-readable summaries.`,{area:N(R(xt)),subject:R(Tt),action:R(bt),kind:R(pt),template:P(`xctrace template name, for example Time Profiler.`),out:P(`Output artifact path.`),tracePath:P(`Existing .trace path to report, defaults to the latest session trace.`)}),run:(e,t)=>e.observability.perf(t),cliSchema:{usageOverride:`perf frames --json
24
+ `)}}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 At(t(e))}async function Uc(e){let{serializeInstallFromSourceResult:t}=await import(`./result-serialization.js`).then(e=>e.t);return At(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){let{formatDoctorCheckDetailLines:n,formatDoctorCheckSummaryLine:r}=await import(`./doctor-output.js`).then(e=>e.t),i=e,a=[`Doctor: ${typeof i.status==`string`?i.status:`unknown`}`],o=Zc(i.checks);if(t?.renderedToStderr){let e=typeof i.summary==`string`?i.summary:void 0;e&&a.push(e)}else if(o.length===0){let e=typeof i.summary==`string`?i.summary:`No blockers found.`;a.push(e)}else for(let e of o)a.push(r(e)),a.push(...n(e));return{data:i,text:a.join(`
25
+ `)}}const Z={boot:d(Wc),shutdown:d(Gc),devices:d(Nc),capabilities:d(Pc),doctor:({result:e,progress:t})=>Kc(e,t),apps:({input:e,result:t})=>Fc({result:t,appsFilter:e.appsFilter}),session:d(Ic),artifacts:d(Bc),open:d(Lc),close:d(zc),install:d(Hc),reinstall:d(Hc),"install-from-source":d(Uc),prepare:f,viewport:f};function qc(e){let t=e.kind?` ${e.kind}`:``,n=e.target?` target=${e.target}`:``,r=typeof e.booted==`boolean`?` booted=${e.booted}`:``,i=e.claimedBy?` claimed by session "${e.claimedBy.session}" in ${e.claimedBy.workspace}`:``;return`${e.name} (${e.platform}${t}${n})${r}${i}`}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=H({name:`artifacts`,text:{summary:`List daemon or cloud provider session artifacts`},metadata:V(`artifacts`,`List daemon or cloud provider artifacts for an active or completed session.`,{provider:P(`Cloud provider name, for example browserstack or aws-device-farm.`),providerSessionId:P(`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)=>({...y(t),provider:t.provider,providerSessionId:e[0]??t.providerSessionId}),daemonWriter:_(u.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=V(`apps`,`List the apps installed on the selected device. Include system or OEM apps only when they are needed as automation targets.`,{appsFilter:R([`user-installed`,`all`],`Restrict the listing to user-installed apps, or include system and OEM apps.`)}),nl=V(`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:P(`App name, bundle id, package, or URL.`),url:P(`Optional URL passed with an app shell.`),surface:R(ft,`macOS presentation surface to open: the app itself, the frontmost app, the desktop, or the menu bar.`),activity:P(`Android activity name.`),launchConsole:P(`Launch console mode.`),launchArgs:jr(`Launch arguments forwarded verbatim to the platform launch command.`),relaunch:L(`Force relaunch.`),timeoutMs:I(`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:Er(`waitMs`),foreground:Er(`foreground`),saveScript:z({oneOf:[j(),k()]}),force:L(`Overwrite an existing --save-script target instead of refusing (alias: --overwrite).`),testIme:L(`Activate the headless Android test IME for deterministic Unicode text entry (default on for emulators; opt-in on real devices).`),noRecord:L(`Do not record this action.`),metroHost:P(`Session-scoped Metro/debug host hint applied to the opened app.`),metroPort:I(`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:P(`Session-scoped bundle URL hint applied to the opened app.`),launchUrl:P(`Session-scoped launch URL hint applied to the opened app.`)}),rl=V(`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.`,{app:P(`Optional app to close.`),shutdown:L(`Shutdown the session/device where supported.`),saveScript:z({oneOf:[j(),k()]}),force:L(`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`,...Ni,`launchUrl`]},sl={positionalArgs:[`app?`],allowedFlags:[`saveScript`,`force`,`shutdown`]},cl=(e,t)=>({...y(t),appsFilter:Qt(t.appsFilter)}),ll=(e,t)=>({...y(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)=>({...y(t),app:e[0],shutdown:t.shutdown,saveScript:t.saveScript,force:t.force}),dl=_(u.apps),fl=_(u.open,vl),pl=_(u.close,e=>S(e.app)),ml=H({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=H({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/--launch-url set this session's Metro/debug runtime hints as part of open itself (applied to the app's dev-server prefs and recorded as the session's dev-server binding), so a fresh session has them before its first reload instead of needing a throwaway reload-first call just to seed hints; a later plain metro reload in the same session reuses whichever of these were set. A fresh open without these flags clears any leftover binding from a previous same-name session; close also clears it. 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 no single installed app owns the scheme, the prompt stays on screen and open returns as usual. 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 simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. Only the English prompt title 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:`Metro and debug runtime hints given here are recorded as the session's dev-server binding, so a later reload reuses them; a fresh open without them clears any binding left by a previous same-name session.`},metadata:nl,run:(e,t)=>e.apps.open(il(t)),cliSchema:ol,cliReader:ll,daemonWriter:fl,cliOutputFormatter:Z.open}),gl=H({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:D(ve),target:D(be),device:k(`Human-readable device name.`),id:k(`Stable device id.`),kind:D(xe)},bl=[`platform`,`target`,`device`,`id`,`kind`],xl=E({success:j(),exitCode:A(),stdout:k(),stderr:k(),error:M(`Normalized error detail when shutdown failed.`)},[`success`,`exitCode`,`stdout`,`stderr`]),Sl={boot:E({...yl,booted:{type:`boolean`,const:!0}},[...bl,`booted`]),shutdown:E({...yl,shutdown:xl},[...bl,`shutdown`])},Cl=V(`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=V(`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=V(`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:L(`Boot without showing simulator UI when supported.`),timeoutMs:I(`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=V(`shutdown`,`Shutdown a selected simulator or emulator.`,{}),Dl={allowedFlags:[`headless`,`timeoutMs`]},Ol={},kl={},Al={},jl=(e,t)=>y(t),Ml=(e,t)=>({...y(t),headless:t.headless,timeoutMs:t.timeoutMs}),Nl=_(u.devices),Pl=_(u.capabilities),Fl=_(u.boot),Il=_(u.shutdown),Ll=[H({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}),H({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}),H({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}),H({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:E({status:D([`pass`,`warn`,`fail`,`info`]),summary:k(),kind:D([`auto`,`react-native`,`expo`,`repack`]),platform:k(),target:D(be),targetApp:k(),metro:E({host:k(),port:A()},[`host`,`port`]),checks:{type:`array`,items:E({id:k(),status:D([`pass`,`warn`,`fail`,`info`]),summary:k(),hint:k(),command:k(),evidence:M()},[`id`,`status`,`summary`])}},[`status`,`summary`,`kind`,`checks`])},zl=H({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:V(`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:P(`Installed app package/bundle id or app name to verify without opening a session.`),remote:L(`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)=>({...y(t),targetApp:t.targetApp,remote:t.remote}),daemonWriter:_(u.doctor),cliOutputFormatter:Z.doctor});function Bl(e,t=`--github-actions-artifact`){let r=e.indexOf(`:`);if(r<=0||r===e.length-1)throw new n(`INVALID_ARGS`,`${t} must use owner/repo:artifact, for example thymikee/RNCLI83:6635342232`);let{owner:i,repo:a}=Ul(e.slice(0,r),t);return Hl(i,a,e.slice(r+1),`${t} artifact`)}function Vl(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`${t} installSource must be an object.`);let r=e;if(Gl(r.type,`${t} installSource.type`)!==`github-actions-artifact`)throw new n(`INVALID_ARGS`,`${t} installSource.type must be "github-actions-artifact".`);let{owner:i,repo:a}=Ul(Gl(r.repo,`${t} installSource.repo`),`${t} installSource.repo`);return Hl(i,a,r.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 r=e.indexOf(`/`);if(r<=0||r===e.length-1||e.indexOf(`/`,r+1)!==-1)throw new n(`INVALID_ARGS`,`${t} must use owner/repo.`);let i={owner:e.slice(0,r).trim(),repo:e.slice(r+1).trim()};if(!i.owner||!i.repo)throw new n(`INVALID_ARGS`,`${t} must use owner/repo.`);return i}function Wl(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Gl(e,t){let r=Wl(e);if(!r)throw new n(`INVALID_ARGS`,`${t} must be a non-empty string.`);return r}function Kl(e,t){let r=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;if(!Number.isInteger(r))throw new n(`INVALID_ARGS`,`${t} must be an integer.`);return r}function ql(e){return typeof e==`string`&&/^\d+$/.test(e.trim())}const Jl=V(`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:P(`Optional app identifier hint.`),appPath:N(P(`Path to app binary.`))}),Yl=V(`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:N(P()),appPath:N(P(`Path to app binary.`))}),Xl=V(`install-from-source`,`Install app builds from URLs, remote source specs, or CI artifacts resolved by a remote daemon.`,{source:N(z(M(`Install source object.`))),retainPaths:L(),retentionMs:I()}),Zl={usageOverride:`install <path> | install <app> <path>`,listUsageOverride:`install <path>`,positionalArgs:[`appOrPath`,`path?`]},Ql={positionalArgs:[`app`,`path`]},$l={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`]},eu=(e,t)=>ou(e,t),tu=(e,t)=>su(e,t),nu=(e,t)=>({...y(t),source:uu(e,t),retainPaths:t.retainPaths,retentionMs:t.retentionMs}),ru=_(u.install,e=>cu(e.app,e.appPath)),iu=_(u.reinstall,e=>lu(e.app,e.appPath)),au=[H({name:`install`,text:{summary:`Install an app binary from a path`},metadata:Jl,run:(e,t)=>e.apps.install(t),cliSchema:Zl,cliReader:eu,daemonWriter:ru,cliOutputFormatter:Z.install}),H({name:`reinstall`,text:{summary:`Replace an installed app with a new build`},metadata:Yl,run:(e,t)=>e.apps.reinstall(t),cliSchema:Ql,cliReader:tu,daemonWriter:iu,cliOutputFormatter:Z.reinstall}),H({name:`install-from-source`,text:{summary:`Install app builds from URLs or CI artifacts`},metadata:Xl,run:(e,t)=>e.apps.installFromSource(t),cliSchema:$l,cliReader:nu,daemonWriter:e=>v(st.installSource,[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),cliOutputFormatter:Z[`install-from-source`]})];function ou(e,t){let[n,r]=e,i=r!==void 0;return{...y(t),...i?{app:w(n,`install requires app`)}:{},appPath:w(i?r:n,`install requires path`)}}function su(e,t){return{...y(t),app:w(e[0],`reinstall requires app`),appPath:w(e[1],`reinstall requires path`)}}function cu(e,t){let n=T(t,`missing app path`);return typeof e==`string`&&e.length>0?[e,n]:[n]}function lu(e,t){return[T(e,`missing first positional`),T(t,`missing second positional`)]}function uu(e,t){let r=e[0]?.trim();if(e.length>1)throw new n(`INVALID_ARGS`,`install-from-source accepts either one <url> positional or --github-actions-artifact`);let i=t.githubActionsArtifact?Bl(t.githubActionsArtifact):void 0,a=t.installSource;if(+!!r+ +!!i+ +!!a!=1)throw new n(`INVALID_ARGS`,`install-from-source requires exactly one source: <url>, --github-actions-artifact, or config installSource`);if(!r&&t.header&&t.header.length>0)throw new n(`INVALID_ARGS`,`install-from-source --header is only supported for URL sources`);return i||a||{kind:`url`,url:r,headers:du(t.header)}}function du(e){if(!e||e.length===0)return;let t={};for(let r of e){let e=r.indexOf(`:`);if(e<=0)throw new n(`INVALID_ARGS`,`Invalid --header value "${r}". Expected "name:value".`);let i=r.slice(0,e).trim(),a=r.slice(e+1).trim();if(!i)throw new n(`INVALID_ARGS`,`Invalid --header value "${r}". Header name cannot be empty.`);t[i]=a}return t}const fu=[`ios-runner`],pu={prepare:E({action:O(`ios-runner`),platform:D(ve),deviceId:k(),deviceName:k(),kind:D(xe),durationMs:A(),runner:E({},[]),cache:D([`exact`,`miss`,`external`]),artifact:D([`valid`,`rebuilt`]),buildMs:A(),connectMs:A(),healthCheckMs:A(),xctestrunPath:k(),recoveryReason:k(),failureReason:k(),timing:E({totalMs:A(),additiveParts:E({buildMs:A(),connectAfterBuildMs:A(),healthCheckMs:A()},[`connectAfterBuildMs`,`healthCheckMs`]),containment:E({connectMs:{type:`array`,items:O(`buildMs`)},healthCheckMs:{type:`array`,items:k()}},[`healthCheckMs`]),note:k()},[`totalMs`,`additiveParts`,`containment`,`note`]),message:k()},[`action`,`platform`,`deviceId`,`deviceName`,`kind`,`durationMs`,`runner`,`connectMs`,`healthCheckMs`,`timing`,`message`])},mu=H({name:`prepare`,text:{summary:`Pre-warm platform helpers before automation`},metadata:V(`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:N(R(fu)),timeoutMs:I(`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)=>({...y(t),action:w(e[0],`prepare requires subcommand`),timeoutMs:t.timeoutMs}),daemonWriter:_(u.prepare,e=>[T(e.action,`prepare requires subcommand`)]),cliOutputFormatter:Z.prepare}),hu={push:{type:`object`,oneOf:[E({platform:O(`ios`),bundleId:k(),message:k()},[`platform`,`bundleId`,`message`]),E({platform:O(`android`),package:k(),action:k(),extrasCount:A(),message:k()},[`platform`,`package`,`action`,`extrasCount`,`message`])]},"trigger-app-event":E({event:k(),eventUrl:k(),transport:O(`deep-link`),message:k()},[`event`,`eventUrl`,`transport`,`message`])},gu=V(`push`,`Deliver push notification payloads to an installed app.`,{app:N(P()),payload:N(z({oneOf:[k(),M()]}))}),_u=V(`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:N(P(`Name of an app-defined automation or test event the app documents.`)),payload:Du(`Structured payload passed to the event, in the shape the app documents for it.`)}),vu={listUsageOverride:`push`,positionalArgs:[`bundleOrPackage`,`payloadOrJson`]},yu={usageOverride:`trigger-app-event <event> [payloadJson]`,listUsageOverride:`trigger-app-event`,positionalArgs:[`event`,`payloadJson?`]},bu=(e,t)=>({...y(t),app:w(e[0],`push requires bundleOrPackage`),payload:w(e[1],`push requires payloadOrJson`)}),xu=(e,t)=>({...y(t),event:w(e[0],`trigger-app-event requires event`),payload:e[1]?cr(e[1],`trigger-app-event payload`):void 0}),Su=_(u.push,e=>Tu(e)),Cu=_(u.triggerAppEvent,e=>Eu(e)),wu=[H({name:`push`,text:{summary:`Deliver a push notification payload`},metadata:gu,run:(e,t)=>e.apps.push(t),cliSchema:vu,cliReader:bu,daemonWriter:Su}),H({name:`trigger-app-event`,text:{summary:`Invoke an app-defined automation event`},metadata:_u,run:(e,t)=>e.apps.triggerEvent(t),cliSchema:yu,cliReader:xu,daemonWriter:Cu})];function Tu(e){return[e.app,typeof e.payload==`string`?e.payload:JSON.stringify(e.payload)]}function Eu(e){return[e.event,...e.payload?[JSON.stringify(e.payload)]:[]]}function Du(e){return Ar(e)}const Ou=H({name:`session`,text:{summary:`List sessions, show the state dir, or publish a script`},metadata:V(`session`,`List active sessions, print the effective daemon state directory, or publish an armed open-to-destination script without closing its session`,{action:R([`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:P(`Optional .ad output path for save-script.`),force:L(`Atomically replace an existing save-script target.`)}),run:async(e,{action:t,path:n,force:r,...i})=>{let a=t??`list`;return Au(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)=>({...y(t),action:ku(e[0]),path:e[1],force:t.force}),cliOutputFormatter:Z.session});function ku(e){let t=e??`list`;if(t===`list`||t===`state-dir`||t===`save-script`)return t;throw new n(`INVALID_ARGS`,`session only supports list, state-dir, or save-script`)}function Au(e,t,r){if(e!==`save-script`&&(t!==void 0||r===!0))throw new n(`INVALID_ARGS`,`session ${e} does not accept a path or --force; use session save-script [path] [--force] to publish a recording.`)}const ju={viewport:E({width:A(),height:A(),message:k()},[`width`,`height`,`message`])},Mu=H({name:`viewport`,text:{summary:`Resize the active web viewport for the current session`},metadata:V(`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:N(I(`Viewport width in CSS pixels.`,{min:1})),height:N(I(`Viewport height in CSS pixels.`,{min:1}))}),run:(e,t)=>e.command.viewport(t),cliSchema:{positionalArgs:[`width`,`height`]},cliReader:(e,t)=>({...y(t),..._e(e)}),daemonWriter:_(u.viewport,e=>{let{width:t,height:n}=e;return[String(t),String(n)]}),cliOutputFormatter:Z.viewport}),Nu=U({name:`management`,commands:[...Ll,Qc,zl,mu,ml,Ou,hl,gl,Mu,...au,...wu]});function Pu(e){return{data:e.result,text:e.action===`reload`?`Reloaded React Native apps via ${e.result.reloadUrl}`:JSON.stringify(e.result,null,2)}}const Fu={metro:({input:e,result:t})=>Pu({result:t,action:e.action})},Iu=`metro`,Lu=U({name:`metro`,commands:[H({name:Iu,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. The reload URL keeps the bound bundle URL mount prefix instead of collapsing to the host root, 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:V(Iu,`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:N(R([`prepare`,`reload`])),projectRoot:P(),kind:z(k()),publicBaseUrl:P(),proxyBaseUrl:Tr(P(),{operatorPath:`Configure the remote proxy in the remote-config profile or operator config for the process serving these tools.`}),bearerToken:Tr(P(),{envFlagKeys:[`metroBearerToken`,`daemonAuthToken`]}),bridgeScope:z({type:`object`,additionalProperties:!0}),launchUrl:P(),port:I(),listenHost:P(),statusHost:P(),startupTimeoutMs:I(),probeTimeoutMs:I(),reuseExisting:L(),installDependenciesIfNeeded:L(),runtimeFilePath:P(),logPath:P(),metroHost:P(),metroPort:I(),bundleUrl:P(),timeoutMs:I()}),run:async(e,t)=>t.action===`prepare`?await e.metro.prepare(Ru(t)):await e.metro.reload(Bu(t)),cliSchema:{usageOverride:`metro prepare (--public-base-url <url> | --proxy-base-url <url>) [--project-root <path>] [--port <port>] [--kind auto|react-native|expo|repack]
26
+ agent-device metro reload [--metro-host <host>] [--metro-port <port>] [--bundle-url <url>]`,usageFlags:[],listUsageOverride:`metro`,positionalArgs:[`prepare|reload`],allowedFlags:[...Ni,...Mi]},cliReader:(e,t)=>{let r=(e[0]??``).toLowerCase();if(r!==`prepare`&&r!==`reload`)throw new n(`INVALID_ARGS`,`metro requires a subcommand: prepare or reload`);if(r===`reload`)return{action:r,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,timeoutMs:t.metroProbeTimeoutMs};if(!t.metroPublicBaseUrl&&!t.metroProxyBaseUrl)throw new n(`INVALID_ARGS`,`metro prepare requires --public-base-url <url> or --proxy-base-url <url>.`);return{action:r,projectRoot:t.metroProjectRoot,kind:cn(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:Fu.metro})]});function Ru(e){return{projectRoot:e.projectRoot,kind:e.kind,publicBaseUrl:e.publicBaseUrl,proxyBaseUrl:e.proxyBaseUrl,bearerToken:e.bearerToken,bridgeScope:e.bridgeScope??zu(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 zu(e){return e.tenant&&e.runId&&e.leaseId?{tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId}:void 0}function Bu(e){return{metroHost:e.metroHost,metroPort:e.metroPort,bundleUrl:e.bundleUrl,timeoutMs:e.timeoutMs}}function Vu(e,t){return e.includes(t)}function Hu(e,t,r={}){let i=t===void 0?void 0:r.normalize?.(t)??t;if(i!==void 0&&Vu(e,i))return i;let a=typeof r.message==`function`?r.message(t):r.message;throw new n(`INVALID_ARGS`,a??`Invalid value: ${t}. Use ${e.join(`|`)}.`)}const Uu=[`started`,`stopped`,`marked`,`cleared`,`restarted`,`removedRotatedFiles`];function Wu(e){return{data:e,text:e.path,stderr:vd([gd(e,[`active`,`state`,`backend`,`sizeBytes`]),cd(e),e.hint,_d(e.notes)])}}function Gu(e){let t=e.events??[];return{data:e,text:t.length>0?Yu(t):`No session events found.`,stderr:vd([gd(e,[`path`,`cursor`,`nextCursor`,`limit`])])}}function Ku(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(...pd(e));return{data:e,text:t.join(`
27
+ `),stderr:vd([gd(e,[`active`,`state`,`backend`,`include`,`scannedLines`,`matchedLines`]),_d(e.notes)])}}function qu(e){return{data:e,text:[`Audio probe: ${String(e.state??`stopped`)} heard=${String(e.heard===!0)}`,sd(`rmsDbfs`,e.rmsDbfs),sd(`peakDbfs`,e.peakDbfs)].filter(e=>!!e).join(`
28
+ `),stderr:vd([gd(e,[`active`,`backend`,`source`,`durationMs`,`elapsedMs`,`bucketMs`,`sampleCount`,`sourceCount`,`mediaElementCount`]),_d(e.notes)])}}const Ju={logs:d(Wu),events:d(Gu),network:d(Ku),audio:d(qu)};function Yu(e){let t=e.map(Xu),n=Math.min(Math.max(...t.map(e=>e.label.length),5),32);return t.map(e=>Zu(e,n)).join(`
29
+ `)}function Xu(e){return{timestamp:Qu(e.ts),label:$u(e),summary:ed(e)}}function Zu(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 Qu(e){return e?e.replace(`T`,` `):``}function $u(e){let t=e.command??`command`;switch(e.kind){case`request.started`:return`start ${t}`;case`request.finished`:return ud([e.status===`error`?`error`:`ok`,t,od(fd(e.details?.durationMs))]);case`action.recorded`:return`action ${t}`;default:return ud([e.kind??`event`,e.command])}}function ed(e){let t=td(e.summary,e);return`${t}${nd(e,t)}`.trim()}function td(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 nd(e,t){if(e.kind!==`action.recorded`)return``;let n=e.details;if(!n)return``;let r=[rd(n,t),ad(fd(n.textLength))].filter(e=>!!e);return r.length>0?` (${r.join(`, `)})`:``}function rd(e,t){let n=dd(e.ref)??dd(e.selector)??id(e);if(!(!n||t.includes(n)))return`target=${n}`}function id(e){let t=fd(e.x),n=fd(e.y);return t===void 0||n===void 0?void 0:`(${t}, ${n})`}function ad(e){return e===void 0?void 0:`text=${e} chars`}function od(e){return e===void 0?void 0:`${Math.round(e)}ms`}function sd(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 cd(e){return Uu.map(t=>ld(t,e[t])).filter(Boolean).join(` `)||void 0}function ld(e,t){return t==null?``:`${e}=${t}`}function ud(e){return e.filter(e=>!!e).join(` `)}function dd(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function fd(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function pd(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?hd(o,`headers`,e.headers):(md(o,`request headers`,e.requestHeaders),md(o,`response headers`,e.responseHeaders)),hd(o,`request`,e.requestBody),hd(o,`response`,e.responseBody),o}function md(e,t,n){!n||Object.keys(n).length===0||e.push(` ${t}: ${JSON.stringify(n)}`)}function hd(e,t,n){n!==void 0&&e.push(` ${t}: ${n}`)}function gd(e,t){return t.map(t=>e[t]!==void 0&&e[t]!==null?`${t}=${e[t]}`:``).filter(Boolean).join(` `)||void 0}function _d(e){let t=e?.filter(e=>e.length>0)??[];return t.length>0?t.join(`
30
+ `):void 0}function vd(e){return e.filter(e=>!!e).join(`
31
+ `)||void 0}const yd=`logs`,bd=`events`,xd=`network`,Sd=`audio`,Cd=[`dump`,`log`],wd=[`probe`],Td=[`start`,`status`,`stop`],Ed=V(yd,`Session app log info, start/stop streaming, diagnostics, and markers`,{action:R(gn),message:P(),restart:L()}),Dd=V(bd,`Read the daemon-owned session event timeline as paged JSON-friendly entries`,{limit:I(),cursor:P()}),Od=V(xd,`Dump recent HTTP(s) traffic parsed from the session app log`,{action:R(Cd),limit:I(),include:R(s)}),kd=V(Sd,`Measure browser or host-rendered simulator/emulator audio as compact dBFS buckets. Start a probe before requesting its status or stopping it.`,{action:R(wd),probeAction:R(Td),durationMs:I(`Probe duration in milliseconds.`),bucketMs:I(`Audio level bucket size in milliseconds.`)}),Ad=U({name:`observability`,commands:[H({name:yd,text:{summary:`Manage session app logs`},metadata:Ed,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)=>({...y(t),action:Fd(e[0]),message:e.slice(1).join(` `)||void 0,restart:t.restart}),daemonWriter:_(yd,e=>jd(e)),cliOutputFormatter:Ju.logs}),H({name:bd,text:{summary:`Read session event timeline`},metadata:Dd,run:(e,t)=>e.observability.events(t),cliSchema:{usageOverride:`events [limit] [cursor]`,listUsageOverride:`events`,positionalArgs:[`limit?`,`cursor?`]},cliReader:(e,t)=>({...y(t),limit:e[0]?.trim()?fr(e[0]):void 0,cursor:e[1]}),daemonWriter:e=>v(bd,Md(e),e),cliOutputFormatter:Ju.events}),H({name:xd,text:{summary:`Inspect HTTP(S) traffic from session logs`},metadata:Od,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)=>({...y(t),action:Id(e[0]),limit:fr(e[1]),include:t.networkInclude??Ld(e[2])}),daemonWriter:e=>v(xd,Nd(e),{...e,networkInclude:e.include}),cliOutputFormatter:Ju.network}),H({name:Sd,text:{summary:`Probe audio levels`},metadata:kd,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)=>({...y(t),action:Rd(e[0]),probeAction:zd(e[1]),durationMs:Bd(e[2]),bucketMs:fr(e[3])}),daemonWriter:e=>v(Sd,Pd(e),e),cliOutputFormatter:Ju.audio})]});function jd(e){return[e.action??`path`,...S(e.message)]}function Md(e){return e.cursor===void 0?C(e.limit):[e.limit===void 0?``:String(e.limit),e.cursor]}function Nd(e){return[...e.action?[e.action]:[],...C(e.limit)]}function Pd(e){return[e.action??`probe`,e.probeAction??`status`,...C(e.durationMs),...C(e.bucketMs)]}function Fd(e){if(e!==void 0)return Hu(gn,e,{message:`logs requires path, start, stop, doctor, mark, or clear`})}function Id(e){if(e!==void 0){if(e===`dump`||e===`log`)return e;throw new n(`INVALID_ARGS`,`network requires dump or log`)}}function Ld(e){if(e!==void 0)return Hu(s,e,{message:`network include must be summary, headers, body, or all`})}function Rd(e){if(e!==void 0)return Hu(wd,e,{message:`audio requires probe`})}function zd(e){if(e!==void 0)return Hu(Td,e,{message:`audio probe requires start, status, or stop`})}function Bd(e){let t=fr(e);return t===void 0?void 0:Math.round(t*1e3)}function Vd(e){let t=e;return{data:t,text:Ud(t)}}const Hd={perf:d(Vd)};function Ud(e){return Xd(e)??Wd(e)}function Wd(e){let t=l(e.artifact)?e.artifact:void 0;return t?Yd(t):Gd(l(e.metrics)?e.metrics:void 0)}function Gd(e){return l(e?.fps)?qd(e):Kd(e)??`Memory: unavailable - missing memory metric`}function Kd(e){let t=l(e?.memory)?e.memory:void 0;if(!t)return;if(t.available===!1)return`Memory: unavailable - ${lf(t)}`;let n=hf(t);return n?`Performance: ${n}`:`Memory: unavailable - missing memory metric`}function qd(e){let t=l(e?.fps)?e.fps:void 0;if(!t)return cf(`missing frame metric`);if(t.available===!1)return cf(lf(t));let n=uf(t);return n?Jd(t,n):cf(`missing dropped-frame summary`)}function Jd(e,t){let n=[`Frame health: ${t}`],r=pf(e);return r.length>0&&n.push(`Worst windows:`,...r),n.join(`
32
+ `)}function Yd(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?``:` (${yf(r)})`;return n?`Memory artifact (${t}): ${n}${i}`:`Memory artifact (${t}): captured${i}`}function Xd(e){return e.kind===`xctrace`?Zd(e):tf(e)}function Zd(e){let t=typeof e.perf==`string`?e.perf:void 0,n=$d(e);if(!t||!n||e.kind!==`xctrace`)return;let r=ef(n,typeof e.mode==`string`?e.mode:`capture`,t,e.template),i=Qd(e);return i.length>0?`${r}\nTop CPU self time:\n${i.join(`
33
+ `)}`:r}function Qd(e){let t=l(e.summary)?e.summary:void 0;return Array.isArray(t?.topFunctions)?t.topFunctions.slice(0,5).flatMap(e=>{if(!l(e))return[];let t=of(e.symbol),n=Q(e.selfSamplePercent);if(!t||n===void 0)return[];let r=of(e.binary);return[`- ${gf(n)} ${t}${r?` (${r})`:``}`]}):[]}function $d(e){return typeof e.outPath==`string`?e.outPath:typeof e.reportPath==`string`?e.reportPath:void 0}function ef(e,t,n,r){let i=[e,`Perf ${t}: ${n}`];return typeof r==`string`&&i.push(`Template: ${r}`),i.join(`
34
+ `)}function tf(e){let t=nf(e);if(!t)return;let n=`Perf ${t.action}: ${t.kind} ${t.type}${rf(e)}${af(e)}${sf(e)}`,r=Qd(e);return r.length>0?`${n}\nTop CPU self time:\n${r.join(`
35
+ `)}`:n}function nf(e){let t=of(e.action),n=of(e.kind),r=of(e.type);return t&&n&&r?{action:t,kind:n,type:r}:void 0}function rf(e){let t=of(e.state);return t?` state=${t}`:``}function af(e){let t=of(e.outPath);if(!t)return``;let n=Q(e.sizeBytes);return`\n${t}${n===void 0?``:` (${yf(n)})`}`}function of(e){return typeof e==`string`?e:void 0}function sf(e){let t=l(e.summary)?e.summary:void 0,n=l(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 ${gf(r)} (${Math.round(i)}/${Math.round(a)} frames)`}function cf(e){return`Frame health: unavailable - ${e}`}function lf(e){return typeof e.reason==`string`&&e.reason.length>0?e.reason:`not available`}function uf(e){let t=Q(e.droppedFramePercent),n=Q(e.droppedFrameCount);if(t!==void 0&&n!==void 0)return[`dropped ${gf(t)}`,df(n,Q(e.totalFrameCount)),ff(Q(e.sampleWindowMs))].filter(Boolean).join(` `)}function df(e,t){return t===void 0?`(${Math.round(e)} dropped frames)`:`(${Math.round(e)}/${Math.round(t)} frames)`}function ff(e){return e===void 0?``:`window ${_f(e)}`}function pf(e){return Array.isArray(e.worstWindows)?e.worstWindows.flatMap(e=>{if(!l(e))return[];let t=mf(e);return t?[t]:[]}):[]}function mf(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 ${_f(i)}`;return`- +${_f(t)}-+${_f(n)}: ${Math.round(r)} missed-deadline frames${a}`}function hf(e){if(e?.available!==!0)return;let t=Q(e.residentMemoryKb)??Q(e.totalPssKb)??Q(e.totalRssKb);return t===void 0?void 0:`memory ${vf(t)}`}function Q(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function gf(e){return`${Number.isInteger(e)?e:e.toFixed(1)}%`}function _f(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 vf(e){let t=e/1024;return`${t>=10?Math.round(t):t.toFixed(1)}MB`}function yf(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 bf=`perf`,xf=U({name:`perf`,commands:[H({name:bf,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 internals, use agent-device react-devtools.`,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:V(bf,`Collect frame health, memory diagnostics, and platform profiling artifacts with compact agent-readable summaries.`,{area:N(R(St)),subject:R(Et),action:R(xt),kind:R(mt),template:P(`xctrace template name, for example Time Profiler.`),out:P(`Output artifact path.`),tracePath:P(`Existing .trace path to report, defaults to the latest session trace.`)}),run:(e,t)=>e.observability.perf(t),cliSchema:{usageOverride:`perf frames --json
36
36
  agent-device perf memory sample --json
37
37
  agent-device perf memory snapshot [--kind android-hprof|memgraph] [--out <path>]
38
38
  agent-device perf cpu profile start --kind xctrace [--template <name>] --out <profile.trace>
@@ -44,9 +44,25 @@ import{D as e,M as t,N as n,O as r,T as i,g as a,p as o,t as s,x as c}from"./sdk
44
44
  agent-device perf cpu profile report --kind simpleperf --out <cpu-report.json>
45
45
  agent-device perf trace start|stop --kind perfetto [--out <path>]
46
46
 
47
- 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)=>({...y(t),...xf(e,{kind:Df(t.kind),template:t.perfTemplate,out:t.out})}),daemonWriter:_(_f,e=>yf(e)),cliOutputFormatter:zd.perf})]});function yf(e){let t=e.area;return t===`cpu`?bf([...S(t),...S(e.subject),...S(e.action),...S(e.kind)],e):t===`trace`?bf([...S(t),...S(e.action),...S(e.kind)],e):[...S(t),...S(e.action)]}function bf(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 xf(e,t={}){let n=Cf(e[0]);if(n===`cpu`)return{area:n,subject:Tf(e[1]),action:wf(e[2]),kind:Ef(t.kind),template:t.template,out:t.out};if(n===`trace`)return{area:n,action:wf(e[1]),kind:Ef(t.kind),template:t.template,out:t.out};let r=wf(e[1]),i=Ef(t.kind);return Sf(n,r,i,t.out),{area:n,action:r,kind:i,out:t.out}}function Sf(e,t,r,i){if(e===`frames`){if(r!==void 0)throw new n(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(i!==void 0)throw new n(`INVALID_ARGS`,`--out is only supported with perf memory snapshot, perf cpu profile, or perf trace`)}if(e===`memory`){if(t!==`snapshot`&&r!==void 0)throw new n(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(t!==`snapshot`&&i!==void 0)throw new n(`INVALID_ARGS`,`--out is only supported with perf memory snapshot`)}}function Cf(e){let t=e?.toLowerCase();if(gt(t))throw new n(`INVALID_ARGS`,vt);if(ht(t))return t;throw new n(`INVALID_ARGS`,ft)}function wf(e){if(e===void 0)return;let t=e.toLowerCase();if(mt(t))return t;throw new n(`INVALID_ARGS`,wt)}function Tf(e){let t=e?.toLowerCase();if(t!==void 0&&_t(t))return t;throw new n(`INVALID_ARGS`,yt)}function Ef(e){if(e===void 0)return;let t=e.toLowerCase();if(St(t))return t;throw new n(`INVALID_ARGS`,Ct)}function Df(e){return typeof e==`string`?Ef(e):void 0}const Of=`react-native`,kf=U({name:`react-native`,commands:[H({name:Of,text:{summary:`Run React Native automation helpers`},metadata:V(Of,`Run supported React Native automation helpers. Use dismiss-overlay to close a visible development error overlay before continuing normal UI automation.`,{action:N(R([`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)=>({...y(t),action:Af(e[0])}),daemonWriter:_(Of,e=>[T(e.action,`react-native requires action`)])})]});function Af(e){if(e===`dismiss-overlay`)return e;throw new n(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}function jf(e){let t=e,n=typeof t.outPath==`string`?t.outPath:``,r=Pf(t);if(r.length<=1)return{data:t,text:Nf(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(`
48
- `)}}const Mf={record:d(jf)};function Nf(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(`
49
- `)}function Pf(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 Ff=`record`,If=`trace`,Lf=[`start`,`stop`],Rf=V(Ff,`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:N(R(Lf)),path:P(),fps:I(),maxSize:Sr(oe.migration.record),quality:R(He),hideTouches:L(),recordingScope:R(Ue)},{parseableOutput:!0}),zf=V(If,`Start or stop trace-log capture and return the resulting artifact when capture ends. Use the same artifact path for the matching start and stop requests when an explicit path is required.`,{action:N(R(Lf)),path:P()}),Bf={start:[`recordingScope`,`fps`,`quality`,`hideTouches`],stop:[],"contact-sheet":[`out`]},Vf={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(Bf).flat())],flagsByAction:Bf},Hf={usageOverride:`trace start <path> | trace stop <path>`,listUsageOverride:`trace start <path> | trace stop <path>`,positionalArgs:[`start|stop`,`path?`]},Uf=(e,t)=>({...y(t),action:Xf(e[0],Ff),path:e[1],fps:t.fps,quality:t.quality,hideTouches:t.hideTouches,recordingScope:t.recordingScope}),Wf=(e,t)=>({...y(t),action:Xf(e[0],If),path:e[1]}),Gf=_(Ff,e=>Yf(e)),Kf=e=>(ae(`record`,e),Gf(e)),qf=_(If,e=>Yf(e)),Jf=U({name:`recording`,commands:[H({name:Ff,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. 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:Rf,run:(e,t)=>e.recording.record(t),cliSchema:Vf,cliReader:Uf,daemonWriter:Kf,cliOutputFormatter:Mf.record}),H({name:If,text:{summary:`Start or stop trace capture`,cliDetail:`Pass that path as the same positional argument to start and stop.`},metadata:zf,run:(e,t)=>e.recording.trace(t),cliSchema:Hf,cliReader:Wf,daemonWriter:qf})]});function Yf(e){return[e.action,...S(e.path)]}function Xf(e,t){if(e===`start`||e===`stop`)return e;throw new n(`INVALID_ARGS`,`${t} requires start|stop`)}const Zf=2097152;async function Qf(e){let t=cn(e.inputPath,{cwd:e.cwd}),n=ep(t,e.inputPath);if(it(t,e.replayBackend)!==`maestro`)return $f(t,{[t]:n},e.inputPath);let{collectMaestroFlowSources:r}=await import(`./src8.js`).then(e=>e.t);return $f(t,r({entryPath:t,entrySource:n,env:e.env,readSource:tp}),e.inputPath)}function $f(e,t,n){return np(t,n),{entry:e,files:t}}function ep(e,t){try{return mn.readFileSync(e,`utf8`)}catch(r){throw new n(`INVALID_ARGS`,`replay script not found on this machine: ${t}`,{path:e,hint:`Replay scripts are read by the client and sent to the daemon, so the path must resolve where you ran the command.`},r instanceof Error?r:void 0)}}function tp(e){try{return mn.readFileSync(e,`utf8`)}catch{return}}function np(e,t){let r=Object.values(e).reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0);if(!(r<=2097152))throw new n(`INVALID_ARGS`,`replay script sources for ${t} total ${r} bytes, over the ${Zf}-byte limit; split the flow or drop unused runFlow includes.`,{limitBytes:Zf,totalBytes:r})}const rp=/[*?[\]{}]/;function ip(e){let t=e.replayBackend===`maestro`?new Set([`.yaml`,`.yml`,`.ad`]):new Set([`.ad`]),n=[],r=[];for(let i of e.inputs){let a=ap(i,e.cwd,t);if(a.source===`file`){n.push(...a.paths);continue}r.push(a.source===`directory`?up(a.paths):cp(a.paths))}return up([...n,...r.flat()])}function ap(e,t,r){let i=cn(e,{cwd:t});if(mn.existsSync(i)){let t=mn.statSync(i);return t.isDirectory()?{paths:sp(i,r),source:`directory`}:t.isFile()?(op(e,i,r),{paths:[i],source:`file`}):{paths:[],source:`file`}}if(!dp(e))throw new n(`INVALID_ARGS`,`test input not found: ${e}`);return{source:`glob`,paths:mn.globSync(ln(e),{cwd:t}).map(e=>p.isAbsolute(e)?e:p.resolve(t,e)).filter(e=>r.has(p.extname(e).toLowerCase())&&fp(e))}}function op(e,t,r){if(!r.has(p.extname(t).toLowerCase()))throw at(t)&&!r.has(`.yaml`)?new n(`INVALID_ARGS`,rt(`test`,e)):new n(`INVALID_ARGS`,`test does not support this file type: ${e}`)}function sp(e,t){let n=[],r=mn.opendirSync(e);try{let i;for(;(i=r.readSync())!==null;){let r=p.join(e,i.name);i.isDirectory()?n.push(...sp(r,t)):i.isFile()&&t.has(p.extname(i.name).toLowerCase())&&n.push(r)}}finally{r.closeSync()}return n}function cp(e){return e.map(e=>p.normalize(e)).sort((e,t)=>{let n=lp(e)-lp(t);return n===0?e.localeCompare(t):n})}function lp(e){return+(p.extname(e).toLowerCase()===`.ad`)}function up(e){return[...new Set(e.map(e=>p.normalize(e)))]}function dp(e){return rp.test(e)}function fp(e){try{return mn.statSync(e).isFile()}catch{return!1}}const pp=`replay`,mp=`test`,hp=V(pp,`Run a recorded automation script, including compatible Maestro YAML flows. A script without a terminal close leaves its session active for subsequent automation.`,{path:N(P()),update:L(),backend:P(),maestro:L(),env:kr(),metroHost:P(`Metro/debug host hint inherited by replay-opened sessions.`),metroPort:I(`Metro/debug port hint inherited by replay-opened sessions.`),bundleUrl:P(`Bundle URL hint inherited by replay-opened sessions.`),resumeFrom:I(),resumePlanDigest:P(),keepSession:L(`Leave the session active by suppressing exactly an authored terminal close in native .ad.`),timeoutMs:I(`Maximum wall-clock duration for the replay request.`),saveScript:z({oneOf:[j(),k()]}),force:L()}),gp=V(mp,`Run one or more replay scripts as a serial test suite`,{paths:N(kr()),update:L(),backend:P(),maestro:L(),env:kr(),metroHost:P(`Metro/debug host hint inherited by each test session.`),metroPort:I(`Metro/debug port hint inherited by each test session.`),bundleUrl:P(`Bundle URL hint inherited by each test session.`),failFast:L(),timeoutMs:I(),retries:I(),recordVideo:L(),artifactsDir:P(),shardAll:I(),shardSplit:I()}),_p={replay:E({replayed:A(),healed:A(),session:k(),sessionActive:j(`True iff the session is still active — the script had no terminal close.`),artifactPaths:xr(),snapshotDiagnostics:M(),message:k()},[`replayed`,`healed`,`session`,`sessionActive`,`artifactPaths`,`message`]),test:E({total:A(),executed:A(),passed:A(),failed:A(),skipped:A(),notRun:A(),durationMs:A(),failures:{type:`array`,items:M()},tests:{type:`array`,items:M()},snapshotDiagnostics:M()},[`total`,`executed`,`passed`,`failed`,`skipped`,`notRun`,`durationMs`,`failures`,`tests`])},vp={usageOverride:`replay <path> | replay export <file.ad> [--out <path>]`,usageFlags:[],positionalArgs:[`path`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...Pi,...ji,`replayFrom`,`replayPlanDigest`,`replayKeepSession`,`timeoutMs`,`out`,`saveScript`,`force`],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.`}},yp={usageOverride:`test <path-or-glob>...`,usageFlags:[],listUsageOverride:`test <path-or-glob>...`,positionalArgs:[`pathOrGlob`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...Pi,...ji,`failFast`,`timeoutMs`,`retries`,`recordVideo`,`artifactsDir`,`reporter`,`reportJunit`,`shardAll`,`shardSplit`]},bp=U({name:`replay`,commands:[H({name:pp,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:hp,run:(e,t)=>e.replay.run(Zc(t)),cliSchema:vp,cliReader:(e,t)=>({...y(t),path:w(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}),daemonWriter:async e=>{let t=T(e.path,`replay requires path`),n=Cp(e),r=Tp(process.env);return v(pp,[t],{...e,replayUpdate:e.update,replayBackend:n,replayEnv:e.env,replayShellEnv:r,replayScriptSource:await Qf({inputPath:t,cwd:Sp(e),replayBackend:n,env:xp(e,r)}),replayFrom:e.resumeFrom,replayPlanDigest:e.resumePlanDigest,replayKeepSession:e.keepSession,saveScript:e.saveScript})},cliOutputFormatter:f}),H({name:mp,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:gp,run:(e,t)=>e.replay.test(Zc(t)),cliSchema:yp,cliReader:(e,t)=>({...y(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}),daemonWriter:async e=>{let t=e.paths??[],n=Cp(e),r=Sp(e),i=Tp(process.env),a=xp(e,i);return v(mp,t,{...wp(e),replayUpdate:e.update,replayBackend:n,replayEnv:e.env,replayShellEnv:i,replayScriptSources:await Promise.all(ip({inputs:t,cwd:r,replayBackend:n}).map(async e=>await Qf({inputPath:e,cwd:r,replayBackend:n,env:a})))})}})]});function xp(e,t){return{...nt(t),...tt(et(e.env))}}function Sp(e){return typeof e.cwd==`string`&&e.cwd.length>0?e.cwd:process.cwd()}function Cp(e){return e.backend??(e.maestro===!0?`maestro`:void 0)}function wp(e){let t={...e};return delete t.reporter,delete t.reportJunit,t}function Tp(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&n.startsWith(`AD_VAR_`)&&(t[n]=r);return t}function Ep(e){return{data:e,text:kp(e)}}function Dp(e){if(e.platform===`android`&&e.action===`status`){let t=[`Keyboard visible: ${e.visible===!0?`yes`:`no`}`,`Input type: ${e.type??e.inputType??`unknown`}`,`Input owner: ${e.inputOwner??`unknown`}`];return e.inputMethodPackage&&t.push(`Input method: ${e.inputMethodPackage}`),e.focusedPackage&&t.push(`Focused package: ${e.focusedPackage}`),e.focusedResourceId&&t.push(`Focused resource: ${e.focusedResourceId}`),t.push(`Next action: ${jp(e.visible,e.inputOwner)}`),{data:e,text:t.join(`
50
- `)}}return kt(e)}function Op(e){return e.action===`read`?{data:e,text:e.text}:kt(e)}const $=Fs({appstate:d(Ep),back:f,home:f,orientation:f,fold:f,"app-switcher":f,"action-button":f,keyboard:d(Dp),clipboard:d(Op),"tv-remote":f});function kp(e){if(e.platform===`ios`)return Ap(e);if(e.platform===`android`){let t=[`Foreground app: ${e.package??`unknown`}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join(`
51
- `)}return null}function Ap(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(`
52
- `)}function jp(e,t){return t===`ime`?`Focused input appears to be owned by the keyboard/IME; dismiss or change the IME before retrying text entry.`:e===!0?`Keyboard is visible and focused input appears app-owned; fill/type can proceed.`:`Keyboard is hidden; focus an app field before type, or use fill with a concrete target.`}const Mp=`back`,Np=`orientation`,Pp=`fold`,Fp=`keyboard`,Ip=`clipboard`,Lp=`tv-remote`,Rp=[`read`,`write`],zp=[`status`,`dismiss`,`enter`,`return`],Bp={back:E({action:O(`back`),mode:D(lt),message:k()},[`action`,`mode`,`message`]),home:E({action:O(`home`),message:k()},[`action`,`message`]),orientation:E({action:O(`orientation`),orientation:D(an),message:k(),confirmed:j(),warning:k()},[`action`,`orientation`,`message`]),"app-switcher":E({action:O(`app-switcher`),message:k()},[`action`,`message`]),fold:E({action:O(`fold`),pose:D(rn),hingeAngleDegrees:A(`Hinge angle CoreDevice read back after the pose settled.`),screen:E({display:k(`CoreDevice name of the panel the device now lights.`),coordinateSpace:O(Qt),widthPt:A(`Panel width in native panel points (pixels divided by point scale), NOT snapshot coordinates; take a fresh snapshot to place a tap.`),heightPt:A(`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:k()},[`action`,`pose`,`hingeAngleDegrees`,`message`]),"action-button":E({action:O(`action-button`),message:k()},[`action`,`message`]),"tv-remote":E({action:O(`tv-remote`),button:D(pn),durationMs:A(),message:k()},[`action`,`button`,`message`]),clipboard:{type:`object`,oneOf:[E({action:O(`read`),text:k()},[`action`,`text`]),E({action:O(`write`),textLength:A(),message:k()},[`action`,`textLength`,`message`])]},appstate:{type:`object`,oneOf:[E({platform:D([`ios`,`macos`]),appName:k(),appBundleId:k(),source:D([`session`,`runner`],`runner when a live runner read the session app state; session when the record alone answered.`),state:D(o,`The session app XCUIApplication state as a live runner reads it; absent with source session.`),surface:D(dt),device_udid:k(`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`]),E({platform:O(`android`),package:k(),activity:k()},[`platform`,`package`,`activity`])]},keyboard:E({platform:D([`android`,`ios`]),action:D([`status`,`dismiss`,`enter`]),visible:j(),wasVisible:j(),dismissed:j(),attempts:A(),inputType:k(),type:D([`text`,`number`,`email`,`phone`,`password`,`datetime`,`unknown`]),inputMethodPackage:k(),focusedPackage:k(),focusedResourceId:k(),inputOwner:D([`app`,`ime`,`unknown`]),message:k()},[`platform`,`action`])},Vp=V(Mp,`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:R(lt),...rs(Mp)}),Hp=V(Np,`Set device orientation on iOS and Android`,{orientation:N(R(an))}),Up={pose:R(rn,`Instant preset; mutually exclusive with keyframes.`),keyframes:z({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:nn},angle:{type:`number`,minimum:0,maximum:180}}}})},Wp=V(Pp,`Fold or unfold a foldable iPhone simulator (iPhone Duo) into the closed, half-open, or open pose, or follow timestamped angle keyframes, by sending a simulator HID hinge event, then read the hinge angle back from CoreDevice to confirm it. A pose change moves the app to a different panel with a different point size, so 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-only; requires the iOS simulator SDK; Device Hub and host Accessibility permission are not required. A simulator scoped to a non-default simulator set is refused with UNSUPPORTED_OPERATION and reason unsupported-device-scope; run fold against a simulator in the default set.`,Up,{readInput:e=>{let{pose:t,keyframes:n,...r}=Lr(e,Up);return{...r,...$t({pose:t,keyframes:n})}}}),Gp={...Wp,inputSchema:{...Wp.inputSchema,oneOf:[{required:[`pose`],not:{required:[`keyframes`]}},{required:[`keyframes`],not:{required:[`pose`]}}]}},Kp=V(Fp,`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:R(zp)}),qp=V(Ip,`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:N(R(Rp)),text:P()},{parseableOutput:!0}),Jp=V(Lp,`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:N(R(pn)),durationMs:I(`Press duration in milliseconds. tvOS and Vega OS use the exact hold duration; Android TV maps any positive value to an ADB longpress (${fn(`android`)}).`,{min:0})}),Yp={usageOverride:`back [--in-app|--system] [--settle]`,usageFlags:[],allowedFlags:[`backMode`,...is(Mp)]},Xp={usageOverride:`orientation <portrait|portrait-upside-down|landscape-left|landscape-right>`,positionalArgs:[`orientation`]},Zp={usageOverride:`fold [${tn}]`,positionalArgs:[`pose?`],allowedFlags:Di},Qp={usageOverride:`keyboard [status|get|dismiss|enter|return]`,positionalArgs:[`action?`]},$p={usageOverride:`clipboard read | clipboard write <text>`,listUsageOverride:`clipboard read | clipboard write <text>`,positionalArgs:[`read|write`,`text?`],allowsExtraPositionals:!0},em={usageOverride:`tv-remote [press|longpress] ${un}`,listUsageOverride:`tv-remote press|longpress <button> [--duration-ms <ms>]`,positionalArgs:[`press|longpress?`,`button`],allowedFlags:[`durationMs`]},tm=(e,t)=>({...y(t),mode:t.backMode}),nm=(e,t)=>({...y(t),orientation:on(e[0])}),rm=(e,t)=>({...y(t),...$t({pose:e[0],keyframes:t.keyframes===void 0?void 0:en(t.keyframes)})}),im=(e,t)=>({...y(t),...wm(e)}),am=(e,t)=>({...y(t),...Tm(e)}),om=(e,t)=>({...y(t),...Em(e,t.durationMs)}),sm=e=>v(Mp,[],{...e,backMode:Sm(e.mode)}),cm=_(Np,e=>[T(e.orientation,`orientation requires orientation`)]),lm=e=>{let t=$t(e);return v(Pp,t.pose?[t.pose]:[],{...e,keyframes:t.keyframes?JSON.stringify(t.keyframes):void 0})},um=_(Fp,e=>S(e.action)),dm=_(Ip,e=>Cm(e)),fm=_(Lp,e=>[T(e.button,`tv-remote requires button`)]),pm=Qr({name:`appstate`,description:`Show foreground app/activity (Android; iOS answers per command)`,text:{summary:`Show the foreground app and activity`},run:(e,t)=>e.command.appState(t),cliOutputFormatter:$.appstate}),mm=H({name:Mp,text:{summary:`Navigate back in the app or system`},metadata:Vp,run:(e,t)=>e.command.back(t),cliSchema:Yp,cliReader:tm,daemonWriter:sm,cliOutputFormatter:$.back}),hm=Qr({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}),gm=H({name:Np,text:{summary:`Set device orientation`},metadata:Hp,run:(e,t)=>e.command.orientation(t),cliSchema:Xp,cliReader:nm,daemonWriter:cm,cliOutputFormatter:$.orientation}),_m=H({name:Pp,text:{summary:`Fold or unfold a foldable iPhone simulator`,cliDetail:`iPhone Duo simulators only. Sends a simulator HID hinge event and confirms the hinge angle through CoreDevice; refs and coordinates do not survive a pose change.`},metadata:Gp,run:(e,t)=>e.command.fold(t),cliSchema:Zp,cliReader:rm,daemonWriter:lm,cliOutputFormatter:$.fold}),vm=Qr({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`]}),ym=H({name:Fp,text:{summary:`Inspect, press, or dismiss the device keyboard`},metadata:Kp,run:(e,t)=>e.command.keyboard(t),cliSchema:Qp,cliReader:im,daemonWriter:um,cliOutputFormatter:$.keyboard}),bm=H({name:Ip,text:{summary:`Read or write device clipboard text`},metadata:qp,run:(e,t)=>e.command.clipboard(t),cliSchema:$p,cliReader:am,daemonWriter:dm,cliOutputFormatter:$.clipboard}),xm=U({name:`system`,commands:[pm,mm,hm,gm,_m,vm,Qr({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`]}),ym,bm,H({name:Lp,text:{summary:`Press a TV remote/D-pad button`,cliDetail:`longpress holds for 500ms by default; --duration-ms overrides the preset.`},metadata:Jp,run:(e,t)=>e.command.tvRemote(t),cliSchema:em,cliReader:om,daemonWriter:fm,cliOutputFormatter:$[`tv-remote`]})]});function Sm(e){return e===`in-app`||e===`system`?e:void 0}function Cm(e){return e.action===`read`?[`read`]:[`write`,e.text]}function wm(e){if(e.length>1)throw new n(`INVALID_ARGS`,`keyboard accepts at most one action argument.`);return h({action:Dm(e[0])})}function Tm(e){let t=e[0]?.toLowerCase();if(t!==`read`&&t!==`write`)throw new n(`INVALID_ARGS`,`clipboard requires a subcommand: read or write.`);if(t===`read`){if(e.length!==1)throw new n(`INVALID_ARGS`,`clipboard read does not accept additional arguments.`);return{action:t}}if(e.length<2)throw new n(`INVALID_ARGS`,`clipboard write requires text.`);return{action:t,text:e.slice(1).join(` `)}}function Em(e,t){let r=e[0]?.toLowerCase(),i=r===`press`||r===`longpress`?e.slice(1):e;if(i.length!==1)throw new n(`INVALID_ARGS`,`tv-remote requires exactly one button: ${pn.join(`, `)}.`);let a=t??(r===`longpress`?500:void 0);return h({button:dn(i[0]),durationMs:a})}function Dm(e){let t=e?.toLowerCase();if(t===`get`)return`status`;if(t===void 0||t===`status`||t===`dismiss`||t===`enter`||t===`return`)return t;throw new n(`INVALID_ARGS`,`keyboard action must be status, get, dismiss, enter, or return.`)}const Om=[hc,Au,Jo,xm,kf,bp,Dd,vf,$o,Jf,Pu,bi];function km(){return Om.flatMap(e=>[...e.metadata])}function Am(){return Om.flatMap(e=>[...e.definitions])}function jm(){return Fm(`cliSchemas`)}function Mm(){return Fm(`cliReaders`)}function Nm(){return Fm(`daemonWriters`)}function Pm(){return Fm(`cliOutputFormatters`)}function Fm(e){let t={};for(let n of Om){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}export{A,yn as B,Li as C,O as D,j as E,Rn as F,Pn as I,xn as L,k as M,dr as N,D as O,fr as P,Sn as R,Ii as S,di as T,as as _,Am as a,zi as b,_p as c,uu as d,Rl as f,ac as g,mc as h,Nm as i,E as j,M as k,Ou as l,yl as m,Mm as n,km as o,Fl as p,jm as r,Bp as s,Pm as t,fu as u,Ro as v,Ai as w,Fi as x,yo as y,vn as z};
47
+ 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)=>({...y(t),...wf(e,{kind:Af(t.kind),template:t.perfTemplate,out:t.out})}),daemonWriter:_(bf,e=>Sf(e)),cliOutputFormatter:Hd.perf})]});function Sf(e){let t=e.area;return t===`cpu`?Cf([...S(t),...S(e.subject),...S(e.action),...S(e.kind)],e):t===`trace`?Cf([...S(t),...S(e.action),...S(e.kind)],e):[...S(t),...S(e.action)]}function Cf(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 wf(e,t={}){let n=Ef(e[0]);if(n===`cpu`)return{area:n,subject:Of(e[1]),action:Df(e[2]),kind:kf(t.kind),template:t.template,out:t.out};if(n===`trace`)return{area:n,action:Df(e[1]),kind:kf(t.kind),template:t.template,out:t.out};let r=Df(e[1]),i=kf(t.kind);return Tf(n,r,i,t.out),{area:n,action:r,kind:i,out:t.out}}function Tf(e,t,r,i){if(e===`frames`){if(r!==void 0)throw new n(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(i!==void 0)throw new n(`INVALID_ARGS`,`--out is only supported with perf memory snapshot, perf cpu profile, or perf trace`)}if(e===`memory`){if(t!==`snapshot`&&r!==void 0)throw new n(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(t!==`snapshot`&&i!==void 0)throw new n(`INVALID_ARGS`,`--out is only supported with perf memory snapshot`)}}function Ef(e){let t=e?.toLowerCase();if(_t(t))throw new n(`INVALID_ARGS`,yt);if(gt(t))return t;throw new n(`INVALID_ARGS`,pt)}function Df(e){if(e===void 0)return;let t=e.toLowerCase();if(ht(t))return t;throw new n(`INVALID_ARGS`,Tt)}function Of(e){let t=e?.toLowerCase();if(t!==void 0&&vt(t))return t;throw new n(`INVALID_ARGS`,bt)}function kf(e){if(e===void 0)return;let t=e.toLowerCase();if(Ct(t))return t;throw new n(`INVALID_ARGS`,wt)}function Af(e){return typeof e==`string`?kf(e):void 0}const jf=`react-native`,Mf=U({name:`react-native`,commands:[H({name:jf,text:{summary:`Run React Native automation helpers`},metadata:V(jf,`Run supported React Native automation helpers. Use dismiss-overlay to close a visible development error overlay before continuing normal UI automation.`,{action:N(R([`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)=>({...y(t),action:Nf(e[0])}),daemonWriter:_(jf,e=>[T(e.action,`react-native requires action`)])})]});function Nf(e){if(e===`dismiss-overlay`)return e;throw new n(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}function Pf(e){let t=e,n=typeof t.outPath==`string`?t.outPath:``,r=Lf(t);if(r.length<=1)return{data:t,text:If(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(`
48
+ `)}}const Ff={record:d(Pf)};function If(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(`
49
+ `)}function Lf(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 Rf=`record`,zf=`trace`,Bf=[`start`,`stop`],Vf=V(Rf,`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:N(R(Bf)),path:P(),fps:I(),maxSize:wr(oe.migration.record),quality:R(Ue),hideTouches:L(),recordingScope:R(We)},{parseableOutput:!0}),Hf=V(zf,`Start or stop trace-log capture and return the resulting artifact when capture ends. Use the same artifact path for the matching start and stop requests when an explicit path is required.`,{action:N(R(Bf)),path:P()}),Uf={start:[`recordingScope`,`fps`,`quality`,`hideTouches`],stop:[],"contact-sheet":[`out`]},Wf={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(Uf).flat())],flagsByAction:Uf},Gf={usageOverride:`trace start <path> | trace stop <path>`,listUsageOverride:`trace start <path> | trace stop <path>`,positionalArgs:[`start|stop`,`path?`]},Kf=(e,t)=>({...y(t),action:$f(e[0],Rf),path:e[1],fps:t.fps,quality:t.quality,hideTouches:t.hideTouches,recordingScope:t.recordingScope}),qf=(e,t)=>({...y(t),action:$f(e[0],zf),path:e[1]}),Jf=_(Rf,e=>Qf(e)),Yf=e=>(ae(`record`,e),Jf(e)),Xf=_(zf,e=>Qf(e)),Zf=U({name:`recording`,commands:[H({name:Rf,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. 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:Vf,run:(e,t)=>e.recording.record(t),cliSchema:Wf,cliReader:Kf,daemonWriter:Yf,cliOutputFormatter:Ff.record}),H({name:zf,text:{summary:`Start or stop trace capture`,cliDetail:`Pass that path as the same positional argument to start and stop.`},metadata:Hf,run:(e,t)=>e.recording.trace(t),cliSchema:Gf,cliReader:qf,daemonWriter:Xf})]});function Qf(e){return[e.action,...S(e.path)]}function $f(e,t){if(e===`start`||e===`stop`)return e;throw new n(`INVALID_ARGS`,`${t} requires start|stop`)}const ep=2097152;async function tp(e){let t=ln(e.inputPath,{cwd:e.cwd}),n=rp(t,e.inputPath);if(at(t,e.replayBackend)!==`maestro`)return np(t,{[t]:n},e.inputPath);let{collectMaestroFlowSources:r}=await import(`./src8.js`).then(e=>e.t);return np(t,r({entryPath:t,entrySource:n,env:e.env,readSource:ip}),e.inputPath)}function np(e,t,n){return ap(t,n),{entry:e,files:t}}function rp(e,t){try{return hn.readFileSync(e,`utf8`)}catch(r){throw new n(`INVALID_ARGS`,`replay script not found on this machine: ${t}`,{path:e,hint:`Replay scripts are read by the client and sent to the daemon, so the path must resolve where you ran the command.`},r instanceof Error?r:void 0)}}function ip(e){try{return hn.readFileSync(e,`utf8`)}catch{return}}function ap(e,t){let r=Object.values(e).reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0);if(!(r<=2097152))throw new n(`INVALID_ARGS`,`replay script sources for ${t} total ${r} bytes, over the ${ep}-byte limit; split the flow or drop unused runFlow includes.`,{limitBytes:ep,totalBytes:r})}const op=/[*?[\]{}]/;function sp(e){let t=e.replayBackend===`maestro`?new Set([`.yaml`,`.yml`,`.ad`]):new Set([`.ad`]),n=[],r=[];for(let i of e.inputs){let a=cp(i,e.cwd,t);if(a.source===`file`){n.push(...a.paths);continue}r.push(a.source===`directory`?pp(a.paths):dp(a.paths))}return pp([...n,...r.flat()])}function cp(e,t,r){let i=ln(e,{cwd:t});if(hn.existsSync(i)){let t=hn.statSync(i);return t.isDirectory()?{paths:up(i,r),source:`directory`}:t.isFile()?(lp(e,i,r),{paths:[i],source:`file`}):{paths:[],source:`file`}}if(!mp(e))throw new n(`INVALID_ARGS`,`test input not found: ${e}`);return{source:`glob`,paths:hn.globSync(un(e),{cwd:t}).map(e=>p.isAbsolute(e)?e:p.resolve(t,e)).filter(e=>r.has(p.extname(e).toLowerCase())&&hp(e))}}function lp(e,t,r){if(!r.has(p.extname(t).toLowerCase()))throw ot(t)&&!r.has(`.yaml`)?new n(`INVALID_ARGS`,it(`test`,e)):new n(`INVALID_ARGS`,`test does not support this file type: ${e}`)}function up(e,t){let n=[],r=hn.opendirSync(e);try{let i;for(;(i=r.readSync())!==null;){let r=p.join(e,i.name);i.isDirectory()?n.push(...up(r,t)):i.isFile()&&t.has(p.extname(i.name).toLowerCase())&&n.push(r)}}finally{r.closeSync()}return n}function dp(e){return e.map(e=>p.normalize(e)).sort((e,t)=>{let n=fp(e)-fp(t);return n===0?e.localeCompare(t):n})}function fp(e){return+(p.extname(e).toLowerCase()===`.ad`)}function pp(e){return[...new Set(e.map(e=>p.normalize(e)))]}function mp(e){return op.test(e)}function hp(e){try{return hn.statSync(e).isFile()}catch{return!1}}const gp=`replay`,_p=`test`,vp=V(gp,`Run a recorded automation script, including compatible Maestro YAML flows. A script without a terminal close leaves its session active for subsequent automation.`,{path:N(P()),update:L(),backend:P(),maestro:L(),env:jr(),metroHost:P(`Metro/debug host hint inherited by replay-opened sessions.`),metroPort:I(`Metro/debug port hint inherited by replay-opened sessions.`),bundleUrl:P(`Bundle URL hint inherited by replay-opened sessions.`),resumeFrom:I(),resumePlanDigest:P(),keepSession:L(`Leave the session active by suppressing exactly an authored terminal close in native .ad.`),timeoutMs:I(`Maximum wall-clock duration for the replay request.`),saveScript:z({oneOf:[j(),k()]}),force:L()}),yp=V(_p,`Run one or more replay scripts as a serial test suite`,{paths:N(jr()),update:L(),backend:P(),maestro:L(),env:jr(),metroHost:P(`Metro/debug host hint inherited by each test session.`),metroPort:I(`Metro/debug port hint inherited by each test session.`),bundleUrl:P(`Bundle URL hint inherited by each test session.`),failFast:L(),timeoutMs:I(),retries:I(),recordVideo:L(),artifactsDir:P(),shardAll:I(),shardSplit:I()}),bp={replay:E({replayed:A(),healed:A(),session:k(),sessionActive:j(`True iff the session is still active — the script had no terminal close.`),artifactPaths:Cr(),snapshotDiagnostics:M(),message:k()},[`replayed`,`healed`,`session`,`sessionActive`,`artifactPaths`,`message`]),test:E({total:A(),executed:A(),passed:A(),failed:A(),skipped:A(),notRun:A(),durationMs:A(),failures:{type:`array`,items:M()},tests:{type:`array`,items:M()},snapshotDiagnostics:M()},[`total`,`executed`,`passed`,`failed`,`skipped`,`notRun`,`durationMs`,`failures`,`tests`])},xp={usageOverride:`replay <path> | replay export <file.ad> [--out <path>]`,usageFlags:[],positionalArgs:[`path`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...Ii,...Ni,`replayFrom`,`replayPlanDigest`,`replayKeepSession`,`timeoutMs`,`out`,`saveScript`,`force`],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.`}},Sp={usageOverride:`test <path-or-glob>...`,usageFlags:[],listUsageOverride:`test <path-or-glob>...`,positionalArgs:[`pathOrGlob`],allowsExtraPositionals:!0,allowedFlags:[`replayMaestro`,...Ii,...Ni,`failFast`,`timeoutMs`,`retries`,`recordVideo`,`artifactsDir`,`reporter`,`reportJunit`,`shardAll`,`shardSplit`]},Cp=U({name:`replay`,commands:[H({name:gp,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:vp,run:(e,t)=>e.replay.run(el(t)),cliSchema:xp,cliReader:(e,t)=>({...y(t),path:w(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}),daemonWriter:async e=>{let t=T(e.path,`replay requires path`),n=Ep(e),r=Op(process.env);return v(gp,[t],{...e,replayUpdate:e.update,replayBackend:n,replayEnv:e.env,replayShellEnv:r,replayScriptSource:await tp({inputPath:t,cwd:Tp(e),replayBackend:n,env:wp(e,r)}),replayFrom:e.resumeFrom,replayPlanDigest:e.resumePlanDigest,replayKeepSession:e.keepSession,saveScript:e.saveScript})},cliOutputFormatter:f}),H({name:_p,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:yp,run:(e,t)=>e.replay.test(el(t)),cliSchema:Sp,cliReader:(e,t)=>({...y(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}),daemonWriter:async e=>{let t=e.paths??[],n=Ep(e),r=Tp(e),i=Op(process.env),a=wp(e,i);return v(_p,t,{...Dp(e),replayUpdate:e.update,replayBackend:n,replayEnv:e.env,replayShellEnv:i,replayScriptSources:await Promise.all(sp({inputs:t,cwd:r,replayBackend:n}).map(async e=>await tp({inputPath:e,cwd:r,replayBackend:n,env:a})))})}})]});function wp(e,t){return{...rt(t),...nt(tt(e.env))}}function Tp(e){return typeof e.cwd==`string`&&e.cwd.length>0?e.cwd:process.cwd()}function Ep(e){return e.backend??(e.maestro===!0?`maestro`:void 0)}function Dp(e){let t={...e};return delete t.reporter,delete t.reportJunit,t}function Op(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&n.startsWith(`AD_VAR_`)&&(t[n]=r);return t}function kp(e){return{data:e,text:Mp(e)}}function Ap(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: ${Pp(e.visible,e.inputOwner)}`),{data:e,text:t.join(`
50
+ `)}}return At(e)}function jp(e){return e.action===`read`?{data:e,text:e.text}:At(e)}const $=Rs({appstate:d(kp),back:f,home:f,orientation:f,fold:f,"app-switcher":f,"action-button":f,keyboard:d(Ap),clipboard:d(jp),"tv-remote":f});function Mp(e){if(e.platform===`ios`)return Np(e);if(e.platform===`android`){let t=[`Foreground app: ${e.package??`unknown`}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join(`
51
+ `)}return null}function Np(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(`
52
+ `)}function Pp(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 Fp=`back`,Ip=`orientation`,Lp=`fold`,Rp=`keyboard`,zp=`clipboard`,Bp=`tv-remote`,Vp=[`read`,`write`],Hp=[`status`,`dismiss`,`enter`,`return`],Up={back:E({action:O(`back`),mode:D(ut),message:k()},[`action`,`mode`,`message`]),home:E({action:O(`home`),message:k()},[`action`,`message`]),orientation:E({action:O(`orientation`),orientation:D(sn),message:k(),confirmed:j(),warning:k()},[`action`,`orientation`,`message`]),"app-switcher":E({action:O(`app-switcher`),message:k()},[`action`,`message`]),fold:E({action:O(`fold`),pose:D(on),hingeAngleDegrees:A(`Hinge angle CoreDevice read back after the pose settled.`),screen:E({display:k(`CoreDevice name of the panel the device now lights.`),coordinateSpace:O($t),widthPt:A(`Panel width in native panel points (pixels divided by point scale), NOT snapshot coordinates; take a fresh snapshot to place a tap.`),heightPt:A(`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:k()},[`action`,`pose`,`hingeAngleDegrees`,`message`]),"action-button":E({action:O(`action-button`),message:k()},[`action`,`message`]),"tv-remote":E({action:O(`tv-remote`),button:D(mn),durationMs:A(),message:k()},[`action`,`button`,`message`]),clipboard:{type:`object`,oneOf:[E({action:O(`read`),text:k()},[`action`,`text`]),E({action:O(`write`),textLength:A(),message:k()},[`action`,`textLength`,`message`])]},appstate:{type:`object`,oneOf:[E({platform:D([`ios`,`macos`]),appName:k(),appBundleId:k(),source:D([`session`,`runner`],`runner when a live runner read the session app state; session when the record alone answered.`),state:D(o,`The session app XCUIApplication state as a live runner reads it; absent with source session.`),surface:D(ft),device_udid:k(`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`]),E({platform:O(`android`),package:k(),activity:k()},[`platform`,`package`,`activity`])]},keyboard:E({platform:D([`android`,`ios`]),action:D([`status`,`dismiss`,`enter`]),visible:j(),wasVisible:j(),dismissed:j(),attempts:A(),inputType:k(),type:D([`text`,`number`,`email`,`phone`,`password`,`datetime`,`unknown`]),inputMethodPackage:k(),focusedPackage:k(),focusedResourceId:k(),inputOwner:D([`app`,`ime`,`unknown`]),message:k()},[`platform`,`action`])},Wp={hingeEvent:`simulator HID hinge event`,permissions:`Device Hub and host Accessibility permission are not required.`,unsupportedScope:`UNSUPPORTED_OPERATION and reason unsupported-device-scope`},Gp=`Fold or unfold a foldable iPhone simulator (iPhone Duo) into the closed, half-open, or open pose, or follow timestamped angle keyframes, by sending a ${Wp.hingeEvent}, then read the hinge angle back from CoreDevice to confirm it. A pose change moves the app to a different panel with a different point size, so 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-only; requires the iOS simulator SDK; ${Wp.permissions} A simulator scoped to a non-default simulator set is refused with ${Wp.unsupportedScope}; run fold against a simulator in the default set.`,Kp={summary:`Foldable Apple devices: panels, pose, and which screen you are on`,body:`agent-device help foldable
53
+
54
+ 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.
55
+
56
+ Screens are handled for you:
57
+ Each iOS simulator capture resolves the CoreDevice display table, captures the lit panel explicitly, and normalizes density with that panel's own point scale. Do not add a screen flag to the normal loop; there is none, because the lit panel is always the only capturable one: the dark panel yields an all-black PNG.
58
+ The two panels are different sizes (iPhone Duo: 466x678 points closed on the outer panel, 669x951 open on the inner). A pose change therefore invalidates every ref and coordinate. Re-snapshot after any pose change and never carry coordinates or refs across one.
59
+ Check which panel is lit before trusting a geometry claim: agent-device screenshot reports its point size, and 466x678 versus 669x951 says which panel you captured.
60
+
61
+ Changing the pose:
62
+ agent-device fold closed | half-open | open
63
+ 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 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 ${Wp.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).
64
+ 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.
65
+ 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.
66
+
67
+ 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). ${Wp.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.
68
+ If a task asserts behavior for more than one pose, fold to each pose and re-snapshot, and report which poses the run covered.`},qp=V(Fp,`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:R(ut),...as(Fp)}),Jp=V(Ip,`Set device orientation on iOS and Android`,{orientation:N(R(sn))}),Yp={pose:R(on,`Instant preset; mutually exclusive with keyframes.`),keyframes:z({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:rn},angle:{type:`number`,minimum:0,maximum:180}}}})},Xp=V(Lp,Gp,Yp,{readInput:e=>{let{pose:t,keyframes:n,...r}=zr(e,Yp);return{...r,...an({pose:t,keyframes:n})}}}),Zp={...Xp,inputSchema:{...Xp.inputSchema,oneOf:[{required:[`pose`],not:{required:[`keyframes`]}},{required:[`keyframes`],not:{required:[`pose`]}}]}},Qp=V(Rp,`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:R(Hp)}),$p=V(zp,`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:N(R(Vp)),text:P()},{parseableOutput:!0}),em=V(Bp,`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:N(R(mn)),durationMs:I(`Press duration in milliseconds. tvOS and Vega OS use the exact hold duration; Android TV maps any positive value to an ADB longpress (${pn(`android`)}).`,{min:0})}),tm={usageOverride:`back [--in-app|--system] [--settle]`,usageFlags:[],allowedFlags:[`backMode`,...os(Fp)]},nm={usageOverride:`orientation <portrait|portrait-upside-down|landscape-left|landscape-right>`,positionalArgs:[`orientation`]},rm={usageOverride:`fold [${tn}]`,positionalArgs:[`pose?`],allowedFlags:ki},im={usageOverride:`keyboard [status|get|dismiss|enter|return]`,positionalArgs:[`action?`]},am={usageOverride:`clipboard read | clipboard write <text>`,listUsageOverride:`clipboard read | clipboard write <text>`,positionalArgs:[`read|write`,`text?`],allowsExtraPositionals:!0},om={usageOverride:`tv-remote [press|longpress] ${dn}`,listUsageOverride:`tv-remote press|longpress <button> [--duration-ms <ms>]`,positionalArgs:[`press|longpress?`,`button`],allowedFlags:[`durationMs`]},sm=(e,t)=>({...y(t),mode:t.backMode}),cm=(e,t)=>({...y(t),orientation:en(e[0])}),lm=(e,t)=>({...y(t),...an({pose:e[0],keyframes:t.keyframes===void 0?void 0:nn(t.keyframes)})}),um=(e,t)=>({...y(t),...Am(e)}),dm=(e,t)=>({...y(t),...jm(e)}),fm=(e,t)=>({...y(t),...Mm(e,t.durationMs)}),pm=e=>v(Fp,[],{...e,backMode:Om(e.mode)}),mm=_(Ip,e=>[T(e.orientation,`orientation requires orientation`)]),hm=e=>{let t=an(e);return v(Lp,t.pose?[t.pose]:[],{...e,keyframes:t.keyframes?JSON.stringify(t.keyframes):void 0})},gm=_(Rp,e=>S(e.action)),_m=_(zp,e=>km(e)),vm=_(Bp,e=>[T(e.button,`tv-remote requires button`)]),ym=ei({name:`appstate`,description:`Show foreground app/activity (Android; iOS answers per command)`,text:{summary:`Show the foreground app and activity`},run:(e,t)=>e.command.appState(t),cliOutputFormatter:$.appstate}),bm=H({name:Fp,text:{summary:`Navigate back in the app or system`},metadata:qp,run:(e,t)=>e.command.back(t),cliSchema:tm,cliReader:sm,daemonWriter:pm,cliOutputFormatter:$.back}),xm=ei({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}),Sm=H({name:Ip,text:{summary:`Set device orientation`},metadata:Jp,run:(e,t)=>e.command.orientation(t),cliSchema:nm,cliReader:cm,daemonWriter:mm,cliOutputFormatter:$.orientation}),Cm=H({name:Lp,text:{summary:`Fold or unfold a foldable iPhone simulator`,cliDetail:`iPhone Duo simulators only. Sends a ${Wp.hingeEvent} and confirms the hinge angle through CoreDevice; refs and coordinates do not survive a pose change.`},metadata:Zp,run:(e,t)=>e.command.fold(t),cliSchema:rm,cliReader:lm,daemonWriter:hm,cliOutputFormatter:$.fold}),wm=ei({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`]}),Tm=H({name:Rp,text:{summary:`Inspect, press, or dismiss the device keyboard`},metadata:Qp,run:(e,t)=>e.command.keyboard(t),cliSchema:im,cliReader:um,daemonWriter:gm,cliOutputFormatter:$.keyboard}),Em=H({name:zp,text:{summary:`Read or write device clipboard text`},metadata:$p,run:(e,t)=>e.command.clipboard(t),cliSchema:am,cliReader:dm,daemonWriter:_m,cliOutputFormatter:$.clipboard}),Dm=U({name:`system`,commands:[ym,bm,xm,Sm,Cm,wm,ei({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`]}),Tm,Em,H({name:Bp,text:{summary:`Press a TV remote/D-pad button`,cliDetail:`longpress holds for 500ms by default; --duration-ms overrides the preset.`},metadata:em,run:(e,t)=>e.command.tvRemote(t),cliSchema:om,cliReader:fm,daemonWriter:vm,cliOutputFormatter:$[`tv-remote`]})]});function Om(e){return e===`in-app`||e===`system`?e:void 0}function km(e){return e.action===`read`?[`read`]:[`write`,e.text]}function Am(e){if(e.length>1)throw new n(`INVALID_ARGS`,`keyboard accepts at most one action argument.`);return h({action:Nm(e[0])})}function jm(e){let t=e[0]?.toLowerCase();if(t!==`read`&&t!==`write`)throw new n(`INVALID_ARGS`,`clipboard requires a subcommand: read or write.`);if(t===`read`){if(e.length!==1)throw new n(`INVALID_ARGS`,`clipboard read does not accept additional arguments.`);return{action:t}}if(e.length<2)throw new n(`INVALID_ARGS`,`clipboard write requires text.`);return{action:t,text:e.slice(1).join(` `)}}function Mm(e,t){let r=e[0]?.toLowerCase(),i=r===`press`||r===`longpress`?e.slice(1):e;if(i.length!==1)throw new n(`INVALID_ARGS`,`tv-remote requires exactly one button: ${mn.join(`, `)}.`);let a=t??(r===`longpress`?500:void 0);return h({button:fn(i[0]),durationMs:a})}function Nm(e){let t=e?.toLowerCase();if(t===`get`)return`status`;if(t===void 0||t===`status`||t===`dismiss`||t===`enter`||t===`return`)return t;throw new n(`INVALID_ARGS`,`keyboard action must be status, get, dismiss, enter, or return.`)}const Pm=[vc,Nu,Xo,Dm,Mf,Cp,Ad,xf,ts,Zf,Lu,Si];function Fm(){return Pm.flatMap(e=>[...e.metadata])}function Im(){return Pm.flatMap(e=>[...e.definitions])}function Lm(){return Vm(`cliSchemas`)}function Rm(){return Vm(`cliReaders`)}function zm(){return Vm(`daemonWriters`)}function Bm(){return Vm(`cliOutputFormatters`)}function Vm(e){let t={};for(let n of Pm){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}export{M as A,yn as B,Ri as C,j as D,pi as E,mr as F,zn as I,Fn as L,E as M,k as N,O,pr as P,Sn as R,Li as S,Mi as T,bn as V,cc as _,Im as a,xo as b,Kp as c,hu as d,pu as f,_c as g,Sl as h,zm as i,A as j,D as k,bp as l,Rl as m,Rm as n,Fm as o,Vl as p,Lm as r,Up as s,Bm as t,ju as u,ss as v,zi as w,Vi as x,Bo as y,Cn as z};