agent-device 0.20.1 → 0.20.3

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 (108) hide show
  1. package/README.md +0 -2
  2. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.1.apk → agent-device-android-ime-helper-0.20.3.apk} +0 -0
  3. package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.3.apk.sha256 +1 -0
  4. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.1.manifest.json → agent-device-android-ime-helper-0.20.3.manifest.json} +4 -4
  5. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.1.apk → agent-device-android-snapshot-helper-0.20.3.apk} +0 -0
  6. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.3.apk.sha256 +1 -0
  7. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.1.manifest.json → agent-device-android-snapshot-helper-0.20.3.manifest.json} +6 -6
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +2 -0
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +1 -35
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +0 -208
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +184 -0
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Orientation.swift +92 -0
  13. package/dist/src/agent-device-client.js +2 -2
  14. package/dist/src/android-adb.d.ts +3 -26
  15. package/dist/src/android-adb.js +1 -1
  16. package/dist/src/android.js +1 -1
  17. package/dist/src/app-helpers.js +1 -0
  18. package/dist/src/app-lifecycle.js +5 -5
  19. package/dist/src/app-log-request-scope.js +1 -1
  20. package/dist/src/app-resolution.js +1 -1
  21. package/dist/src/apps.js +5 -5
  22. package/dist/src/cli-config.js +1 -1
  23. package/dist/src/cli-help.js +6 -6
  24. package/dist/src/cli-runner.js +1 -1
  25. package/dist/src/cli.js +14 -14
  26. package/dist/src/click-button.d.ts +5 -0
  27. package/dist/src/client-metro.js +1 -0
  28. package/dist/src/command-schema.js +3 -3
  29. package/dist/src/context.js +1 -1
  30. package/dist/src/contracts.d.ts +1 -1
  31. package/dist/src/device-input-state.d.ts +26 -0
  32. package/dist/src/device-input-state.js +1 -1
  33. package/dist/src/device.js +9 -0
  34. package/dist/src/devices2.js +1 -1
  35. package/dist/src/find.js +1 -1
  36. package/dist/src/generic.js +1 -1
  37. package/dist/src/gesture-plan-types.js +1 -0
  38. package/dist/src/gesture-plan.js +1 -0
  39. package/dist/src/index.d.ts +1174 -1413
  40. package/dist/src/input-actions.js +4 -4
  41. package/dist/src/install-artifact.js +5 -1
  42. package/dist/src/install-artifact2.js +1 -0
  43. package/dist/src/interaction-snapshot.js +1 -1
  44. package/dist/src/interaction.d.ts +3 -6
  45. package/dist/src/interaction.js +1 -1
  46. package/dist/src/interactor.js +2 -2
  47. package/dist/src/interactor2.js +1 -1
  48. package/dist/src/internal/bin.js +1 -1
  49. package/dist/src/internal/daemon.js +14 -22
  50. package/dist/src/lease-context.js +1 -1
  51. package/dist/src/lease.js +1 -1
  52. package/dist/src/limrun.d.ts +437 -0
  53. package/dist/src/limrun.js +1 -0
  54. package/dist/src/linux.js +1 -1
  55. package/dist/src/logcat.js +1 -5
  56. package/dist/src/metro.d.ts +71 -2
  57. package/dist/src/metro.js +1 -1
  58. package/dist/src/metro2.js +1 -1
  59. package/dist/src/notifications.js +1 -1
  60. package/dist/src/physical-device-control.js +1 -0
  61. package/dist/src/plist.js +1 -0
  62. package/dist/src/react-native.js +1 -1
  63. package/dist/src/recording-export-quality.js +12 -13
  64. package/dist/src/register-builtins.js +1 -1
  65. package/dist/src/registry.js +18 -18
  66. package/dist/src/remote-config.d.ts +5 -2
  67. package/dist/src/remote-config.js +1 -1
  68. package/dist/src/remote-config2.js +1 -0
  69. package/dist/src/reporting.js +8 -8
  70. package/dist/src/runner-client.js +1 -1
  71. package/dist/src/runner-disposal.js +1 -2
  72. package/dist/src/runner-lease.js +1 -1
  73. package/dist/src/runtime-transport.js +1 -1
  74. package/dist/src/runtime.js +3 -3
  75. package/dist/src/runtime2.js +1 -1
  76. package/dist/src/sdk-android-adb.d.ts +4 -2
  77. package/dist/src/sdk-batch-runner.d.ts +13 -3
  78. package/dist/src/sdk-batch-runner.js +1 -1
  79. package/dist/src/sdk-contracts.d.ts +28 -2
  80. package/dist/src/sdk-contracts.js +2 -2
  81. package/dist/src/sdk-finders.d.ts +1 -1
  82. package/dist/src/sdk-remote-config.d.ts +119 -4
  83. package/dist/src/selector-runtime.js +1 -1
  84. package/dist/src/selector-vocabulary.js +1 -1
  85. package/dist/src/selectors.d.ts +1 -1
  86. package/dist/src/server.js +2 -2
  87. package/dist/src/session-target-evidence.js +1 -1
  88. package/dist/src/session.js +8 -8
  89. package/dist/src/simulator.js +1 -1
  90. package/dist/src/snapshot-diagnostics.js +4 -4
  91. package/dist/src/snapshot2.js +1 -1
  92. package/dist/src/tool-provider.js +3 -3
  93. package/dist/src/tool-provider2.js +1 -1
  94. package/dist/src/tool-provider3.js +1 -1
  95. package/dist/src/tv-remote.d.ts +213 -0
  96. package/dist/src/xml.js +2 -0
  97. package/package.json +49 -30
  98. package/server.json +2 -2
  99. package/smithery.yaml +1 -1
  100. package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.1.apk.sha256 +0 -1
  101. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.1.apk.sha256 +0 -1
  102. package/dist/src/android-system-chrome.js +0 -1
  103. package/dist/src/client-metro-companion.js +0 -1
  104. package/dist/src/metro-types.d.ts +0 -52
  105. package/dist/src/project-runtime.js +0 -1
  106. package/dist/src/scoped-provider.js +0 -1
  107. package/dist/src/simctl.js +0 -1
  108. package/dist/src/snapshot-quality.js +0 -1
@@ -1,6 +1,6 @@
1
- import{S as e,T as t,_ as n,c as r,d as i,p as a,t as o,v as s}from"./sdk-contracts.js";import{C as c,N as l,j as u,p as d,s as f,v as p}from"./sdk-android-adb.js";import{$ as m,G as h,I as g,L as _,R as v,T as y,et as b,m as x,n as S,t as C}from"./sdk-batch-runner.js";import{$n as w,Bt as T,E as ee,Ft as E,Ht as te,Kn as ne,Lt as re,Nt as ie,Qn as D,Rt as ae,Ut as oe,Vt as se,Wt as ce,_n as le,an as ue,cr as O,dt as de,gn as fe,hn as pe,i as me,in as he,jt as ge,m as _e,mn as ve,sr as ye,u as be,ut as xe,yn as Se,zn as Ce}from"./recording-export-quality.js";import{$ as we,A as Te,B as Ee,F as De,H as Oe,K as ke,O as k,Y as Ae,a as je,at as Me,et as Ne,it as Pe,j as Fe,mt as Ie,n as Le,nt as Re,ot as ze,pt as Be,rt as Ve,st as He,t as Ue,tt as We,z as Ge}from"./snapshot-diagnostics.js";import{n as Ke}from"./version.js";import{_ as qe,c as A,d as Je,h as j,l as Ye,m as Xe,o as M,p as Ze,s as N}from"./sdk-device.js";import{A as Qe,B as $e,E as et,F as tt,H as nt,I as rt,M as it,_ as at,c as ot,ft as st,h as ct,ht as lt,m as ut,pt as dt,rt as ft,t as pt,w as mt}from"./sdk-selectors.js";import{t as ht}from"./timeouts.js";import{t as gt}from"./project-runtime.js";import{n as _t,t as vt}from"./runtime-transport.js";import{n as yt,t as bt}from"./snapshot-quality.js";import{a as xt,i as St,l as Ct,o as wt}from"./android-input-method-overlays.js";import{n as Tt}from"./sdk-app-inventory.js";import{o as Et}from"./runtime.js";import{f as Dt,p as Ot,s as kt}from"./app-lifecycle.js";import{d as At,f as jt,p as Mt,s as Nt}from"./logcat.js";import{a as Pt,o as Ft,r as It,s as Lt}from"./boot-diagnostics.js";import{o as Rt}from"./selector-vocabulary.js";import{$ as zt,Q as P,Y as Bt,at as Vt,ct as Ht,et as Ut,it as Wt,lt as Gt,ot as Kt,rt as qt,st as Jt,u as Yt,ut as Xt}from"./runner-disposal.js";import{C as F,S as Zt,a as Qt,c as $t,d as en,g as I,h as tn,i as nn,l as L,m as rn,n as an,s as R,t as z,u as on,x as sn,y as cn}from"./context.js";import{i as ln,n as un,o as dn,s as fn,t as pn}from"./register-builtins.js";import{a as mn}from"./tool-provider.js";import{r as hn}from"./helper.js";import{n as gn}from"./simctl.js";import{c as _n,i as vn,l as yn,n as bn,r as xn,s as Sn,t as Cn}from"./runner-client.js";import{n as wn,s as Tn}from"./agent-browser-tool.js";import{$ as En,$t as Dn,A as On,B as kn,C as An,Cn as jn,Ct as Mn,D as Nn,Dt as Pn,En as Fn,Et as In,F as Ln,G as Rn,H as zn,I as Bn,J as Vn,K as Hn,L as Un,M as Wn,Mt as Gn,N as Kn,Nn as qn,Ot as Jn,P as Yn,Q as Xn,R as Zn,S as Qn,Sn as $n,St as er,T as tr,Tn as nr,Tt as rr,U as ir,V as ar,W as or,X as sr,Y as cr,Z as lr,Zt as ur,_ as dr,_n as fr,_t as pr,a as mr,at as hr,b as gr,bn as _r,bt as vr,c as yr,cn as br,ct as xr,d as Sr,dn as Cr,dt as wr,et as Tr,f as Er,ft as Dr,g as Or,gt as kr,h as Ar,ht as jr,i as Mr,j as Nr,jn as Pr,k as Fr,l as Ir,ln as Lr,lt as Rr,m as zr,mt as Br,n as Vr,nt as Hr,o as Ur,on as Wr,ot as Gr,p as Kr,q as qr,r as Jr,rn as Yr,rt as Xr,s as Zr,st as Qr,t as $r,tt as ei,u as ti,un as ni,ut as ri,v as ii,vn as ai,vt as oi,w as si,wn as ci,wt as li,x as ui,xn as di,xt as fi,y as pi,yn as mi,yt as hi,z as gi}from"./internal/daemon.js";import{i as _i,n as B,r as vi,t as yi}from"./compatibility-policy.js";import"./apps.js";import{a as bi,n as xi}from"./simulator.js";import{i as Si}from"./app-resolution.js";import{a as Ci,n as wi,o as Ti,r as Ei,t as Di}from"./session-target-evidence.js";import{createHash as Oi}from"node:crypto";import V,{promises as ki}from"node:fs";import Ai from"node:os";import H from"node:path";import{access as ji}from"node:fs/promises";import{setTimeout as Mi}from"node:timers/promises";import Ni from"node:vm";function Pi(e){throw new n(`UNSUPPORTED_OPERATION`,`install_from_source ${String(e.kind)} sources require a compatible remote daemon`)}function Fi(e){let t=e.meta?.installSource;if(!t)throw new n(`INVALID_ARGS`,`install_from_source requires a source payload`);switch(t.kind){case`url`:if(!t.url||t.url.trim().length===0)throw new n(`INVALID_ARGS`,`install_from_source url source requires a non-empty url`);return t;case`path`:if(!t.path||t.path.trim().length===0)throw new n(`INVALID_ARGS`,`install_from_source path source requires a non-empty path`);return t;case`github-actions-artifact`:throw new n(`UNSUPPORTED_OPERATION`,`install_from_source github-actions-artifact sources require a compatible remote daemon`);default:Pi(t)}}function Ii(e){let t=Fi(e),n=e.meta?.uploadedArtifactId;return!n||t.kind!==`path`?{source:t,cleanup:()=>{}}:{source:{kind:`path`,path:qn(n,e.meta?.tenantId)},cleanup:()=>{Pr(n)}}}function Li(e){return e===`ios`||e===`android`?e:void 0}function Ri(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(r!==void 0&&r<=0)throw new n(`INVALID_ARGS`,`install_from_source retentionMs must be a positive integer`);return{enabled:!0,ttlMs:r}}async function zi(e){let t=Li(e.flags?.platform);if(e.session){if(t&&e.session.device.platform!==t)throw new n(`INVALID_ARGS`,`install_from_source requested platform ${t}, but session is bound to ${e.session.device.platform}`);return await Or(e.session.device),e.session.device}if(!t)throw new n(`INVALID_ARGS`,`install_from_source requires platform "ios" or "android" when no session is provided`);let r=await I(e.flags??{});return await Or(r),r}async function Bi(e){let{prepared:t,retention:n,req:r,session:i,sessionName:a}=e;if(n.enabled)return await ui({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:r.meta?.tenantId,sessionName:i?a:void 0,ttlMs:n.ttlMs})}function Vi(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}function Hi(e){let{session:t,sessionStore:n,req:r,data:i}=e;Ar(n,t,r,`install_source`,i,{positionals:[]})}async function Ui(t){let{req:n,sessionName:r,sessionStore:i}=t,a=i.get(r);try{let e=Ii(n),t=Ri(n),o=await zi({session:a,flags:n.flags}),s=L(`install`,o,{message:`install_from_source is not supported on this device`});if(s)return s;let c=Vt(n.meta?.requestId);if(N(o)){let{prepareIosInstallArtifact:s}=await import(`./install-artifact.js`).then(e=>e.t),l=await s(e.source,{signal:c});return await Wi({prepared:l,retention:t,req:n,resolvedSourceCleanup:()=>e.cleanup(),session:a,sessionName:r,sessionStore:i,buildResult:async e=>await Gi(o,l,e)})}let{prepareAndroidInstallArtifact:l}=await import(`./logcat.js`).then(e=>e.r),u=await l(e.source,{signal:c});return await Wi({prepared:u,retention:t,req:n,resolvedSourceCleanup:()=>e.cleanup(),session:a,sessionName:r,sessionStore:i,buildResult:async e=>await Ki(o,u,e)})}catch(t){return{ok:!1,error:e(t)}}}async function Wi(e){let t;try{t=await Bi(e);let n=await e.buildResult(t),r=w(n,Zi(n));return Hi({session:e.session,sessionStore:e.sessionStore,req:e.req,data:r}),{ok:!0,data:r}}catch(n){throw t&&await pi(t.materializationId,e.req.meta?.tenantId).catch(()=>{}),n}finally{await e.prepared.cleanup(),e.resolvedSourceCleanup()}}async function Gi(e,t,n){let r=await Zt(e,t.installablePath,{appIdentifierHint:t.bundleId});if(!r){let{installIosInstallablePath:n}=await import(`./apps.js`).then(e=>e.t);await n(e,t.installablePath)}return qi(t,r,n)}async function Ki(e,t,n){let r=await Zt(e,t.installablePath,{packageNameHint:t.packageName}),i=await Xi(e,t,r),{inferAndroidAppName:a}=await import(`./app-lifecycle.js`).then(e=>e.t),o=a(i);return{...Vi(n),packageName:i,...Yi(r?.appName??o),launchTarget:r?.launchTarget??i}}function qi(e,t,n){let r=Ji(e,t),i=t?.appName??e.appName;return{...Vi(n),bundleId:r,...Yi(i),launchTarget:t?.launchTarget??r}}function Ji(e,t){let r=t?.bundleId??e.bundleId;if(r)return r;throw new n(`COMMAND_FAILED`,`Installed iOS app identity could not be resolved from the artifact`)}function Yi(e){return e?{appName:e}:{}}async function Xi(e,t,r){let i=r?.packageName??r?.launchTarget;if(i)return i;let{installAndroidInstallablePathAndResolvePackageName:a}=await import(`./app-lifecycle.js`).then(e=>e.t),o=await a(e,t.installablePath,t.packageName);if(!o)throw new n(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return o}function Zi(e){return`Installed: ${de(e)}`}async function Qi(t){let{req:r}=t;try{let e=r.meta?.materializationId?.trim();if(!e)throw new n(`INVALID_ARGS`,`release_materialized_paths requires a materializationId`);return await pi(e,r.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(t){return{ok:!1,error:e(t)}}}function U(e){return N(e)&&e.kind===`simulator`}function $i(e){return e.platform===`android`&&e.kind===`emulator`}function W(e,t,n){return t||ai(n)?null:R(`INVALID_ARGS`,`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}function ea(e){return typeof e?.session==`string`&&e.session.trim().length>0}async function ta(e,t){F(e)||!U(e)||t<=0||await new Promise(e=>setTimeout(e,t))}async function G(e){let t=ai(e.flags)||!e.session?await I(e.flags??{},{allowStoppedAndroidAvdPlaceholders:e.allowStoppedAndroidAvdPlaceholders}):await na(e.session.device);return e.ensureReady!==!1&&await Or(t),t}async function na(e){if(F(e)||!N(e)||e.kind!==`simulator`||process.platform!==`darwin`)return e;if(Sn(e.id)?.alive)return{...e,booted:!0};let t={platform:`ios`,target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await I(t)}catch(e){if(!(e instanceof n)||e.code!==`DEVICE_NOT_FOUND`)throw e}return await I({platform:`ios`,target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function ra(e){let t=e.flags?.device?.trim();if(t)return t;if(e.resolvedDevice?.platform===`android`&&e.resolvedDevice.kind===`emulator`)return e.resolvedDevice.name;if(e.sessionDevice?.platform===`android`&&e.sessionDevice.kind===`emulator`)return e.sessionDevice.name}function ia(e,t){return t?Pn(t,e).length===0:!1}const aa=`debug_http_host`,oa=`dev_server_https`,sa=`RCT_jsLocation`,ca=`RCT_packager_scheme`,la=`React Native runtime hints require adb run-as access to the app sandbox. Verify the app is debuggable and the selected package/device are correct.`,ua=[`<?xml version="1.0" encoding="utf-8" standalone="yes" ?>`,`<map>`,`</map>`,``].join(`
2
- `);function da(e){return vt(e)!==void 0}async function fa(e){let{device:t,appId:n,runtime:r}=e;if(F(t)||!n)return;let i=vt(r);if(i){if(t.platform===`android`){await ha(t,n,i);return}N(t)&&t.kind===`simulator`&&await Ca(t,n,i)}}async function pa(e){let{device:t,appId:n}=e;if(n){if(t.platform===`android`){await ga(t,n);return}N(t)&&t.kind===`simulator`&&await wa(t,n)}}function ma(e){return[`shared_prefs/${e}_preferences.xml`,`shared_prefs/ReactNativeDevPrefs.xml`]}async function ha(e,t,n){Aa(t);let r=[];for(let i of ma(t)){let a=Ea(await _a(e,t,i),aa,`${n.host}:${n.port}`);a=Da(a,oa,n.scheme===`https`),r.push({path:i,xml:a})}await va(e,t,r)}async function ga(e,t){Aa(t);let n=[];for(let r of ma(t)){let i=await _a(e,t,r),a=ka(ka(i,aa),oa);a!==i&&n.push({path:r,xml:a})}n.length!==0&&await va(e,t,n)}async function _a(e,t,n){let r=await Nt(e,[`shell`,`run-as`,t,`cat`,n],{allowFailure:!0});return r.exitCode===0?Ta(r.stdout):ua}async function va(e,t,n){await ya(e,t);try{await xa(e,t,n)}catch(e){throw Sa(e,t)}}async function ya(e,t){let n=[`shell`,`run-as`,t,`id`],r=await Nt(e,n,{allowFailure:!0});if(r.exitCode!==0)throw ba(r,t,n)}function ba(e,t,r){let i=Na(e.stdout,e.stderr);return new n(`COMMAND_FAILED`,i?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,d(e,{package:t,cmd:`adb`,args:r,hint:i?la:`adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information.`}))}async function xa(e,t,n){await Nt(e,[`shell`,`run-as`,t,`mkdir`,`-p`,`shared_prefs`]);for(let r of n)await Nt(e,[`shell`,`run-as`,t,`tee`,r.path],{stdin:r.xml.trimEnd()})}function Sa(e,t){let r=s(e);if(r.code===`TOOL_MISSING`)return r;let i=Na(typeof r.details?.stdout==`string`?r.details.stdout:``,typeof r.details?.stderr==`string`?r.details.stderr:``);return new n(`COMMAND_FAILED`,i?`Failed to access Android app sandbox for ${t}`:`Failed to write Android runtime hints for ${t}`,{...r.details??{},package:t,cmd:`adb`,phase:`write-runtime-hints`,hint:i?la:`adb run-as succeeded, but writing React Native dev-server preferences failed. Inspect stderr/details for the failing shell command.`},r)}async function Ca(e,t,n){await mn(gn(e,[`spawn`,e.id,`defaults`,`write`,t,sa,`-string`,`${n.host}:${n.port}`])),await mn(gn(e,[`spawn`,e.id,`defaults`,`write`,t,ca,`-string`,n.scheme]))}async function wa(e,t){await mn(gn(e,[`spawn`,e.id,`defaults`,`delete`,t,sa]),{allowFailure:!0}),await mn(gn(e,[`spawn`,e.id,`defaults`,`delete`,t,ca]),{allowFailure:!0})}function Ta(e){let t=e.trim();return!t.includes(`<map`)||!t.includes(`</map>`)?ua:`${t}\n`}function Ea(e,t,n){let r=` <string name="${Ma(t)}">${Ma(n)}</string>`;return Oa(ka(e,t),r)}function Da(e,t,n){let r=` <boolean name="${Ma(t)}" value="${n?`true`:`false`}" />`;return Oa(ka(e,t),r)}function Oa(e,t){return Ta(e).replace(`</map>`,`${t}\n</map>`)}function ka(e,t){let n=ja(t);return Ta(e).replace(RegExp(`^\\s*<string name="${n}">[\\s\\S]*?<\\/string>\\n?`,`m`),``).replace(RegExp(`^\\s*<boolean name="${n}" value="(?:true|false)"\\s*\\/?>\\n?`,`m`),``)}function Aa(e){if(Dt(e)!==`binary`)return;let t=Ot(e);throw new n(`INVALID_ARGS`,t,{package:e,hint:t})}function ja(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ma(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`).replaceAll(`'`,`&apos;`)}function Na(e,t){let n=`${e}\n${t}`.toLowerCase();return[`run-as: package not debuggable`,`run-as: permission denied`,`run-as: package is unknown`,`run-as: unknown package`,`is unknown`,`is not an application`,`could not set capabilities`].some(e=>n.includes(e))}const Pa=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function Fa(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Ia(e,t){if(e!==void 0){if(typeof e!=`string`)throw new n(`INVALID_ARGS`,`Invalid open runtime ${t}: expected string.`);return _t(e)}}function La(e){if(e!==void 0){if(!Number.isInteger(e)||e<1||e>65535)throw new n(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function Ra(e){if(e!==void 0){if(typeof e!=`number`)throw new n(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return La(e)}}function za(e,t,r){if(e===void 0)return r;if(e!==`ios`&&e!==`android`)throw new n(`INVALID_ARGS`,`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new n(`INVALID_ARGS`,`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}function Ba(e){if(e===`ios`||e===`android`)return e}function Va(e,t){return{platform:t,metroHost:_t(e?.metroHost),metroPort:La(e?.metroPort),bundleUrl:_t(e?.bundleUrl),launchUrl:_t(e?.launchUrl)}}function Ha(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Ua(e){if($i(e))return`10.0.2.2`;if(U(e))return`127.0.0.1`}function Wa(e,t){if(!e||_t(e.metroHost)||_t(e.bundleUrl)||e.metroPort===void 0)return e;let n=Ua(t);return n?{...e,metroHost:n}:e}function Ga(e){let{runtime:t,sessionName:r,platform:i}=e;if(t===void 0)return;if(!t||typeof t!=`object`||Array.isArray(t))throw new n(`INVALID_ARGS`,`open runtime must be an object.`);let a=t,o=Object.keys(a).find(e=>!Pa.includes(e));if(o)throw new n(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Pa.join(`, `)}.`);return{platform:za(a.platform,r,i),metroHost:Ia(a.metroHost,`metroHost`),metroPort:Ra(a.metroPort),bundleUrl:Ia(a.bundleUrl,`bundleUrl`),launchUrl:Ia(a.launchUrl,`launchUrl`)}}function Ka(e,t,n){if(n){if(Fa(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function qa(e,t,r,i){let a=e.getRuntimeHints(t);if(!a)return;let o=r?j(r):void 0,s=Ba(o)??i;if(a.platform&&r&&!s)throw new n(`INVALID_ARGS`,`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new n(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Ja(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?Ba(j(i)):e.platform,o=n.getRuntimeHints(r),s=Ga({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=qa(n,r,i,a);return{runtime:i?Wa(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&Fa(s)>0?s:void 0;return{runtime:i?Wa(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Ya(e){return Ja(e).runtime}function Xa(e){try{return{ok:!0,data:Ja(e)}}catch(e){let t=s(e);return R(t.code,t.message,t.details)}}async function Za(e){let{replacedStoredRuntime:t,previousRuntime:n,runtime:r,session:i}=e;!t||!i?.appBundleId||!da(n)||da(r)||await pa({device:i.device,appId:i.appBundleId})}async function Qa(e){let{req:t,sessionName:n,sessionStore:r}=e,i=(t.positionals?.[0]??`show`).toLowerCase();if(i===`port-reverse`)return await io(t);if(!$a(i))return R(`INVALID_ARGS`,`runtime requires set, show, clear, or port-reverse`);let a=r.get(n),o=r.getRuntimeHints(n);return i===`clear`?await eo(n,r,a,o):i===`show`?to(n,o):ro({req:t,sessionName:n,sessionStore:r,session:a,current:o})}function $a(e){return e===`set`||e===`show`||e===`clear`}async function eo(e,t,n,r){return da(r)&&n?.appBundleId&&await pa({device:n.device,appId:n.appBundleId}),{ok:!0,data:{session:e,cleared:t.clearRuntimeHints(e)}}}function to(e,t){return{ok:!0,data:{session:e,configured:!!t,runtime:t}}}function no(e){return e?j(e.device):void 0}function ro(e){let{req:t,sessionName:n,sessionStore:r,session:i,current:a}=e,o=no(i),s=Ba(t.flags?.platform??a?.platform??o);if(!s)return R(`INVALID_ARGS`,`runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.`);if(o!==void 0&&o!==s)return R(`INVALID_ARGS`,`runtime set targets ${s}, but session "${n}" is already bound to ${o}.`);let c=Ha(a,Va(t.flags,s));return Fa(c)===0?R(`INVALID_ARGS`,`runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url.`):(r.setRuntimeHints(n,c),{ok:!0,data:{session:n,configured:!0,runtime:c}})}async function io(e){let t=ao(e);if(!t.ok)return t.response;let n=await cn(t.options);return n?{ok:!0,data:{action:`port-reverse`,...n}}:R(`UNSUPPORTED_OPERATION`,`No active provider device runtime supports port reverse for this lease.`)}function ao(e){let t=oo(e);if(!t.ok)return t;let n=so(e);if(!n.ok)return n;let r=e.flags?.portReverseName?.trim()||`runtime`;return{ok:!0,options:{leaseId:t.leaseId,provider:t.provider,devicePort:n.devicePort,hostPort:n.hostPort,name:r}}}function oo(e){let t=e.flags?.leaseId,n=e.flags?.leaseProvider;return t?n?{ok:!0,leaseId:t,provider:n}:{ok:!1,response:R(`INVALID_ARGS`,`runtime port-reverse requires a lease provider.`)}:{ok:!1,response:R(`INVALID_ARGS`,`runtime port-reverse requires a resolved remote lease.`)}}function so(e){let t=co(e.flags?.devicePort),n=co(e.flags?.hostPort??e.flags?.devicePort);return!t||!n?{ok:!1,response:R(`INVALID_ARGS`,`runtime port-reverse requires numeric devicePort and hostPort values from 1 to 65535.`)}:{ok:!0,devicePort:t,hostPort:n}}function co(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<1||e>65535))return e}const lo=`open-command-roundtrip`,uo=`Not implemented for this platform in this release.`;function fo(e){let{sessionName:t,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a,appName:o,appBundleId:s,surface:c,startup:l,timing:u,device:d,runtime:f,runtimeHintCount:p,sessionReused:m}=e,h={session:t,surface:c,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a,sessionReused:m};return o&&(h.appName=o),s&&(h.appBundleId=s),l&&(h.startup=l),u&&(h.timing=u),f&&p(f)>0&&(h.runtime=f),d&&(h.platform=j(d),h.target=d.target??`mobile`,h.device=d.name,h.id=d.id,h.kind=d.kind,Je(d.platform)&&(h.serial=d.id)),d&&N(d)&&(h.device_udid=d.id,h.ios_simulator_device_set=d.simulatorSetPath??null),{...h,...D(`Opened: ${o??s??t}`)}}function po(e){let{existingSession:t,sessionName:n,sessionScope:r,device:i,surface:a,appBundleId:o,appName:s,saveScript:c}=e;return t?{...t,device:i,surface:a,appBundleId:o,appName:s,recordSession:t.recordSession||c,snapshot:void 0}:{name:n,sessionScope:r,device:i,createdAt:Date.now(),surface:a,appBundleId:o,appName:s,recordSession:c,actions:[]}}const mo=new Set([`app`,`desktop`,`frontmost-app`]);function ho(e,t,r){if(e.platform===`linux`){if(!t)return`app`;let e=ne(t);if(!mo.has(e))throw new n(`INVALID_ARGS`,`Linux supports --surface app, desktop, and frontmost-app (got "${t}")`);if(e!==`app`&&r)throw new n(`INVALID_ARGS`,`open --surface ${e} does not accept an app target`);return e}if(!A(e)){if(t)throw new n(`INVALID_ARGS`,`surface is only supported on macOS and Linux`);return`app`}let i=t?ne(t):`app`;if(i!==`app`&&i!==`menubar`&&r)throw new n(`INVALID_ARGS`,`open --surface ${i} does not accept an app target`);return i}function go(e){let{device:t,surfaceFlag:n,openTarget:r,existingSurface:i}=e;return(A(t)||t.platform===`linux`)&&!n?i??`app`:ho(t,n,r)}async function _o(e){if(e===`app`||e===`desktop`||e===`menubar`)return{};let t=await hn();return{appBundleId:t.bundleId,appName:t.appName}}async function vo(e,t,n){if(!(!M(e.platform)||!t))return At(t)?A(e)?void 0:e.kind===`device`?Mt(n,t):jt(t)?void 0:n??await yo(e,t):await bo(e,t)}async function yo(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:n}=await import(`./apps.js`).then(e=>e.t);return await n(e,t)}catch{return}}async function bo(e,t){try{let{resolveIosApp:n}=await import(`./apps.js`).then(e=>e.t);return await n(e,t)}catch{return}}async function xo(e,t){if(!(e.platform!==`android`||!t||At(t)))try{let{resolveAndroidApp:n}=await import(`./app-lifecycle.js`).then(e=>e.t),r=await n(e,t);return r.type===`package`?r.value:void 0}catch{return}}async function So(e,t,n){if(n||e.platform!==`android`||!t||!At(t))return n;try{let{getAndroidAppState:t}=await import(`./app-lifecycle.js`).then(e=>e.t);return(await t(e)).package?.trim()||n}catch{return n}}function Co(e,t){return e.platform===`android`&&!!(t&&At(t))}async function wo(e,t,n,r){return N(e)&&F(e)?n:await vo(e,t,n)??await r(e,t)??(Co(e,t)?n:void 0)}function To(e){return R(`INVALID_ARGS`,e)}function Eo(e,t,r,i){try{return go({device:e,surfaceFlag:t,openTarget:r,existingSurface:i})}catch(e){return R(e instanceof n?e.code:`INVALID_ARGS`,String(e.message))}}function Do(e){let{shouldRelaunch:t,openTarget:n,surface:r,device:i}=e;return t?n&&At(n)?To(`open --relaunch does not support URL targets.`):r===`app`?i.platform===`android`&&n&&Dt(n)===`binary`?To(Ot(n)):null:To(`open --relaunch is supported only for app surfaces.`):null}function Oo(e){let{shouldRelaunch:t,openTarget:n,platform:r}=e;return t?n&&At(n)?To(`open --relaunch does not support URL targets.`):r===`android`&&n&&Dt(n)===`binary`?To(Ot(n)):null:null}async function ko(e){let{req:t,sessionName:n,sessionStore:r,device:i,surface:a,openTarget:o,existingSession:s,onIosSimulatorColdBootStart:c}=e;await Or(i,{deviceHub:t.flags?.deviceHub===!0,onIosSimulatorColdBootStart:c});let{appBundleId:l,appName:u}=await Ao({device:i,surface:a,openTarget:o,existingAppBundleId:s?.appBundleId}),d=Xa({req:t,sessionStore:r,sessionName:n,device:i});if(!d.ok)return{type:`response`,response:d};if(s){let{runtime:e,previousRuntime:t,replacedStoredRuntime:n}=d.data;await Za({replacedStoredRuntime:n,previousRuntime:t,runtime:e,session:s})}return{type:`details`,details:{appBundleId:l,appName:u,runtime:d.data.runtime}}}async function Ao(e){let{device:t,surface:n,openTarget:r,existingAppBundleId:i}=e,a=await _o(n);return{appBundleId:a.appBundleId??await wo(t,r,i,xo),appName:a.appName??r}}const jo=new Map;function Mo(e){return e.internal?.resolvedSessionScope??Mn(e)}function No(e){let{session:t,existingSession:n,saveScriptRequested:r,responseData:i}=e;if(!n&&r){t.scriptRecordingState=`armed`,t.recordSession=!0;return}n?.scriptRecordingState===`armed`&&(t.scriptRecordingState=`aborted`,t.recordSession=!1,i.warnings=[...Array.isArray(i.warnings)?i.warnings.filter(e=>typeof e==`string`):[],`Script publication was aborted because this session completed a second open. Start a fresh session with open --save-script to author another script.`])}async function Po(e){let{device:t,closeTarget:n,outFlag:r,context:i}=e;M(t.platform)&&!U(t)&&await yn(t.id),await an(t,`close`,[n],r,i),await ta(t,300)}async function Fo(e){let{runtime:t,device:n,req:r,logPath:i,appBundleId:a,traceLogPath:o,openPositionals:s}=e,c=t?.launchUrl;if(!c||s.length===0||s.length>1)return;let l=s[0]?.trim();!l||At(l)||await an(n,`open`,[c],r.flags?.out,{...Io(i,r.flags,a,o)})}function Io(e,t,n,r){let i=z(e,t,n,r);return delete i.launchConsole,delete i.launchArgs,i}function Lo(e,t){if(e.platform!==`android`)return!1;let n=t.flags?.testIme;return n===void 0?e.kind===`emulator`:n}async function Ro(e,t,n){if(Lo(e,t))try{await An(e,{stateDir:n})}catch(t){u({level:`warn`,phase:`android_test_ime_activate_failed`,data:{device:e.id,error:t instanceof Error?t.message:String(t)}})}}function zo(e,t,n){return{durationMs:Math.max(0,Date.now()-e),measuredAt:new Date().toISOString(),method:lo,appTarget:t,appBundleId:n}}function Bo(e){return!(!e.shouldRelaunch||!e.openTarget||e.collapseSimulatorRelaunch||!e.existingSession&&F(e.device))}async function Vo(e){let{req:t,sessionName:n,sessionStore:r,logPath:i,device:a,openTarget:o,openPositionals:s,appName:c,surface:d,appBundleId:f,runtime:p,existingSession:m,deviceClaim:h}=e,g=t.flags?.relaunch===!0,_=m?.trace?.outPath,v=f,y=Date.now(),b={},x=N(a)&&!F(a)&&d===`app`&&s.length>0&&!!v,S=Sr({req:t,logPath:i,appBundleId:v,traceLogPath:_}),C=t.flags?.maestro?.prewarmRunnerBeforeOpen===!0,w,T=!1,ee=!1,E=(e=S)=>{T=!0,b.runnerPrewarmKind=`session`,b.runnerPrewarmScheduled=!0,w=vn(a,e)},te=async()=>{if(!w||ee)return;ee=!0;let e=Date.now();await w,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)};x&&U(a)&&!C&&E();let ne=g&&!!o&&s.length===1&&U(a)&&!F(a)&&t.flags?.clearAppState!==!0;if(Bo({shouldRelaunch:g,openTarget:o,collapseSimulatorRelaunch:ne,device:a,existingSession:m})&&o){m&&Yr(m);let e=v??o,n=Date.now();await Po({device:a,closeTarget:e,outFlag:t.flags?.out,context:{...z(i,t.flags,v??m?.appBundleId,_)}}),b.relaunchCloseDurationMs=Math.max(0,Date.now()-n)}let re=Date.now();await fa({device:a,appId:v,runtime:p}),b.runtimeHintsDurationMs=Math.max(0,Date.now()-re),x&&C&&(E({...S,propagateError:!0}),await te());let ie=ee,D=Date.now(),ae=await Ho({req:t,sessionName:n,sessionStore:r,device:a,surface:d,sessionAppBundleId:v,appName:c,existingSession:m});if(ae.type===`response`)return ae.response;let oe=ae.session??m;oe&&Yr(oe),await an(a,`open`,s,t.flags?.out,{...z(i,t.flags,v),...ne?{terminateRunningApp:!0}:{}}),b.openDispatchDurationMs=Math.max(0,Date.now()-D),await Ro(a,t,r.resolveDaemonStateDir());let se=Date.now();await Fo({runtime:p,device:a,req:t,logPath:i,appBundleId:v,traceLogPath:_,openPositionals:s}),b.launchUrlDurationMs=Math.max(0,Date.now()-se),x&&!T&&E(),g?await te():w&&!ee&&(b.runnerPrewarmWaited=!1),!F(a)&&U(a)&&(g||ie)&&await Cn(a,S),v=await So(a,o,v),a.platform===`android`&&v&&await ir(a,v);let ce=o?zo(D,o,v):void 0,le=Date.now();if(await ta(a,300),b.postOpenSettleDurationMs=Math.max(0,Date.now()-le),Kt(t.meta?.requestId)){let e=Wt();return R(e.code,e.message,e.details)}m&&fr(m,`open`,m.snapshot);let ue=po({existingSession:oe,sessionName:m?.name??li(t),sessionScope:m?.sessionScope??Mo(t),device:a,surface:d,appBundleId:v,appName:c,saveScript:!!t.flags?.saveScript});ue.lease=_r({req:t,existingLease:m?.lease}),h&&(ue.deviceClaim=h),t.runtime!==void 0&&Ka(r,n,p);let O=r.ensureSessionDir(n),de=Te(O,t.meta?.requestId??l().requestId);b.totalDurationMs=Math.max(0,Date.now()-y),u({level:`info`,phase:`open_timing`,durationMs:b.totalDurationMs,data:b});let fe=fo({sessionName:ue.name,sessionStateDir:O,runnerLogPath:Fe(O),requestLogPath:de,eventLogPath:r.resolveEventLogPath(n),appName:c,appBundleId:v,surface:d,startup:ce,timing:b,device:a,runtime:p,runtimeHintCount:Fa,sessionReused:m!==void 0});return No({session:ue,existingSession:m,saveScriptRequested:!!t.flags?.saveScript,responseData:fe}),r.set(n,ue),r.recordAction(ue,{command:`open`,positionals:s,flags:t.flags??{},runtime:t.runtime===void 0?void 0:p,result:fe}),{ok:!0,data:fe}}async function Ho(e){let{req:t,sessionName:n,sessionStore:r,device:i,surface:a,sessionAppBundleId:o,appName:s,existingSession:c}=e,l=t.internal?.openLifecycle?.beforeDispatch;if(!l)return{type:`session`,session:c};let u=po({existingSession:c,sessionName:c?.name??li(t),sessionScope:c?.sessionScope??Mo(t),device:i,surface:a,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});u.lease=_r({req:t,existingLease:c?.lease}),r.set(n,u);let d=await l(u);return d&&!d.ok?{type:`response`,response:d}:{type:`session`,session:r.get(n)??u}}function Uo(e){let{req:t,device:n,sessionStore:r}=e,i=r.toArray().find(e=>e.device.id===n.id);if(i)return er(t,i)?R(`DEVICE_IN_USE`,`Device is already in use by another workspace session.`,{deviceId:n.id,deviceName:n.name,hint:`Use a different device selector, wait for the other workspace to close its session, or run agent-device devices to choose another target.`}):Wo(i,n)}function Wo(e,t){return R(`DEVICE_IN_USE`,`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:t.id,deviceName:t.name,hint:Jn(e,`device-in-use`)})}async function Go(e){let{req:t,device:n,sessionName:r,logPath:i}=e;return nr(t.meta,F(n))?await jn({device:n,session:r,workspace:t.meta?.cwd??process.cwd(),stateDir:H.dirname(i)}):{}}async function Ko(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,device:a,surface:o,openTarget:s}=e,c=Uo({req:t,device:a,sessionStore:i});if(c)return c;let l=await Go({req:t,device:a,sessionName:n,logPath:r}),u={mayHaveStarted:!1};try{let e=await ko({req:t,sessionName:n,sessionStore:i,device:a,surface:o,openTarget:s,onIosSimulatorColdBootStart:Er({req:t,logPath:r,device:a,surface:o,openTarget:s})});if(e.type===`response`)return await qo(l.ownership,u),e.response;u.mayHaveStarted=!0;let c=await Vo({req:t,sessionName:n,sessionStore:i,logPath:r,device:a,openTarget:s,openPositionals:t.positionals??[],appBundleId:e.details.appBundleId,appName:e.details.appName,runtime:e.details.runtime,surface:o,deviceClaim:l.ownership});return c.ok||await qo(l.ownership,u),c}catch(e){throw await qo(l.ownership,u),e}}async function qo(e,t){if(e){if(t.mayHaveStarted){u({level:`warn`,phase:`device_claim_open_effects_unconfirmed`,data:{deviceKey:e.deviceKey}});return}await ci(e)}}async function Jo(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=i.get(n);if(a){if(t.flags?.saveScript)return R(`INVALID_ARGS`,`open --save-script can only arm a fresh session. Use the current session without --save-script, or close it and start a fresh session.`);let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?a.appName:void 0),c=Eo(a.device,t.flags?.surface,s,a.surface);if(typeof c!=`string`)return c;if(!s&&c===`app`)return To(e?`open --relaunch requires an app name or an active session app.`:`Session already active. Close it first or pass a new --session name.`);let l=Do({shouldRelaunch:e,openTarget:s,surface:c,device:a.device});if(l)return l;let u=await na(a.device),d=await ko({req:t,sessionName:n,sessionStore:i,device:u,surface:c,openTarget:s,existingSession:a,onIosSimulatorColdBootStart:Er({req:t,logPath:r,device:u,surface:c,openTarget:s,traceLogPath:a.trace?.outPath})});return d.type===`response`?d.response:await Vo({req:t,sessionName:n,sessionStore:i,logPath:r,device:u,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:d.details.appBundleId,appName:d.details.appName,runtime:d.details.runtime,surface:c,existingSession:a})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return To(`open --relaunch requires an app argument.`);let c=Oo({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform===`android`?`android`:void 0});if(c)return c;let l=await I(t.flags??{},fi(s)),u=Eo(l,t.flags?.surface,s);return typeof u==`string`?Do({shouldRelaunch:o,openTarget:s,surface:u,device:l})||await Bt(jo,l.id,async()=>await Ko({req:t,sessionName:n,logPath:r,sessionStore:i,device:l,surface:u,openTarget:s})):u}function Yo(e){return U(e)||$i(e)}async function Xo(t){if(t.booted===!1)return{success:!0,exitCode:0,stdout:``,stderr:``};try{return U(t)?await Zo(t):await $o(t)}catch(t){let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}async function Zo(e){let t=await bi(e);return t.success?t:await Qo(e)===`Shutdown`?{...t,success:!0,exitCode:0}:t}async function Qo(e){try{return await xi(e)}catch{return null}}async function $o(e){let t=await Nt(e,[`emu`,`kill`],{allowFailure:!0,timeoutMs:15e3});return{success:t.exitCode===0,exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr}}async function es(e){let{device:t,shutdownRequested:n}=e;if(n&&!F(t)&&Yo(t))return await Xo(t)}function ts(e,t){return!!(e.flags?.force||t.saveScriptForce)}function ns(e,t){return U(t.device)&&!e.flags?.shutdown&&!t.recording&&!t.lease&&!t.device.simulatorSetPath}function rs(e){return M(e.device.platform)&&!U(e.device)}function is(e,t,n){if(t.saveScriptBoundary===void 0)return{kind:`not-armed`};let r=t.actions.length;Ar(e,t,n,`close`,{session:t.name,...D(`Closed: ${t.name}`)});let i=e.writeSessionLog(t,{force:ts(n,t)});return i.written?{kind:`committed`,path:i.path}:i.error?(t.actions.length=r,{kind:`failed`,error:i.error}):t.saveScriptComplete?{kind:`committed`}:{kind:`aborted`}}function as(t,n){let r=e(n);return{ok:!1,error:{...r,details:{...r.details,session:t.name,...t.saveScriptPath?{savedScript:t.saveScriptPath}:{}},retriable:!0}}}function os(e){return e instanceof n?e:new n(`COMMAND_FAILED`,`The platform close failed: ${e instanceof Error?e.message:String(e)}`,{hint:`The repair transaction was not committed because the platform close failed; fix the underlying issue and retry close --save-script.`})}async function ss(e){let{req:t,session:n,sessionName:r,logPath:i,sessionStore:a,cleanupFailures:o,repairArmed:s}=e,c=async(e,t)=>{try{await t()}catch(t){o.push({step:e,error:t})}},l=ns(t,n);await cs(n,a,c);let u=e.skipPlatformClose?void 0:await fs({req:t,session:n,logPath:i});return await ms(l,n,c),await ps(n,a,r),s||(u||Ar(a,n,t,`close`,{session:n.name,...D(`Closed: ${n.name}`)}),t.flags?.saveScript&&(n.recordSession=!0),a.writeSessionLog(n,{force:ts(t,n)})),await c(`materialized_paths`,()=>gr(r)),u}async function cs(e,t,n){await n(`recording`,()=>Ir(e)),await n(`app_log`,()=>Ur(e)),await n(`audio_probe`,async()=>{await ii(e,`session-close`)}),await n(`apple_perf`,()=>Zr(e)),await n(`android_native_perf`,()=>Mr(e)),await n(`android_snapshot_helper`,()=>mr(e)),await n(`android_ime`,()=>Vr(e,t.resolveDaemonStateDir()))}function ls(e){return JSON.stringify(e.positionals??[])}async function us(e){let{req:t,session:n,logPath:r,sessionStore:i}=e,a=n.saveScriptBoundary!==void 0,o=ls(t);if(a&&!(n.repairPlatformCloseSucceeded&&n.repairPlatformCloseIdentity===o)){let e=await fs({req:t,session:n,logPath:r});if(e)return{response:as(n,os(e))};n.repairPlatformCloseSucceeded=!0,n.repairPlatformCloseIdentity=o}let s=is(i,n,t);return s.kind===`failed`?{response:as(n,s.error)}:(n.repairPlatformCloseSucceeded=!1,n.repairPlatformCloseIdentity=void 0,{repairArmed:a,...s.kind===`committed`&&s.path?{healedScriptPath:s.path}:{},...s.kind===`aborted`?{aborted:!0}:{}})}async function ds(t){try{return{providerData:await mi(t)}}catch(n){let r=e(n);return{response:{ok:!1,error:{...r,hint:`The provider device could not be released. Retry close after the provider is reachable.`,details:{...r.details,session:t.session.name},retriable:!0}}}}}async function fs(e){let{req:t,session:n,logPath:r}=e;if(vs(t,n)){if(rs(n))try{await Jr(n)}catch(e){return e}try{Yr(n),await an(n.device,`close`,t.positionals??[],t.flags?.out,{...z(r,t.flags,n.appBundleId,n.trace?.outPath)}),await ta(n.device,300);return}catch(e){return e}}}async function ps(e,t,n){!da(t.getRuntimeHints(n))||!e.appBundleId||await pa({device:e.device,appId:e.appBundleId}).catch(()=>{})}async function ms(e,t,n){if(M(t.device.platform)){if(!e){await n(`apple_runner`,()=>Jr(t));return}u({level:`debug`,phase:`ios_runner_retained_after_close`,data:{session:t.name,deviceId:t.device.id}}),_n(t.device.id)}}function hs(e,t){if(e.flags?.saveScript&&!(t.scriptRecordingState!==`aborted`&&t.scriptRecordingState!==`published`))throw new n(`INVALID_ARGS`,`close --save-script cannot ${t.scriptRecordingState===`published`?`re-publish`:`publish`} this terminal recording. Retry with plain close; it will tear down the session without writing.`)}async function gs(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o}=e,s=i.get(n);if(!s)return await bs(t,r);if(hs(t,s),t.internal?.closeAppOnly===!0)return await _s({req:t,session:s,logPath:r});let c=await us({req:t,session:s,logPath:r,sessionStore:i});if(`response`in c)return c.response;let l=[],u=await ss({req:t,session:s,sessionName:n,logPath:r,sessionStore:i,cleanupFailures:l,repairArmed:c.repairArmed,skipPlatformClose:c.repairArmed}),d=await ds({session:s,leaseRegistry:a,leaseLifecycleProvider:o});if(d.response)return d.response;let f=$r({sessionName:n,phase:`session_close_cleanup_failed`,failures:l});if(!u&&!f&&await ci(s.deviceClaim),i.delete(n),u)throw u;if(f)throw f;let p=await es({device:s.device,shutdownRequested:t.flags?.shutdown}),m=c.healedScriptPath?{savedScript:c.healedScriptPath}:{},h=`Closed: ${s.name}`;return c.aborted&&t.flags?.saveScript?{ok:!1,error:{code:`COMMAND_FAILED`,message:`The repair was aborted and no script was written.`,hint:`Recovery: replay --from <n> --plan-digest <digest> before closing.`,details:{session:s.name}}}:p?{ok:!0,data:w({session:s.name,shutdown:p,...m,...d.providerData?{provider:d.providerData}:{}},h)}:{ok:!0,data:{session:s.name,...D(h),...m,...d.providerData?{provider:d.providerData}:{}}}}async function _s(e){let{req:t,session:n,logPath:r}=e,i=t.positionals?.[0];if(!i)return R(`INVALID_ARGS`,`App-only close requires an app target`);let a=await fs({req:t,session:n,logPath:r});if(a)throw a;return{ok:!0,data:{app:i,...D(`Closed: ${i}`)}}}function vs(e,t){return ys(e)||t.device.platform===`web`}function ys(e){return(e.positionals?.length??0)>0}async function bs(e,t){if(!e.positionals||e.positionals.length===0)return R(`SESSION_NOT_FOUND`,`No active session`);let n=await G({session:void 0,flags:e.flags,ensureReady:!0});return await an(n,`close`,e.positionals,e.flags?.out,{...z(t,e.flags)}),await ta(n,300),{ok:!0,data:{app:e.positionals[0],...D(`Closed: ${e.positionals[0]}`)}}}const xs={ios:async(e,t,n)=>{let r=await sn(e,t,n,{relaunch:!0,appIdentifierHint:t});if(r)return{bundleId:r.bundleId??r.launchTarget??t};let{reinstallIosApp:i}=await import(`./apps.js`).then(e=>e.t);return await i(e,t,n)},android:async(e,t,n)=>{let r=await sn(e,t,n,{relaunch:!0,packageNameHint:t});if(r)return{package:r.packageName??r.launchTarget??t};let{reinstallAndroidApp:i}=await import(`./app-lifecycle.js`).then(e=>e.t);return await i(e,t,n)}},Ss={ios:async(e,t,n)=>{let r=await sn(e,t,n,{appIdentifierHint:t});if(r)return{bundleId:r.bundleId,appName:r.appName,launchTarget:r.launchTarget};let{installIosApp:i}=await import(`./apps.js`).then(e=>e.t),a=await i(e,n,{appIdentifierHint:t});return{bundleId:a.bundleId,appName:a.appName,launchTarget:a.launchTarget}},android:async(e,t,n)=>{let r=await sn(e,t,n,{packageNameHint:t});if(r)return{package:r.packageName,appName:r.appName,launchTarget:r.launchTarget};let{installAndroidApp:i}=await import(`./app-lifecycle.js`).then(e=>e.t),a=await i(e,n);return{package:a.packageName,appName:a.appName,launchTarget:a.launchTarget}}};async function Cs(e){let{req:t,command:n,sessionName:r,sessionStore:i,deployOps:a}=e,o=i.get(r),s=t.flags??{},c=W(n,o,s);if(c)return c;let l=Ds(n,t.positionals??[]);if(!l.ok)return l.response;let{app:u,appPathInput:d}=l,f=t.meta?.uploadedArtifactId;try{let e=f?qn(f,t.meta?.tenantId):k.expandHome(d);if(!V.existsSync(e))return R(`INVALID_ARGS`,`App binary not found: ${e}`);let r=await G({session:o,flags:s,ensureReady:!1}),c=L(n,r);if(c)return c;o&&Yr(o);let l=N(r)?Ts(u,e,await a.ios(r,u,e)):Es(u,e,await a.android(r,u,e)),p=w(l,ws(l));return Ar(i,o,t,n,p),{ok:!0,data:p}}finally{f&&Pr(f)}}function ws(e){return`Installed: ${e.appName??xe(e)}`}function Ts(e,t,n){let r=n.bundleId;return{app:e||r||n.launchTarget||t,appPath:t,platform:`ios`,...r?{appId:r,bundleId:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function Es(e,t,n){let r=n.package;return{app:e||r||n.launchTarget||t,appPath:t,platform:`android`,...r?{appId:r,package:r,packageName:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function Ds(e,t){let n=t[0]?.trim(),r=t[1]?.trim();if(e===`install`){let e=r??n;return e?{ok:!0,app:r?n??``:``,appPathInput:e}:{ok:!1,response:R(`INVALID_ARGS`,`install requires: install <path-to-app-binary>`)}}return!n||!r?{ok:!1,response:R(`INVALID_ARGS`,`reinstall requires: reinstall <app> <path-to-app-binary>`)}:{ok:!0,app:n,appPathInput:r}}async function Os(e,t,n){return await S(e,t,n)}async function ks(e){let{req:t,sessionName:n,sessionStore:r}=e;if(t.command===`session_list`){let e=Mn(t);return{ok:!0,data:{sessions:r.toArray().filter(t=>rr(t,e)).map(e=>{let t=r.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:Fe(t),platform:j(e.device),...M(e.device.platform)&&e.device.appleOs?{appleOs:e.device.appleOs}:{},target:e.device.target??`mobile`,surface:e.surface??`app`,device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,...M(e.device.platform)&&!A(e.device)&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if(t.command===`devices`)try{let e=Pt(t.flags?.androidDeviceAllowlist),n=t.flags?.platform,r=qe({simulatorSetPath:Ft(t.flags?.iosSimulatorDeviceSet),platform:n,target:t.flags?.target}),i=await tn({platform:n,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:r,androidSerialAllowlist:e?Array.from(e).sort():void 0}),a=n?i.filter(e=>js(e,n)):i;return{ok:!0,data:{devices:(t.flags?.target?a.filter(e=>(e.target??`mobile`)===t.flags?.target):a).map(As)}}}catch(e){let t=s(e);return R(t.code,t.message,t.details)}if(t.command===`capabilities`){let e=r.get(n),i=t.flags??{},a=W(t.command,e,i);if(a)return a;let o=await G({session:e,flags:i,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0});return{ok:!0,data:{device:As(o),availableCommands:en().filter(e=>on(e,o))}}}if(t.command===`apps`){let e=r.get(n),i=t.flags??{},a=W(t.command,e,i);if(a)return a;let o=await G({session:e,flags:i,ensureReady:!0}),s=L(`apps`,o);if(s)return s;let c=Tt(t.flags?.appsFilter);return M(o.platform)?{ok:!0,data:{apps:(await Si(o,c)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await kt(o,c)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}function As({simulatorSetPath:e,iosPhysicalDeviceBackend:t,appleOs:n,...r}){return{...r,platform:j({platform:r.platform,appleOs:n}),...M(r.platform)&&n?{appleOs:n}:{}}}function js(e,t){return Xe(e,t)}async function Ms(e){let{ensureAndroidEmulatorBooted:t}=await import(`./logcat.js`).then(e=>e.c);return await t(e)}const Ns=`iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).`,Ps=`macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").`;async function Fs(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),a=t.flags??{},o=a.platform;if(!i&&ea(a))return R(`SESSION_NOT_FOUND`,o===`ios`?`No active session "${n}". Run open with --session ${n} first.`:`No active session "${n}". Run open with --session ${n} first, or omit --session to query by device selector.`);let s=W(`appstate`,i,a);if(s)return s;let c=M(i?.device.platform)&&ia(a,i),l=o===`ios`,u=o===`macos`;if(l&&!c)return R(`SESSION_NOT_FOUND`,Ns);if(u&&!c)return R(`SESSION_NOT_FOUND`,Ps);if(c&&i){let e=i.appName??i.appBundleId;return!i.appName&&!i.appBundleId?A(i.device)&&i.surface&&i.surface!==`app`&&i.surface!==`frontmost-app`?{ok:!0,data:{platform:j(i.device),appName:i.surface,appBundleId:i.appBundleId,source:`session`,surface:i.surface}}:R(`COMMAND_FAILED`,`No foreground app is tracked for this ${A(i.device)?`macOS`:`iOS`} session. Open an app in the session, then retry appstate.`):{ok:!0,data:{platform:j(i.device),appName:e??`unknown`,appBundleId:i.appBundleId,source:`session`,surface:i.surface??`app`,...N(i.device)?{device_udid:i.device.id,ios_simulator_device_set:i.device.simulatorSetPath??null}:{}}}}let d=await G({session:i,flags:a,ensureReady:!0});if(N(d))return R(`SESSION_NOT_FOUND`,Ns);if(A(d))return R(`SESSION_NOT_FOUND`,Ps);if(d.platform===`web`)return R(`UNSUPPORTED_OPERATION`,`appstate is not supported on web.`);let{getAndroidAppState:f}=await import(`./app-lifecycle.js`).then(e=>e.t),p=await f(d);return{ok:!0,data:{platform:`android`,package:p.package,activity:p.activity}}}async function Is(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e;if(t.command===`boot`){let e=i.get(n),a=t.flags??{},o=W(t.command,e,a);if(o)return o;let c=(a.platform??e?.device.platform)===`android`,l=a.headless===!0;if(l&&!c)return R(`INVALID_ARGS`,`boot --headless is supported only for Android emulators.`);let u=ra({flags:a,sessionDevice:e?.device}),d=c&&!!u,f,p=!1;try{f=await G({session:e,flags:a,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0})}catch(e){let t=s(e);if(c&&l&&!u&&t.code===`DEVICE_NOT_FOUND`)return R(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`);if(!d||t.code!==`DEVICE_NOT_FOUND`||!u)throw e;f=await Ms({avdName:u,serial:a.serial,headless:l}),p=!0}if(a.target&&(f.target??`mobile`)!==a.target)return R(`DEVICE_NOT_FOUND`,`No ${f.platform} device found matching --target ${a.target}.`);if(c&&l){if(f.platform!==`android`||f.kind!==`emulator`)return R(`INVALID_ARGS`,`boot --headless is supported only for Android emulators.`);if(!p){let t=ra({flags:a,sessionDevice:e?.device,resolvedDevice:f});if(!t)return R(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`);f=await Ms({avdName:t,serial:a.serial,headless:!0})}await Or(f)}else f.platform===`android`&&f.kind===`emulator`&&f.booted!==!0?(f=await Ms({avdName:f.name,serial:a.serial,headless:!1}),await Or(f)):(f.platform!==`android`||f.booted!==!0)&&await Or(f,{onIosSimulatorColdBootStart:Kr({req:t,logPath:r,device:f,enabled:!0})});return L(`boot`,f)||(N(f)&&f.kind===`simulator`&&xn(f,{}),{ok:!0,data:{platform:j(f),target:f.target??`mobile`,device:f.name,id:f.id,kind:f.kind,booted:!0,...M(f.platform)&&f.appleOs?{appleOs:f.appleOs}:{}}})}if(t.command===`shutdown`){let e=i.get(n),r=t.flags??{},a=W(t.command,e,r);if(a)return a;let o=await G({ensureReady:!1,flags:r,session:e}),s=L(`shutdown`,o,{message:`shutdown is supported only for Apple simulators and Android emulators.`});if(s)return s;if(e&&e.device.platform===o.platform&&e.device.id===o.id)return R(`DEVICE_IN_USE`,`Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.`,{hint:`Run agent-device close --shutdown --session ${n}`,session:n,platform:j(o),target:o.target??`mobile`,device:o.name,id:o.id,kind:o.kind});let c=await Xo(o);return c.success?{ok:!0,data:{platform:j(o),target:o.target??`mobile`,device:o.name,id:o.id,kind:o.kind,shutdown:c,...M(o.platform)&&o.appleOs?{appleOs:o.appleOs}:{}}}:R(c.error?.code??`COMMAND_FAILED`,Ls(c),{platform:j(o),target:o.target??`mobile`,device:o.name,id:o.id,kind:o.kind,shutdown:c})}return t.command===`appstate`?await Fs({req:t,sessionName:n,sessionStore:i}):null}function Ls(e){let t=e.error?.message??e.stderr.trim();return t.length>0?t:`Shutdown failed`}pn();function Rs(e){let t=[];for(let n of e){if(n.command!==`open`)continue;let e=n.result?.startup;if(!e||typeof e!=`object`)continue;let r=e;typeof r.durationMs!=`number`||!Number.isFinite(r.durationMs)||typeof r.measuredAt!=`string`||r.measuredAt.trim().length===0||r.method!==`open-command-roundtrip`||t.push({durationMs:Math.max(0,Math.round(r.durationMs)),measuredAt:r.measuredAt,method:lo,appTarget:typeof r.appTarget==`string`&&r.appTarget.length>0?r.appTarget:void 0,appBundleId:typeof r.appBundleId==`string`&&r.appBundleId.length>0?r.appBundleId:void 0})}return t.slice(-20)}async function zs(e,t={}){let n=Us(e);if(!Zs(e))return n;if(!e.appBundleId)return Js(n,e),n;let r=Bs(e.device);return r&&Ys(n,e,await r(e,e.appBundleId,t)),n}function Bs(e){let t=ln(e.platform)?.perf?.metricsSamplerTag(e);return t?ac[t]:void 0}async function Vs(e,t={}){let n=Ks(e);return Zs(e)?e.appBundleId?(await Xs(n,e,e.appBundleId,t),n):(n.metrics.fps={available:!1,reason:Qs(e)},n):n}async function Hs(e,t){let n=qs(e);return Zs(e)?t.action===`sample`?(n.metrics={memory:await oc(e,t)},n):(n.artifact=await cc(e,t),n.support=mc(n.artifact.support)??pc(e),n):t.action===`snapshot`?(n.artifact=dc(e,lc(e,t.kind)),n.support=mc(n.artifact.support)??pc(e),n):(n.metrics={memory:{available:!1,reason:uo}},n)}function Us(e){let t=Rs(e.actions),n=t.at(-1),r=n?{available:!0,lastDurationMs:n.durationMs,lastMeasuredAt:n.measuredAt,method:lo,sampleCount:t.length,samples:t}:{available:!1,reason:`No startup sample captured yet. Run open <app|url> in this session first.`,method:lo};return{session:e.name,platform:j(e.device),device:e.device.name,deviceId:e.device.id,metrics:{startup:r,...Ws()},sampling:{startup:{method:lo,description:`Elapsed wall-clock time around dispatching the open command for the active session app target.`,unit:`ms`},...$s(e)}}}function Ws(){return{fps:Gs(),memory:{available:!1,reason:uo},cpu:{available:!1,reason:uo}}}function Gs(){return{available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`}}function Ks(e){return{session:e.name,platform:j(e.device),device:e.device.name,deviceId:e.device.id,metrics:{fps:Gs()},sampling:{fps:nc(e)}}}function qs(e){return{session:e.name,platform:j(e.device),device:e.device.name,deviceId:e.device.id,sampling:{memory:ec(e),snapshot:tc(e)}}}function Js(e,t){let n=Qs(t);e.metrics.fps={available:!1,reason:n},e.metrics.memory={available:!1,reason:n},e.metrics.cpu={available:!1,reason:n}}function Ys(e,t,n){e.metrics.memory=gc(n.memory),e.metrics.cpu=gc(n.cpu),e.metrics.fps=_c(gc(n.fps),t)}async function Xs(e,t,n,r){let i=t.device.platform===`android`?await hc(or(t.device,n,{adb:r.androidAdb})):await hc(Hr(t.device,n));e.metrics.fps=_c(gc(i),t)}function Zs(e){return ln(e.device.platform)?.perf?.supportsMetrics(e.device)??!1}function Qs(e){return e.device.platform===`android`?`No Android app package is associated with this session. Run open <app> first.`:`No Apple app bundle ID is associated with this session. Run open <app> first.`}function $s(e){return e.device.platform===`android`?{memory:{method:Yn,description:Kn,unit:`kB`},cpu:{method:On,description:Fr,unit:`percent`},fps:{method:Hn,description:Rn,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}}:Tr(e.device)}function ec(e){return e.device.platform===`android`?{method:Yn,description:Kn,unit:`kB`,topConsumerLimit:5}:Tr(e.device).memory}function tc(e){return e.device.platform===`android`?{method:Wn,description:Nr,defaultKind:`android-hprof`,artifactOnly:!0}:{method:lr,description:sr,defaultKind:`memgraph`,artifactOnly:!0}}function nc(e){return e.device.platform===`android`?{method:Hn,description:Rn,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}:Xn(e.device)}async function rc(e,t,n){let r={adb:n.androidAdb},[i,a,o]=await Promise.allSettled([Un(e.device,t,r),Bn(e.device,t,r),or(e.device,t,r)]);return{memory:i,cpu:a,fps:o}}async function ic(e,t){let n=await hc(Hr(e.device,t)),r=await hc(Xr(e.device,t));if(r.status===`fulfilled`){let e=r.value;return{memory:{status:`fulfilled`,value:e.memory},cpu:{status:`fulfilled`,value:e.cpu},fps:n}}return{memory:{status:`rejected`,reason:r.reason},cpu:{status:`rejected`,reason:r.reason},fps:n}}const ac={android:rc,apple:ic};async function oc(e,t){return e.appBundleId?gc(e.device.platform===`android`?await hc(Un(e.device,e.appBundleId,{adb:t.androidAdb})):await hc(sc(e))):{available:!1,reason:Qs(e)}}async function sc(e){if(!e.appBundleId)throw new n(`INVALID_ARGS`,Qs(e));return(await Xr(e.device,e.appBundleId)).memory}async function cc(e,t){if(!e.appBundleId)throw new n(`INVALID_ARGS`,Qs(e),{hint:`Run open <app> first so perf memory snapshot can resolve the app process.`});let r=lc(e,t.kind),i=uc(t,r);return e.device.platform===`android`?r===`android-hprof`?await Ln(e.device,e.appBundleId,i,{adb:t.androidAdb}):dc(e,r):r===`memgraph`?await ei(e.device,e.appBundleId,i):dc(e,r)}function lc(e,t){return t||(e.device.platform===`android`?`android-hprof`:`memgraph`)}function uc(e,t){if(e.out)return k.expandHome(e.out,e.cwd);let n=t===`android-hprof`?`hprof`:t===`memgraph`?`memgraph`:`artifact`,r=new Date().toISOString().replace(/[:.]/g,`-`),i=e.sessionStore.ensureSessionDir(e.sessionName);return H.join(i,`artifacts`,`memory-${t}-${r}.${n}`)}function dc(e,t){let n=pc(e),r=fc(e,t);return{available:!1,kind:t,reason:r.reason,hint:r.hint,support:n}}function fc(e,t){return e.device.platform===`android`?{reason:`Android perf memory snapshot supports android-hprof, not ${t}.`,hint:`Use perf memory snapshot --kind android-hprof for Android Java heap artifacts.`}:M(e.device.platform)?{reason:`Apple perf memory snapshot supports memgraph, not ${t}.`,hint:`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`}:{reason:`Memory snapshot artifacts are not supported on ${e.device.platform}.`,hint:`Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS.`}}function pc(e){return e.device.platform===`android`?{platform:e.device.platform,defaultKind:`android-hprof`,androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:`Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice.`}:M(e.device.platform)?{...En(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:`Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice.`}:{platform:e.device.platform,defaultKind:`memgraph`,androidHprof:!1,memgraph:!1,heapprofd:!1,reason:`Memory snapshot artifacts are available only on Android, iOS simulator, and macOS.`,hint:`Use perf memory sample where supported, or switch to a platform with memory artifact support.`,heapprofdDecision:`Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice.`}}function mc(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function hc(e){try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}function gc(t){if(t.status===`fulfilled`)return{available:!0,...t.value};let n=e(t.reason);return{available:!1,reason:n.message,error:n}}function _c(e,t){if(e.available!==!0)return e;let n=vc(t.actions,e);return n.length===0?e:{...e,relatedActions:n}}function vc(e,t){let n=yc(t.windowStartedAt),r=yc(t.windowEndedAt)??yc(t.measuredAt);return n===void 0||r===void 0?[]:e.filter(e=>e.ts>=n&&e.ts<=r).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:bc(e)})).slice(-12)}function yc(e){if(typeof e!=`string`)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function bc(e){let t=e.result;if(t)for(let e of[`refLabel`,`ref`,`appName`,`appBundleId`]){let n=t[e];if(typeof n==`string`&&n.length>0)return n}}async function xc(t){let n=Sc(t.req,t.area);if(!n.ok)return n;let{session:r}=t;if(r.device.platform!==`android`)return R(`UNSUPPORTED_OPERATION`,`Android native perf collectors are supported only on Android sessions.`);if(!r.appBundleId)return R(`COMMAND_FAILED`,`No Android app package is associated with this session.`,{hint:`Run open <app> first so perf can resolve the package and process identity.`});try{return{ok:!0,data:n.area===`cpu`?await jc(t,r,r.appBundleId,n):await Mc(t,r,r.appBundleId,n)}}catch(t){return{ok:!1,error:e(t)}}}function Sc(e,t){let n=Ac(e,t);return t===`cpu`?Cc(e,n):wc(e,n)}function Cc(e,t){let n=Tc(e,1),r=Tc(e,2),i=Tc(e,3);return ce(n)?Ec(r)?i===`simpleperf`?{ok:!0,area:`cpu`,subject:n,action:r,kind:i,outPath:t}:R(`INVALID_ARGS`,`perf cpu profile requires --kind simpleperf`):R(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`):R(`INVALID_ARGS`,ae)}function wc(e,t){let n=Tc(e,1),r=Tc(e,2);return Dc(n)?te(r)?r===`perfetto`?{ok:!0,area:`trace`,action:n,kind:r,outPath:t}:R(`INVALID_ARGS`,`perf trace requires --kind perfetto`):R(`INVALID_ARGS`,E):R(`INVALID_ARGS`,`perf trace action must be start or stop`)}function Tc(e,t){return(e.positionals?.[t]??``).toLowerCase()}function Ec(e){return e===`start`||e===`stop`||e===`report`}function Dc(e){return e===`start`||e===`stop`}function Oc(e,t){return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),Lc(t)}function kc(e,t,n){return t?k.expandHome(t,e.req.meta?.cwd):Ic(e.sessionStore,e.sessionName,n)}function Ac(e,t){return typeof e.flags?.out==`string`&&e.flags.out.length>0?e.flags.out:(e.positionals??[])[t===`cpu`?5:4]||void 0}async function jc(e,t,n,r){if(r.action===`start`){Pc(t);let i=kc(e,r.outPath,`cpu.perf.data`);return Oc(e,await Zn(t.device,n,i,{adb:e.androidAdbExecutor}))}let i=Rc(t,`cpu-profile`,r.kind);if(r.action===`report`){await Nc(i);let n=kc(e,r.outPath,`cpu-report.json`);return await kn(t.device,i,n,{adb:e.androidAdbExecutor})}let a=Fc(e,r.outPath,i);return Oc(e,await gi(t.device,i,a,{adb:e.androidAdbExecutor}))}async function Mc(e,t,n,r){if(r.action===`start`){Pc(t);let i=kc(e,r.outPath,`app.perfetto-trace`);return Oc(e,await ar(t.device,n,i,{adb:e.androidAdbExecutor}))}let i=Rc(t,`trace`,r.kind),a=Fc(e,r.outPath,i);return Oc(e,await zn(t.device,i,a,{adb:e.androidAdbExecutor}))}function Nc(e){if(e.state===`running`)throw new n(`COMMAND_FAILED`,`Stop the Android Simpleperf CPU profile before generating a report.`,{hint:`Run perf cpu profile stop --kind simpleperf, then retry perf cpu profile report --kind simpleperf.`})}function Pc(e){let t=e.nativePerf?.android;if(t?.state===`running`)throw new n(`COMMAND_FAILED`,`Android ${t.kind} ${t.type} is already running for this session.`,{hint:t.type===`cpu-profile`?`Run perf cpu profile stop --kind simpleperf before starting another Android native perf capture.`:`Run perf trace stop --kind perfetto before starting another Android native perf capture.`})}function Fc(e,t,n){return t?kc(e,t,n.outPath):n.outPath}function Ic(e,t,n){let r=new Date().toISOString().replace(/[:.]/g,`-`);return H.join(e.ensureSessionDir(t),`${r}-${n}`)}function Lc(e){return{action:e.action,platform:`android`,type:e.type,kind:e.kind,packageName:e.packageName,appPid:e.appPid,profilerPid:e.profilerPid,state:e.state,startedAt:new Date(e.startedAt).toISOString(),stoppedAt:typeof e.stoppedAt==`number`?new Date(e.stoppedAt).toISOString():void 0,durationMs:e.durationMs,outPath:e.outPath,sizeBytes:e.sizeBytes,remotePath:e.remotePath,method:e.method,summary:e.summary,message:e.message}}function Rc(e,t,r){let i=e.nativePerf?.android;if(i?.type===t&&i.kind===r)return i;throw new n(`COMMAND_FAILED`,`No Android ${r} ${t} is active for this session.`,{hint:t===`cpu-profile`?`Run perf cpu profile start --kind simpleperf first, then stop or report in the same session.`:`Run perf trace start --kind perfetto first, then stop in the same session.`})}async function zc(e){if(!un(e))return;let{macOsScreenCaptureKitAudioProbeBackend:t}=await import(`./audio-probe.js`);return t}const Bc=[`probe`],Vc=[`start`,`status`,`stop`],Hc=`audio probe requires ${Vc.join(`, `)}`;async function Uc(t){let n=Wc(t);if(!n.ok)return n;let r=await zc(n.session.device);if(r)return await Kc(t,n,r);let i=zr();if(!i.probeAudio)return R(`UNSUPPORTED_OPERATION`,`audio is not supported by this web provider`);try{return{ok:!0,data:await i.probeAudio({action:n.probeAction,durationMs:n.durationMs,bucketMs:n.bucketMs})}}catch(t){return{ok:!1,error:e(t)}}}function Wc(e){let t=Gc(e);if(!t.ok)return t;let n=qc(e.req);if(!n.ok)return n;let r=Jc(e.req,n.probeAction);return r.ok?{ok:!0,session:t.session,probeAction:n.probeAction,...r.timing}:r}function Gc(e){let t=e.sessionStore.get(e.sessionName);return t?on(`audio`,t.device)?{ok:!0,session:t}:R(`UNSUPPORTED_OPERATION`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`):R(`SESSION_NOT_FOUND`,`audio requires an active session`)}async function Kc(t,n,r){try{return{ok:!0,data:await dr({session:n.session,sessionName:t.sessionName,sessionStore:t.sessionStore,backend:r,probeAction:n.probeAction,durationMs:n.durationMs,bucketMs:n.bucketMs})}}catch(t){return{ok:!1,error:e(t)}}}function qc(e){if(!Yc(e.positionals?.[0]))return R(`INVALID_ARGS`,`audio requires probe`);let t=Xc(e.positionals?.[1]);return t?{ok:!0,probeAction:t}:R(`INVALID_ARGS`,Hc)}function Jc(e,t){if(t!==`start`&&e.positionals&&e.positionals.length>2)return R(`INVALID_ARGS`,`audio probe duration and bucket are only supported with audio probe start`);let n=Zc(e.positionals?.[2],{defaultValue:1e4,min:100,max:12e4,message:`audio probe duration must be an integer in range 100..120000 ms`});if(n instanceof Error)return R(`INVALID_ARGS`,n.message);let r=Zc(e.positionals?.[3],{defaultValue:1e3,min:100,max:1e4,message:`audio probe bucket must be an integer in range 100..10000 ms`});return r instanceof Error?R(`INVALID_ARGS`,r.message):{ok:!0,timing:{durationMs:n,bucketMs:r}}}function Yc(e){let t=(e??`probe`).toLowerCase();return Bc.includes(t)?`probe`:void 0}function Xc(e){let t=(e??`status`).toLowerCase();return Vc.includes(t)?t:void 0}function Zc(e,t){if(e===void 0)return t.defaultValue;let n=Number.parseInt(e,10);return!Number.isInteger(n)||String(n)!==e||n<t.min||n>t.max?Error(t.message):n}async function Qc(t,n){let r=$c(t.req);if(!r.ok)return r;if(n.device.platform===`android`)return R(`UNSUPPORTED_OPERATION`,`Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.`);if(!M(n.device.platform))return R(`UNSUPPORTED_OPERATION`,`Apple xctrace perf is not supported on ${n.device.platform}.`);if(!n.appBundleId)return R(`INVALID_ARGS`,`Apple xctrace perf requires an active app session. Run open <app> first.`);try{return r.action===`start`?await il(t,n,r):r.action===`stop`?await al(t,n,r):await ul(t,n,r)}catch(t){return{ok:!1,error:e(t)}}}function $c(e){let t=e.positionals??[],n=t[0]?.toLowerCase();return n===`cpu`?el(t):n===`trace`?tl(t):R(`INVALID_ARGS`,ie)}function el(e){if(e[1]?.toLowerCase()!==`profile`)return R(`INVALID_ARGS`,`perf cpu requires profile`);let t=nl(e[2],`perf cpu profile`,!0);if(!t.ok)return t;let n=rl(e[3]);return n.ok?{ok:!0,area:`cpu`,mode:`cpu-profile`,action:t.value,kind:`xctrace`,template:e[4]||void 0,outPath:e[5]||void 0,tracePath:e[6]||void 0}:n}function tl(e){let t=nl(e[1],`perf trace`,!1);if(!t.ok)return t;let n=rl(e[2]);return n.ok?{ok:!0,area:`trace`,mode:`trace`,action:t.value,kind:`xctrace`,template:e[3]||void 0,outPath:e[4]||void 0,tracePath:e[5]||void 0}:n}function nl(e,t,n){let r=e?.toLowerCase();return r===`start`||r===`stop`||n&&r===`report`?{ok:!0,value:r}:R(`INVALID_ARGS`,n?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function rl(e){return e?.toLowerCase()===`xctrace`?{ok:!0}:R(`INVALID_ARGS`,`perf native collection currently supports --kind xctrace`)}async function il(e,t,n){if(t.applePerf?.active)return R(`INVALID_ARGS`,`Apple xctrace perf capture already in progress`);let r=n.template??ml(n.mode),i=pl(e,n),a=await qr({device:t.device,appBundleId:t.appBundleId,mode:n.mode,template:r,outPath:i});t.applePerf={...t.applePerf??{},active:a},e.sessionStore.set(e.sessionName,t);let o=hl(`started`,a);return fl(e,t,o),{ok:!0,data:o}}async function al(e,t,n){let r=t.applePerf?.active;if(!r)return R(`INVALID_ARGS`,`no active Apple xctrace perf capture`);let i=n.outPath?k.expandHome(n.outPath,e.req.meta?.cwd):r.outPath,a;try{a=await Vn(r,i)}catch(n){throw sl(n)&&ol(e,t),n}cl(e,t,a);let o=hl(`stopped`,a);return fl(e,t,o),{ok:!0,data:o}}function ol(e,t){t.applePerf={...t.applePerf??{},active:void 0},e.sessionStore.set(e.sessionName,t)}function sl(e){return s(e).details?.captureCleanedUp===!0}function cl(e,t,n){t.applePerf={...t.applePerf??{},active:void 0,lastMode:n.mode,...ll(n)},e.sessionStore.set(e.sessionName,t)}function ll(e){return e.mode===`cpu-profile`?{lastProfileTracePath:e.outPath,lastProfileTemplate:e.template}:{lastTracePath:e.outPath}}async function ul(e,t,n){if(n.mode!==`cpu-profile`)return R(`INVALID_ARGS`,`perf trace does not support report`);if(t.applePerf?.active)return R(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace; stop the active capture first.`);let r=pl(e,n),i=dl(t,n);if(!i.ok)return i;let a={perf:`reported`,...await cr({tracePath:k.expandHome(i.value,e.req.meta?.cwd),outPath:r,mode:n.mode,template:t.applePerf?.lastProfileTemplate??n.template,appBundleId:t.appBundleId})};return fl(e,t,a),{ok:!0,data:a}}function dl(e,t){let n=t.tracePath??e.applePerf?.lastProfileTracePath??e.applePerf?.active?.outPath;return n?{ok:!0,value:n}:R(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace or tracePath option`)}function fl(e,t,n){Ar(e.sessionStore,t,e.req,`perf`,n)}function pl(e,t){if(t.outPath)return k.expandHome(t.outPath,e.req.meta?.cwd);let n=e.sessionStore.ensureSessionDir(e.sessionName),r=new Date().toISOString().replace(/[:.]/g,`-`),i=t.action===`report`?`json`:`trace`;return`${n}/perf-${t.mode}-${r}.${i}`}function ml(e){return e===`cpu-profile`?`Time Profiler`:`Animation Hitches`}function hl(e,t){return{perf:e,kind:t.kind,mode:t.mode,template:t.template,outPath:t.outPath,appBundleId:t.appBundleId,deviceId:t.deviceId,platform:t.platform,targetPids:t.targetPids,targetProcesses:t.targetProcesses,startedAt:t.startedAt,endedAt:t.endedAt}}const gl=`logs requires ${me.slice(0,-1).join(`, `)}, or ${me.at(-1)}`,_l=[`dump`,`log`],vl=`network requires ${_l.join(` or `)}`,yl=`network include mode must be one of: ${o.join(`, `)}`,bl={path:({session:e,sessionName:t,sessionStore:n})=>Kl(e,t,n),doctor:({session:e,sessionName:t,sessionStore:n})=>ql(e,t,n),mark:({req:e,sessionName:t,sessionStore:n})=>Jl(e,t,n),clear:({session:e,sessionName:t,sessionStore:n,restart:r})=>Yl(e,t,n,r),start:({session:e,sessionName:t,sessionStore:n})=>Xl(e,t,n),stop:({session:e,sessionName:t,sessionStore:n})=>Zl(e,t,n)};function xl(e){if(e.appLog){let t=e.appLog.getState();return{active:t===`active`||t===`recovering`,state:t,backend:e.appLog.backend,startedAt:e.appLog.startedAt,notes:wl(t)}}return e.appLogFailure?{active:!1,state:`failed`,backend:e.appLogFailure.backend,failureCode:e.appLogFailure.code,failureMessage:e.appLogFailure.message,hint:e.appLogFailure.hint,notes:[Cl(e.appLogFailure)]}:{active:!1,state:`inactive`,backend:ri(e.device)}}function Sl(e,t){return{backend:t,code:e.code,message:e.message,hint:e.hint}}function Cl(e){return e.hint?`${e.message} ${e.hint}`:e.message}function wl(e){if(e===`failed`)return[`The app log stream process exited with an error. Run logs doctor for backend diagnostics.`];if(e===`ended`)return[`The app log stream process ended. Run logs clear --restart before the next capture window.`]}function Tl(e,t){return hr([...e,...t.notes??[]])}function El(e,t,n){return{...n,platform:e.device.platform,outPath:t}}function Dl(t,n,r,i){let a=e(i);return t.set(n,{...r,appLog:void 0,appLogFailure:Sl(a,ri(r.device))}),{ok:!1,error:a}}async function Ol(e){let{req:t}=e;return t.command===`perf`?Al(e):t.command===`logs`?Wl(e):t.command===`events`?await kl(e):t.command===`network`?Ql(e):t.command===`audio`?await Uc(e):null}async function kl(t){let{req:n,sessionName:r,sessionStore:i}=t;try{return await i.flushEvents(r),{ok:!0,data:i.readEvents(r,{limit:n.positionals?.[0],cursor:n.positionals?.[1]})}}catch(t){return{ok:!1,error:e(t)}}}async function Al(t){let{req:n,sessionName:r,sessionStore:i,androidAdbExecutor:a}=t,o=i.get(r);if(!o)return R(`SESSION_NOT_FOUND`,`perf requires an active session. Run open first.`);let s=(n.positionals?.[0]??`metrics`).toLowerCase();if(jl(s))return o.device.platform===`android`?await xc({req:n,sessionName:r,sessionStore:i,session:o,androidAdbExecutor:a,area:s}):await Qc(t,o);let c=Ml(n);if(!c.ok)return c;if(c.native)return await Qc(t,o);try{return{ok:!0,data:await Nl(t,o,c)}}catch(t){return{ok:!1,error:e(t)}}}function jl(e){return e===`cpu`||e===`trace`}function Ml(t){let r=Pl(t.positionals?.[0]);if(!r)return R(`INVALID_ARGS`,ie);if(r===`cpu`||r===`trace`)return{ok:!0,native:!0};let i=Fl(t.positionals?.[1]);if(!i)return R(`INVALID_ARGS`,ge);let a=Il(t.flags?.kind);return a instanceof n?{ok:!1,error:e(a)}:(Ll(r,i)??Bl(t,r,i,a))||{ok:!0,native:!1,area:r,action:i,kind:a,out:Ul(t.flags?.out)}}async function Nl(e,t,n){let{sessionName:r,sessionStore:i,androidAdbExecutor:a}=e;return n.area===`memory`?await Hs(t,{action:zl(n.action),kind:n.kind,out:n.out,cwd:e.req.meta?.cwd,sessionName:r,sessionStore:i,androidAdb:a}):n.area===`frames`?await Vs(t,{androidAdb:a}):await zs(t,{androidAdb:a})}function Pl(e){let t=(e??`metrics`).toString().toLowerCase();return se(t)?t:void 0}function Fl(e){let t=(e??`sample`).toString().toLowerCase();return T(t)?t:void 0}function Il(e){if(e!==void 0)return typeof e!=`string`||!te(e)?new n(`INVALID_ARGS`,E):e}function Ll(e,t){if(e===`memory`)return Rl(t)?void 0:R(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(t!==`sample`)return R(`INVALID_ARGS`,`perf metrics and perf frames only support sample`)}function Rl(e){return e===`sample`||e===`snapshot`}function zl(e){if(Rl(e))return e;throw new n(`INVALID_ARGS`,`perf memory requires sample or snapshot`)}function Bl(e,t,n,r){return Vl(e.flags?.out,t,n)??Hl(r,t,n)}function Vl(e,t,n){if(!(!e||t===`memory`&&n===`snapshot`))return R(`INVALID_ARGS`,`--out is only supported with perf memory snapshot`)}function Hl(e,t,n){if(e){if(t!==`memory`||n!==`snapshot`)return R(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(!oe(e))return R(`INVALID_ARGS`,re)}}function Ul(e){return typeof e==`string`&&e.length>0?e:void 0}async function Wl(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n);if(!i)return R(`SESSION_NOT_FOUND`,`logs requires an active session`);let a=L(`logs`,i.device);if(a)return a;let o=Gl(t);return o.ok?await bl[o.action]({...e,session:i,restart:o.restart}):o}function Gl(e){let t=(e.positionals?.[0]??`path`).toLowerCase(),n=!!e.flags?.restart;return me.includes(t)?n&&t!==`clear`?R(`INVALID_ARGS`,`logs --restart is only supported with logs clear`):{ok:!0,action:t,restart:n}:R(`INVALID_ARGS`,gl)}function Kl(e,t,n){let r=n.resolveAppLogPath(t),i=xr(r),a=xl(e);return{ok:!0,data:{path:r,active:a.active,state:a.state,backend:a.backend,sizeBytes:i.sizeBytes,modifiedAt:i.modifiedAt,startedAt:a.startedAt?new Date(a.startedAt).toISOString():void 0,failureCode:a.failureCode,failureMessage:a.failureMessage,hint:a.hint??`Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>`,notes:a.notes}}}async function ql(e,t,n){let r=n.resolveAppLogPath(t),i=await Br(e.device,e.appBundleId),a=xl(e);return{ok:!0,data:{path:r,active:a.active,state:a.state,backend:a.backend,checks:i.checks,failureCode:a.failureCode,failureMessage:a.failureMessage,hint:a.hint,notes:Tl(i.notes,a)}}}function Jl(e,t,n){let r=e.positionals?.slice(1).join(` `)??``,i=n.resolveAppLogPath(t);return Gr(i,r),{ok:!0,data:{path:i,marked:!0}}}async function Yl(e,t,n,r){if(e.appLog&&!r)return R(`INVALID_ARGS`,`logs clear requires logs to be stopped first; run logs stop`);let i=n.resolveAppLogPath(t);if(!r){let r=Qr(i);return n.set(t,{...e,appLogFailure:void 0}),{ok:!0,data:r}}let a=e.appBundleId;if(!a)return R(`INVALID_ARGS`,`logs clear --restart requires an app session; run open <app> first`);e.appLog&&await Dr(e.appLog);let o=Qr(i),s=n.resolveAppLogPidPath(t);try{let r=await wr(e.device,a,i,s);return n.set(t,{...e,appLog:El(e,i,r),appLogFailure:void 0}),{ok:!0,data:{...o,restarted:!0}}}catch(r){return Dl(n,t,e,r)}}async function Xl(e,t,n){if(e.appLog)return R(`INVALID_ARGS`,`app log already streaming; run logs stop first`);if(!e.appBundleId)return R(`INVALID_ARGS`,`logs start requires an app session; run open <app> first`);let r=n.resolveAppLogPath(t),i=n.resolveAppLogPidPath(t);try{let a=await wr(e.device,e.appBundleId,r,i);return n.set(t,{...e,appLog:El(e,r,a),appLogFailure:void 0}),{ok:!0,data:{path:r,started:!0}}}catch(r){return Dl(n,t,e,r)}}async function Zl(e,t,n){if(!e.appLog)return R(`INVALID_ARGS`,`no app log stream active`);let r=e.appLog.outPath;return await Dr(e.appLog),n.set(t,{...e,appLog:void 0,appLogFailure:void 0}),{ok:!0,data:{path:r,stopped:!0}}}async function Ql(e){let t=eu(e);if(!t.ok)return t;let{include:n,maxEntries:r,session:i}=t;if(i.device.platform===`web`)return await $l({include:n,maxEntries:r});let a=await Rr({device:i.device,appBundleId:i.appBundleId,appLogState:i.appLog?.getState(),appLogStartedAt:i.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:r,include:n,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...a.dump,active:!!i.appLog,state:i.appLog?.getState()??`inactive`,backend:a.backend,notes:a.notes}}}async function $l(t){let n=zr();if(!n.dumpNetwork)return R(`UNSUPPORTED_OPERATION`,`network is not supported by this web provider`);try{let e=await n.dumpNetwork({include:t.include,limit:t.maxEntries});return{ok:!0,data:{entries:e.entries,active:!0,state:`active`,backend:e.backend??`agent-browser`,include:t.include,matchedLines:e.entries.length,scannedLines:e.entries.length,limits:{maxEntries:t.maxEntries,maxPayloadChars:2048,maxScanLines:e.entries.length},notes:e.notes}}}catch(t){return{ok:!1,error:e(t)}}}function eu(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n);if(!i)return R(`SESSION_NOT_FOUND`,`network requires an active session`);let a=L(`network`,i.device);if(a)return a;let o=(t.positionals?.[0]??`dump`).toLowerCase();if(!_l.includes(o))return R(`INVALID_ARGS`,vl);let s=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(s)||s<1||s>200)return R(`INVALID_ARGS`,`network dump limit must be an integer in range 1..200`);let c=tu(t);return c.ok?{ok:!0,session:i,maxEntries:s,include:c.include}:c}function tu(e){let t=e.positionals?.[2]?.toLowerCase(),n=e.flags?.networkInclude;if(t&&n&&t!==n)return R(`INVALID_ARGS`,`network include mode was provided both positionally and via --include with different values`);let r=(n??t??`summary`).toLowerCase();return o.includes(r)?{ok:!0,include:r}:R(`INVALID_ARGS`,yl)}function nu(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=k.expandHome(t??`.agent-device/test-artifacts`,n);return H.join(i,r)}function ru(e,t){let n=t?H.relative(t,e):H.basename(e);return(n.length===0||n.startsWith(`..`)?H.basename(e):n).toLowerCase().replace(/[\\/]+/g,`__`).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)||`test`}function iu(e,t){V.mkdirSync(t,{recursive:!0}),cu(e,t)}function au(e){let{response:t,filePath:n,sessionName:r,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=[...ou(t)];!t.ok&&typeof t.error.logPath==`string`&&s.push(t.error.logPath);let c=su(s,o),l=[`file: ${n}`,`session: ${r}`,`attempt: ${i}/${a}`,`status: ${t.ok?`passed`:`failed`}`];if(t.ok){let e=typeof t.data?.replayed==`number`?t.data.replayed:0,n=typeof t.data?.healed==`number`?t.data.healed:0;l.push(`replayed: ${e}`,`healed: ${n}`)}else l.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&l.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&l.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&l.push(`logPath: ${t.error.logPath}`),t.error.details?.reason===`timeout`&&l.push(`timeoutMode: cooperative`);c.length>0&&l.push(`copiedArtifacts: ${c.map(e=>H.basename(e)).join(`, `)}`);let u=H.join(o,`result.txt`),d=`${l.join(`
3
- `)}\n`;V.writeFileSync(u,d),t.ok||V.writeFileSync(H.join(o,`failure.txt`),d)}function ou(e){let t=e.ok?e.data?.artifactPaths:e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>typeof e==`string`))]:[]}function su(e,t){let n=[],r=new Map;for(let i of e){if(!du(i))continue;let e=uu(H.basename(i),r),a=H.join(t,e);H.resolve(i)!==H.resolve(a)&&V.copyFileSync(i,a),n.push(a)}return n}function cu(e,t){let n=H.join(t,`replay.ad`);if(V.copyFileSync(e,n),!lu(e))return;let r=H.join(t,H.basename(e));H.resolve(r)!==H.resolve(n)&&V.copyFileSync(e,r)}function lu(e){let t=H.extname(e).toLowerCase();return t===`.yml`||t===`.yaml`}function uu(e,t){let n=H.extname(e),r=n?e.slice(0,-n.length):e,i=t.get(e)??0;return t.set(e,i+1),i===0?e:`${r}-${i+1}${n}`}function du(e){try{return V.statSync(e).isFile()}catch{return!1}}const fu=/[*?[\]{}]/;function pu(e){let{inputs:t,cwd:r,platformFilter:i,replayBackend:a}=e,o=Cu(a),s=yu(t,r??process.cwd(),o,a),c=[];for(let e of s){let t=V.readFileSync(e,`utf8`),n=Rt(t),r=Au(t,e,a);if(!i){c.push({kind:`run`,path:e,title:r,metadata:n});continue}if(!n.platform){ku(a)?c.push({kind:`run`,path:e,title:r,metadata:n}):c.push({kind:`skip`,path:e,reason:`skipped-by-filter`,message:`missing platform metadata for --platform ${i}`});continue}Mu(i,n.platform)&&c.push({kind:`run`,path:e,title:r,metadata:n})}if(c.filter(e=>e.kind===`run`).length===0)throw new n(`INVALID_ARGS`,`No replay tests matched${i?` for --platform ${i}`:``}.`);return c}function mu(e,t,n,r,i=0){let a=H.basename(n,H.extname(n)).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return`${e}:test:${t}:${r+1}${a?`-${a}`:``}:attempt-${i+1}`}function hu(e){return(e?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`suite`}function gu(e){let{requestId:t,suiteInvocationId:n,filePath:r,caseIndex:i,attemptIndex:a,shardIndex:o}=e,s=o===void 0?``:`:shard:${o+1}`;return Xt(`${t??n}${s}:test:${i+1}:${H.basename(r)}:attempt:${a+1}`,n)}function _u(e,t){return typeof e==`number`?e:t}function vu(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function yu(e,t,n,r){if(!ku(r))return[...new Set(e.flatMap(e=>Su(e,t,n).paths))].map(e=>H.normalize(e)).sort((e,t)=>e.localeCompare(t));let i=[],a=[];for(let r of e){let e=bu(r,t,n);e.source===`file`?i.push(...e.paths):a.push(e.source===`directory`?Ou(e.paths):Tu(e.paths))}return Ou([...i,...a.flat()])}function bu(e,t,n){let r=k.expandHome(e,t);return V.existsSync(r)&&V.statSync(r).isDirectory()?{paths:xu(r,n),source:`directory`}:Su(e,t,n)}function xu(e,t){let n=[],r=V.opendirSync(e);try{let i;for(;(i=r.readSync())!==null;){let r=H.join(e,i.name);i.isDirectory()?n.push(...xu(r,t)):i.isFile()&&t.has(H.extname(i.name))&&n.push(r)}}finally{r.closeSync()}return n}function Su(e,t,r){let i=k.expandHome(e,t);if(V.existsSync(i)){let t=V.statSync(i);if(t.isDirectory())return{paths:wu(r).flatMap(e=>V.globSync(e,{cwd:i}).map(e=>H.join(i,e))),source:`directory`};if(t.isFile()){if(!r.has(H.extname(i)))throw new n(`INVALID_ARGS`,`test does not support this file type: ${e}`);return{paths:[i],source:`file`}}return{paths:[],source:`file`}}if(!ju(e)&&!ju(i))throw new n(`INVALID_ARGS`,`test input not found: ${e}`);let a=H.isAbsolute(i)?i:e;return{paths:V.globSync(a,{cwd:H.isAbsolute(i)?void 0:t}).map(e=>H.isAbsolute(e)?e:H.resolve(t,e)).filter(e=>r.has(H.extname(e))&&Nu(e)),source:`glob`}}function Cu(e){return ku(e)?new Set([`.yaml`,`.yml`,`.ad`]):new Set([`.ad`])}function wu(e){return[...e].map(e=>`**/*${e}`)}function Tu(e){return e.map(e=>H.normalize(e)).sort(Eu)}function Eu(e,t){let n=Du(e),r=Du(t);return n===r?e.localeCompare(t):n-r}function Du(e){return+(H.extname(e)===`.ad`)}function Ou(e){return[...new Set(e.map(e=>H.normalize(e)))]}function ku(e){return e===`maestro`}function Au(e,t,n){return ku(n)&&H.extname(t)!==`.ad`?pr(e,{sourcePath:t}).config.name:void 0}function ju(e){return fu.test(e)}function Mu(e,t){return e===`apple`?M(t):t===e}function Nu(e){try{return V.statSync(e).isFile()}catch{return!1}}const Pu=[`failed to start daemon`,`runner did not accept connection`,`xcodebuild exited early`,`device is offline`,`device offline`,`device unauthorized`];function Fu(e){let t=Iu(e);return t?Lu(t.details)||Ru(t.code,t.message):!1}function Iu(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function Lu(e){let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`?!0:t?It(t):!1}function Ru(e,t){let n=`${e}\n${t}`.toLowerCase();return Pu.some(e=>n.includes(e))}const zu=2e3;async function Bu(t){let{filePath:n,sessionName:r,requestId:i,parentRequestId:a,timeoutMs:o,platform:s,target:c,artifactsDir:l,shard:d,progress:f,runReplay:p,cleanupSession:m,finalizeAttempt:h}=t;Gt(i);let g=Vu(i,a),_=new Set,v,y=!1,b,x=Date.now(),S=qu({artifactsDir:l,artifactPaths:_,filePath:n,sessionName:r,requestId:i,timeoutMs:o,platform:s,target:c}),C=Ut(f,async()=>await p({filePath:n,sessionName:r,platform:s,target:c,requestId:i,artifactsDir:l,artifactPaths:_,tracePath:S,shard:d})).catch(t=>({ok:!1,error:e(t)})).finally(()=>{g(),qt(i)});try{b=typeof o==`number`?await Promise.race([C,new Promise(e=>{v=setTimeout(()=>{y=!0,Ht(i),e(Ju(o,[..._]))},o)})]):await C,K(S,{type:`replay_test_attempt_stop`,ts:new Date().toISOString(),session:r,ok:b.ok,timedOut:y,durationMs:Date.now()-x,errorCode:b.ok?void 0:b.error.code})}finally{v&&clearTimeout(v),y&&(await Hu(C)||(Gu(b),u({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:r,requestId:i,graceMs:zu}}),Uu({replayPromise:C,cleanupSession:m,sessionName:r,requestId:i})));let t=await Wu({finalizeAttempt:h,sessionName:r,artifactPaths:_,artifactsDir:l,tracePath:S});b?.ok&&t&&!t.ok&&Ku(b,`Replay test finalization failed: ${t.error.message}`);let n=Date.now();try{K(S,{type:`replay_test_cleanup_start`,ts:new Date().toISOString(),session:r}),await m(r),K(S,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!0,durationMs:Date.now()-n})}catch(t){let i=e(t);K(S,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-n,errorCode:i.code}),u({level:`warn`,phase:`test_cleanup_failed`,data:{session:r,error:i.message}})}}return b??{ok:!1,error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}}}function Vu(e,t){if(!t||t===e)return()=>{};let n=Vt(t);if(!n)return()=>{};let r=()=>{Ht(e)};return n.aborted?(r(),()=>{}):(n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r)})}async function Hu(e){return await Promise.race([e.then(()=>!0),Mi(zu).then(()=>!1)])}async function Uu(t){let{replayPromise:n,cleanupSession:r,sessionName:i,requestId:a}=t;try{await n}finally{try{await r(i)}catch(t){u({level:`warn`,phase:`test_late_cleanup_failed`,data:{session:i,requestId:a,error:e(t).message}})}}}async function Wu(t){let{finalizeAttempt:n,sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o}=t;if(!n)return;let s=Date.now();K(o,{type:`replay_test_finalize_start`,ts:new Date().toISOString(),session:r});try{let e=await n({sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o});return K(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:e?.ok??!0,durationMs:Date.now()-s,errorCode:e?.ok===!1?e.error.code:void 0}),e}catch(t){let n=e(t);return K(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-s,errorCode:n.code}),u({level:`warn`,phase:`test_finalize_failed`,data:{session:r,error:n.message}}),{ok:!1,error:n}}}function Gu(e){!e||e.ok||(e.error.details={...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0})}function Ku(e,t){let n=e.data??={};n.warnings=[...Array.isArray(n.warnings)?n.warnings.filter(e=>typeof e==`string`):[],t]}function qu(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=H.join(t,`replay-timing.ndjson`);return V.mkdirSync(H.dirname(l),{recursive:!0}),V.writeFileSync(l,``),n.add(l),K(l,{type:`replay_test_attempt_start`,ts:new Date().toISOString(),replayPath:r,session:i,requestId:a,timeoutMs:o,platform:s,target:c}),l}function K(e,t){e&&V.appendFileSync(e,`${JSON.stringify(t)}\n`)}function Ju(e,t=[]){return{ok:!1,error:{code:`COMMAND_FAILED`,message:`TIMEOUT after ${e}ms`,hint:`Replay test timeouts are cooperative; the active command may take a short grace period to stop.`,details:{reason:`timeout`,timeoutMs:e,timeoutMode:`cooperative`,artifactPaths:t}}}}async function Yu(e){let t=Xu(e);return rd(e,t,await Zu(e,t))}function Xu(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:H.join(i,...a?[`shard-${a.shardIndex+1}`]:[],ru(t.path,n)),maxAttempts:r+1}}async function Zu(e,t){$u(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!Kt(e.requestId);r+=1){let i=await Qu(e,t,r);if(ed(n,i),td(e,i.response,r))break;nd(e,t,i)}return n}async function Qu(e,t,n){let{entry:r,sessionName:i,suiteInvocationId:a,caseIndex:o,suiteIndex:s,suiteTotal:c,requestId:l,timeoutMs:u,shard:d}=e,f=n+1,p=Date.now(),m=mu(i,a,r.path,o,n),h=H.join(t.testArtifactsDir,`attempt-${f}`);iu(r.path,h);let g=gu({requestId:l,suiteInvocationId:a,filePath:r.path,caseIndex:o,attemptIndex:n,shardIndex:d?.shardIndex}),_=await Bu({filePath:r.path,sessionName:m,requestId:g,parentRequestId:l,timeoutMs:u,platform:r.metadata.platform,target:r.metadata.target,artifactsDir:h,shard:d,progress:{file:r.path,title:r.title,index:s,total:c,attempt:f,maxAttempts:t.maxAttempts,session:m,artifactsDir:t.testArtifactsDir,...fd(d)},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),v=Date.now()-p;return au({response:_,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{response:_,sessionName:m,attempt:f,durationMs:v}}function $u(e,t){let{entry:n,sessionName:r,suiteInvocationId:i,caseIndex:a,suiteIndex:o,suiteTotal:s,shard:c}=e;P({type:`replay-test`,file:n.path,title:n.title,status:`start`,index:o,total:s,maxAttempts:t.maxAttempts,session:mu(r,i,n.path,a),artifactsDir:t.testArtifactsDir,...fd(c)})}function ed(e,t){e.finalResponse=t.response,e.finalSessionName=t.sessionName,e.attempts=t.attempt,e.finalAttemptDurationMs=t.durationMs,!t.response.ok&&e.attemptFailures.push({attempt:t.attempt,message:t.response.error.message,durationMs:t.durationMs})}function td(e,t,n){return t.ok||Kt(e.requestId)||Fu(t)||n>=e.retries}function nd(e,t,n){n.response.ok||P({type:`replay-test`,file:e.entry.path,title:e.entry.title,status:`fail`,index:e.suiteIndex,total:e.suiteTotal,attempt:n.attempt,maxAttempts:t.maxAttempts,durationMs:n.durationMs,retrying:!0,message:n.response.error.message,hint:n.response.error.hint,session:n.sessionName,artifactsDir:t.testArtifactsDir,...fd(e.shard)})}function rd(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalResponse?.ok?id(e,t,n,r):ad(e,t,n,r)}function id(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalResponse;if(!c?.ok)throw Error(`Expected passing replay test response.`);return P({type:`replay-test`,file:i.path,title:i.title,status:`pass`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,...fd(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`passed`,durationMs:r,finalAttemptDurationMs:n.finalAttemptDurationMs,attempts:n.attempts,artifactsDir:t.testArtifactsDir,...sd(c),...cd(c.data?.warnings),...ld(c.data?.snapshotDiagnostics),...dd(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function ad(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=od(n.finalResponse);return P({type:`replay-test`,file:i.path,title:i.title,status:`fail`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,message:c.message,hint:c.hint,...fd(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`failed`,durationMs:r,attempts:n.attempts,artifactsDir:t.testArtifactsDir,error:c,...ld(ud(n.finalResponse)),...dd(s)}}function od(e){return e&&!e.ok?e.error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}}function sd(e){return{replayed:typeof e.data?.replayed==`number`?e.data.replayed:0,healed:typeof e.data?.healed==`number`?e.data.healed:0}}function cd(e){if(!Array.isArray(e))return{};let t=e.filter(e=>typeof e==`string`);return t.length>0?{warnings:t}:{}}function ld(e){let t=Le(e);return t?{snapshotDiagnostics:t}:{}}function ud(e){return e?.ok?e.data?.snapshotDiagnostics:e?.error.details?.snapshotDiagnostics}function dd(e){return fd(e)}function fd(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function pd(e,t,n){let r=hd(e);if(!r||t.length===0)return;let i=await _d(e,r.count);return{mode:r.kind,shardCount:r.count,total:n+(r.kind===`all`?t.length*r.count:t.length),shards:i.map((e,n)=>({shardIndex:n,shardCount:r.count,device:e,entries:r.kind===`all`?t:t.filter((e,t)=>t%r.count===n)}))}}function md(e,t){if(!t)return e;let n={...e??{},device:void 0,udid:void 0,serial:void 0,platform:t.device.platform,target:t.device.target,shardAll:void 0,shardSplit:void 0,shardCount:t.shardCount,shardIndex:t.shardIndex};return t.device.platform===`android`?{...n,serial:t.device.id}:{...n,udid:t.device.id}}function hd(e){let t=gd(e?.shardAll,`--shard-all`),r=gd(e?.shardSplit,`--shard-split`);if(t!==void 0&&r!==void 0)throw new n(`INVALID_ARGS`,`--shard-all and --shard-split are mutually exclusive`);if(t!==void 0)return{kind:`all`,count:t};if(r!==void 0)return{kind:`split`,count:r}}function gd(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<1)throw new n(`INVALID_ARGS`,`${t} requires a positive integer`);return e}}async function _d(e,t){let r=xd(e),i=yd(await tn(vd(e)),r,e);if(i.length<t)throw new n(`DEVICE_NOT_FOUND`,`test sharding requires ${bd(t)}, but only ${i.length} matched`);return i.slice(0,t)}function vd(e){let t=Pt(e?.androidDeviceAllowlist);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:qe({simulatorSetPath:Ft(e?.iosSimulatorDeviceSet),platform:e?.platform,target:e?.target}),androidSerialAllowlist:t?Array.from(t).sort():void 0}}function yd(e,t,n){return t.length>0?Sd(e,t,n):e.filter(e=>Cd(e,n)).sort(Ed)}function bd(e){return`${e} device${e===1?``:`s`}`}function xd(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function Sd(e,t,r){return t.map(t=>{let i=Td(t),a=e.find(e=>wd(e,r)&&(e.id===t||Td(e.name)===i));if(!a)throw new n(`DEVICE_NOT_FOUND`,`No shard device matched ${t}`);return a})}function Cd(e,t){return!wd(e,t)||!Ye(e)?!1:e.booted!==!1}function wd(e,t){return!(!Xe(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function Td(e){return e.toLowerCase().replace(/_/g,` `).replace(/\s+/g,` `).trim()}function Ed(e,t){return e.id.localeCompare(t.id)}async function Dd(e){let{req:t,sessionName:n,runReplay:r,cleanupSession:i,finalizeAttempt:a}=e;if((t.positionals?.length??0)===0)return R(`INVALID_ARGS`,`test requires at least one path or glob`);try{let e=Date.now(),o=await Od(t);Md(o);let s=o.shardPlan?Nd({entries:o.entries,total:o.total}):[];return o.shardPlan?s.push(...await Pd({shards:o.shardPlan.shards,sessionName:n,suiteInvocationId:o.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:o.suiteArtifactsDir,suiteTotal:o.total,runReplay:r,cleanupSession:i,finalizeAttempt:a})):s.push(...await Rd({discoveryEntries:o.entries,sessionName:n,suiteInvocationId:o.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:o.suiteArtifactsDir,suiteTotal:o.total,runReplay:r,cleanupSession:i,finalizeAttempt:a})),{ok:!0,data:Vd(o.total,s,Date.now()-e)}}catch(e){let t=s(e);return R(t.code,t.message)}}async function Od(e){let t=kd(e),n=Ad(t),r=t.length-n.length,i=hu(e.meta?.requestId),a=await pd(e.flags,n,r);return{entries:t,runnable:n,shardPlan:a,suiteInvocationId:i,suiteArtifactsDir:jd(e,i),total:a?.total??t.length}}function kd(e){return pu({inputs:e.positionals??[],cwd:e.meta?.cwd,platformFilter:e.flags?.platform,replayBackend:e.flags?.replayBackend})}function Ad(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function jd(e,t){return nu({artifactsDir:typeof e.flags?.artifactsDir==`string`?e.flags.artifactsDir:void 0,cwd:e.meta?.cwd,suiteInvocationId:t})}function Md(e){P({type:`replay-test-suite`,status:`start`,total:e.total,runnable:e.runnable.length,skipped:e.entries.length-e.runnable.length,artifactsDir:e.suiteArtifactsDir,shardMode:e.shardPlan?.mode,shardCount:e.shardPlan?.shardCount})}function Nd(e){let{entries:t,total:n}=e,r=[];for(let[e,i]of t.entries())i.kind===`skip`&&(P({type:`replay-test`,file:i.path,status:`skip`,index:e+1,total:n,message:i.message}),r.push({file:i.path,status:`skipped`,durationMs:0,reason:i.reason,message:i.message}));return r}async function Pd(e){return(await Promise.allSettled(e.shards.map(async t=>await Id({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[Fd(r,e.sessionName,t.reason)]:[]})}function Fd(t,n,r){let i=e(r);return{file:t.entries[0]?.entry.path??`shard-${t.shardIndex+1}`,session:Ld(n,t),status:`failed`,durationMs:0,attempts:1,error:{code:i.code,message:i.message,hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,details:i.details},shardIndex:t.shardIndex,shardCount:t.shardCount,deviceId:t.device.id,deviceName:t.device.name}}async function Id(e){let{shard:t,sessionName:n}=e;return await zd({...e,entries:t.entries,sessionName:Ld(n,t),shard:t})}function Ld(e,t){return`${e}:shard-${t.shardIndex+1}`}async function Rd(e){let{discoveryEntries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,flags:o,suiteArtifactsDir:s,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d}=e,f=[],p=0;for(let[e,m]of t.entries()){if(Kt(a))break;if(m.kind===`skip`){P({type:`replay-test`,file:m.path,status:`skip`,index:e+1,total:c,message:m.message}),f.push({file:m.path,status:`skipped`,durationMs:0,reason:m.reason,message:m.message});continue}p+=1;let t=await Yu({entry:m,sessionName:n,suiteInvocationId:r,caseIndex:p-1,cwd:i,requestId:a,retries:vu(o?.retries,m.metadata.retries),timeoutMs:_u(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d});if(f.push(t),Bd(t,o,a))break}return f}async function zd(e){let{entries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,flags:o,suiteArtifactsDir:s,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f}=e,p=[];for(let[e,m]of t.entries()){if(Kt(a))break;let{entry:t,suiteIndex:h}=m,g=await Yu({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:vu(o?.retries,t.metadata.retries),timeoutMs:_u(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f});if(p.push(g),Bd(g,o,a))break}return p}function Bd(e,t,n){return Kt(n)||t?.failFast===!0&&e.status===`failed`||Fu(e)}function Vd(e,t,n){let r=t.filter(e=>e.status===`passed`).length,i=t.filter(e=>e.status===`failed`),a=i.length,o=t.filter(e=>e.status===`skipped`).length,s=r+a,c=Ue(t.map(e=>e.status===`skipped`?void 0:e.snapshotDiagnostics));return{total:e,executed:s,passed:r,failed:a,skipped:o,notRun:Math.max(0,e-s-o),durationMs:n,failures:i,tests:t,...c?{snapshotDiagnostics:c}:{}}}function Hd(e){let t=e.sessionStore.get(e.sessionName),n=Ud({failedIndex:e.failedIndex,actions:e.actions,planDigest:e.planDigest,repairHint:e.repairHint,sessionExists:t!==void 0});return t&&(Gd({session:t,resume:n,repairHint:e.repairHint,failedIndex:e.failedIndex,actions:e.actions}),e.sessionStore.set(e.sessionName,t)),n}function Ud(e){let{failedIndex:t,actions:n,planDigest:r,repairHint:i,sessionExists:a}=e,o=i===`record-and-heal`?t+1:t,s=Wd({failedIndex:t,actions:n,repairHint:i,sessionExists:a});return{allowed:!0,from:o,planDigest:r,...s===void 0?{}:{alternateFrom:s}}}function Wd(e){let{failedIndex:t,actions:n,repairHint:r,sessionExists:i}=e;if(r!==`caution`&&r!==`manual`)return;let a=t+1;if(!(a>n.length&&!i))return a}function Gd(e){let{session:t,resume:n,repairHint:r,failedIndex:i,actions:a}=e;t.pendingRecordAndHeal=qd({resume:n,repairHint:r,failedIndex:i,actions:a,actionsCountAtDivergence:t.actions.length})}function Kd(e){e.pendingRecordAndHeal=void 0}function qd(e){let{resume:t,repairHint:n,failedIndex:r,actions:i,actionsCountAtDivergence:a}=e;if(n===`record-and-heal`)return t.allowed?{expectedFrom:t.from,actionsCountAtDivergence:a}:void 0;if(!(n!==`caution`&&n!==`manual`)&&r===i.length)return{expectedFrom:r+1,actionsCountAtDivergence:a}}function Jd(e){return JSON.stringify(Yd(e))}function Yd(e){if(Array.isArray(e))return e.map(Yd);if(!e||typeof e!=`object`)return e;let t=e;return Object.fromEntries(Object.keys(t).sort().map(e=>[e,Yd(t[e])]))}function Xd(e){let t=Jd(Zd(e));return Oi(`sha256`).update(t,`utf8`).digest(`hex`)}function Zd(e){let{actions:t,actionLines:n,actionSourcePaths:r,metadata:i}=e;return{platform:i.platform??null,target:i.target??null,steps:t.map((e,t)=>Qd(e,n[t]??null,r?.[t]??null))}}function Qd(e,t,n){return{command:e.command,positionals:e.positionals??[],flags:e.flags??{},runtime:e.runtime??null,targetEvidence:e.targetEvidence??null,source:{path:n,line:t}}}function $d(e,n){if(e)try{V.appendFileSync(e,`${JSON.stringify(t(n))}\n`)}catch(t){u({level:`warn`,phase:`replay_trace_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}}async function ef(t){let{req:r,sessionName:i,action:a,scope:o,filePath:s,line:c,step:l,sourcePath:u,tracePath:d,invoke:f}=t,p=Me(a,o,{file:u??s,line:c}),m=Date.now();$d(d,{type:`replay_action_start`,ts:new Date(m).toISOString(),replayPath:s,...u?{sourcePath:u}:{},line:c,step:l,command:p.command,positionals:De(p)??[]});let h;try{h=await nf({req:r,sessionName:i,resolved:p,sourceAction:a,scope:o,line:c,step:l,invoke:f})}catch(t){if(!(t instanceof n))throw t;h={ok:!1,error:e(t)}}let g=Date.now();return $d(d,{type:`replay_action_stop`,ts:new Date(g).toISOString(),replayPath:s,...u?{sourcePath:u}:{},line:c,step:l,command:p.command,ok:h.ok,durationMs:g-m,resultTiming:h.ok?af(h.data):void 0,errorCode:h.ok?void 0:h.error.code}),tf(h,u??s,c)}function tf(e,t,n){return e.ok||e.error.details?.replaySource!==void 0?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},replaySource:{path:t,line:n}}}}}async function nf(e){let{req:t,sessionName:n,resolved:r,sourceAction:i,invoke:a}=e,o=of(t.flags,r.flags),s=i.command===`fill`?Ae(ze(i)):void 0;return s&&(o.recordAs=s),await a(rf({token:t.token,session:n,flags:o,runtime:r.runtime,meta:t.meta,internal:{...t.internal,replayPlanStep:!0,...r.command===`open`?{resolvedSessionScope:t.internal?.resolvedSessionScope??Mn(t)}:{}}},r))}function rf(e,t){let n=t.positionals??[];return t.command===`gesture`?{...e,command:t.command,positionals:[],input:be(n,e.flags?.pointerCount)}:t.command===`swipe`?{...e,command:t.command,positionals:[],input:_e(n,{count:e.flags?.count,pauseMs:e.flags?.pauseMs,pattern:e.flags?.pattern})}:{...e,command:t.command,positionals:n}}function af(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.timing;if(!(!t||typeof t!=`object`||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return t===`number`||t===`string`||t===`boolean`}))}function of(e,t){return C(e,{...t??{}})}function sf(e){return mf(e.ok?lf(e.data):cf(e.error.details?.artifactPaths))}function cf(e){return Array.isArray(e)?e.filter(pf):[]}function lf(e){return e?[ff(e.path),ff(e.outPath),...uf(e.artifacts)].filter(pf):[]}function uf(e){return Array.isArray(e)?e.map(df).filter(pf):[]}function df(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;return ff(t.localPath)??ff(t.path)}function ff(e){return typeof e==`string`?e:void 0}function pf(e){return typeof e==`string`}function mf(e){return[...new Set(e.filter(hf))]}function hf(e){try{return V.statSync(e).isFile()}catch{return!1}}function gf(e){if(e.length===0)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],n=t!==void 0&&/^\d+$/.test(t)?t:null,r=m(n===null?e.slice():e.slice(0,-1));return!r||r.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:r.selectorExpression,selectorTimeout:n}}function _f(e){let t=[],n=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];if(t.push(...n),Oe(e.command)){let n=vf(e),r=n[0]??``;r&&!r.startsWith(`@`)&&t.push(n.join(` `))}if(e.command===`fill`){let n=e.positionals?.[0]??``;n&&!n.startsWith(`@`)&&Number.isNaN(Number(n))&&t.push(n)}if(e.command===`get`){let n=e.positionals?.[1]??``;n&&!n.startsWith(`@`)&&t.push(e.positionals.slice(1).join(` `))}if(e.command===`is`){let{split:n}=mt([...e.positionals]);n&&t.push(n.selectorExpression)}if(e.command===`wait`){let{selectorExpression:n}=gf([...e.positionals]);n&&t.push(n)}return hr(t).filter(e=>e.trim().length>0)}function vf(e){let t=e.positionals;if(e.command!==`longpress`)return t;let n=t.at(-1);return t.length>1&&yf(n)?t.slice(0,-1):t}function yf(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}const bf={id:0,"role-label":1,label:2,other:3};function xf(e){let t=new Map;for(let n of e){let e=t.get(n.nodeIndex);(!e||Sf(n.basis)<Sf(e.basis))&&t.set(n.nodeIndex,n)}return[...t.values()].sort((e,t)=>Sf(e.basis)-Sf(t.basis)||e.nodeIndex-t.nodeIndex)}function Sf(e){return bf[e]}function Cf(e){let{kind:t,targetEvidence:n,capture:r}=e;if(t===`identity-mismatch`)return`caution`;if(t===`identity-unverifiable`||!n||r.state!==`available`||!wf(n))return`manual`;let i=Tf(n,r.nodes);return t===`selector-miss`?i?`record-and-heal`:`state-repair`:i?`record-and-heal`:`manual`}function wf(e){return e.ancestry.length>0?!0:e.scrollRegion!==void 0&&Ef(e.scrollRegion)}function Tf(e,t){let n=xt(t),r=Of(e.ancestry,n,t),i=e.scrollRegion;return i&&Ef(i)?r&&Df(i,n,t):r}function Ef(e){return e.id!==void 0||e.label!==void 0}function Df(e,t,n){return n.some(n=>Ti(wi(n,t),e))}function Of(e,t,n){return e.length===0?n.length>0:n.some(n=>{let r=St(n,t,e.length);return!r.broken&&lt(r.chain,e)})}async function kf(e){let{error:t,action:n,index:r,sourcePath:i,sourceLine:a,session:o,sessionName:s,sessionStore:c,logPath:l,responseLevel:u,scrubVars:d=[],planActions:f,planDigest:p}=e,m=le(d),h={code:t.code,message:m(t.message),...t.hint?{hint:m(t.hint)}:{}},g=o?await Nf({session:o,sessionName:s,sessionStore:c,logPath:l,action:n}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},_=Lf(g,m),v=g.state===`available`&&o?Uf({action:n,session:o,nodes:g.nodes,sanitize:m}):[],y=Cf({kind:`action-failure`,targetEvidence:n.targetEvidence,capture:jf(g)}),b=Hd({failedIndex:r+1,actions:f,planDigest:p,repairHint:y,sessionStore:c,sessionName:s});return Af({sessionStore:c,sessionName:s,divergence:{version:1,kind:`action-failure`,step:{index:r+1,source:{path:m(i),line:a}},action:m(Ge(n)),cause:h,screen:_,suggestions:v.slice(0,5),suggestionCount:v.length,resume:b,repairHint:y},responseLevel:u})}function Af(e){let{sessionStore:t,sessionName:n,divergence:r,responseLevel:i}=e;return fe({divergence:r,level:i,writeOverflowArtifact:e=>Yf(t,n,e)})}function jf(e){return e.state===`available`?{state:`available`,nodes:e.nodes}:{state:`unavailable`}}const Mf=[300,500,800,1200,2e3,3e3,4e3];async function Nf(e){let{session:t,sessionName:n,sessionStore:r,logPath:i,action:a,retryLaunchRace:o=!1}=e,s=Ff(a),c=Date.now()+12e3,l=await Pf({session:t,sessionName:n,sessionStore:r,logPath:i,flags:s});if(!o)return l.observation;for(let e of Mf){if(l.observation.state===`available`||!l.retryable)break;let a=c-Date.now();if(a<=0)break;await ht(Math.min(e,a)),l=await Pf({session:t,sessionName:n,sessionStore:r,logPath:i,flags:s})}return l.observation}async function Pf(e){let{session:t,sessionName:n,sessionStore:r,logPath:i,flags:a}=e;try{let e=(await Wr({device:t.device,session:t,flags:a,logPath:i})).snapshot;return bt(e.snapshotQuality)?{observation:{state:`unavailable`,reason:`sparse-snapshot`,hint:`The post-failure snapshot was sparse or unavailable; run snapshot -i to observe the current screen.`},retryable:!0}:(Dn(t,e),ur(t,Bf(e.nodes,t.appBundleId).nodes.map(e=>e.ref)),r.set(n,t),{observation:{state:`available`,nodes:e.nodes,refsGeneration:t.snapshotGeneration??0,appBundleId:t.appBundleId},retryable:!1})}catch(e){return{observation:{state:`unavailable`,reason:`capture-failed`,hint:`Post-failure snapshot capture failed (${e instanceof Error?e.message:String(e)}); the original replay failure is unaffected.`},retryable:yt(e)}}}function Ff(e){return{snapshotInteractiveOnly:If(e)}}function If(e){return Wf(e.command)?Gf(e).requiresRect:!0}function Lf(e,t){if(e.state===`unavailable`)return{state:`unavailable`,reason:t(e.reason),hint:t(e.hint)};let{refs:n,truncated:r}=Vf(e.nodes,t,e.appBundleId);return{state:`available`,refsGeneration:e.refsGeneration,refs:n,...r?{truncated:!0}:{}}}function Rf(e){return!!ve(e,pe(e.type??`Element`))||e.hittable===!0}function zf(e,t){return t!==void 0&&e.bundleId!==void 0&&e.bundleId!==t&&e.hittable===!0}function Bf(e,t){let n=ee(e,t),r=e.filter(e=>e.ref&&!n.has(e.ref)&&Rf(e)),i=r.length>0?r:e.filter(e=>e.ref&&e.hittable===!0),a=i.filter(e=>e.interactionBlocked!==`covered`),o=a.length>0?a:i,s=[...o.filter(e=>zf(e,t)),...o.filter(e=>!zf(e,t))],c=s.slice(0,20);return{nodes:c,truncated:s.length>c.length}}function Vf(e,t,n){let{nodes:r,truncated:i}=Bf(e,n);return{refs:r.map(e=>{let n=pe(e.type??`Element`),r=ve(e,n);return{ref:e.ref,role:t(n),...r?{label:t(r)}:{}}}),truncated:i}}function Hf(e){let t=new Set(e.terms.map(e=>e.key));if(t.has(`id`))return`id`;let n=t.has(`role`),r=t.has(`label`)||t.has(`text`);return n&&r?`role-label`:r||t.has(`value`)?`label`:`other`}function Uf(e){let{action:t,session:n,nodes:r,sanitize:i}=e;if(!Wf(t.command))return[];let a=_f(t);return a.length===0?[]:Kf({candidates:a,nodes:r,session:n,action:t,matching:Gf(t),sanitize:i})}function Wf(e){return Oe(e)||[`fill`,`get`,`is`,`wait`].includes(e)}function Gf(e){let t=Oe(e.command);return{requiresRect:t||e.command===`fill`,allowDisambiguation:t||e.command===`fill`||e.command===`get`&&e.positionals?.[0]===`text`}}function Kf(e){let{candidates:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=[];for(let e of t){let t=qf({candidate:e,nodes:n,session:r,action:i,matching:a,sanitize:o});t&&s.push(t)}return xf(s).map(e=>e.suggestion)}function qf(e){let{candidate:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=b(t);if(!s)return;let c=ct(n,s,{platform:r.device.platform,requireRect:a.requiresRect,requireUnique:!0,disambiguateAmbiguous:a.allowDisambiguation});if(!c)return;let l=Hf(c.selector);return{suggestion:Jf({node:c.node,nodes:n,session:r,action:i,basis:l,sanitize:o}),basis:l,nodeIndex:c.node.index}}function Jf(e){let{node:t,nodes:n,session:r,action:i,basis:a,sanitize:o}=e,s=pt(t,r.device.platform,{action:i.command===`fill`?`fill`:Oe(i.command)?`click`:`get`,nodes:n}),c=pe(t.type??`Element`),l=ve(t,c);return{selector:o(s.join(` || `)),basis:a,...t.ref?{ref:t.ref}:{},role:o(c),...l?{label:o(l)}:{}}}function Yf(e,n,r){try{let i=H.join(e.ensureSessionDir(n),`replay-divergence`);V.mkdirSync(i,{recursive:!0});let a=`${Date.now()}-step${r.step.index}.json`,o=H.join(i,a);return V.writeFileSync(o,`${JSON.stringify(t(r),null,2)}\n`),{artifactPath:o}}catch{return{artifactUnavailable:!0}}}function Xf(e){return{...e,hint:e.hint??$f(e.details,`hint`),diagnosticId:e.diagnosticId??$f(e.details,`diagnosticId`),logPath:e.logPath??$f(e.details,`logPath`)}}function Zf(e){let{error:t,action:n,step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c}=e;return Qf({error:t,actionLabel:Ge(n),action:n.command,positionals:De(n)??[],step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c})}function Qf(e){let{error:t,actionLabel:n,action:r,positionals:i,step:a,replayPath:o,artifactPaths:s,snapshotDiagnostics:c,divergence:l,scrubVars:u}=e;return{ok:!1,error:{code:`REPLAY_DIVERGENCE`,message:Se(`Replay failed at step ${a} (${n}): ${t.message}`,u),hint:t.hint===void 0?void 0:Se(t.hint,u),diagnosticId:t.diagnosticId,logPath:t.logPath,...t.retriable===void 0?{}:{retriable:t.retriable},...t.supportedOn===void 0?{}:{supportedOn:t.supportedOn},details:{...tp(t.details),replayPath:o,step:a,action:r,positionals:i,artifactPaths:s,...c?{snapshotDiagnostics:c}:{},divergence:l}}}}function $f(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}const ep=[`reason`,`retriable`,`supportedOn`];function tp(e){if(!e)return{};let t={};for(let n of ep)e[n]!==void 0&&(t[n]=e[n]);return t}async function np(e){return await rp({...e,snapshotDiagnostics:je(e.snapshotDiagnosticSamples)})}async function rp(e){let{response:t,action:n,index:r,replayPath:i,sourcePath:a,sourceLine:o,artifactPaths:s=[],snapshotDiagnostics:c,scope:l,req:u,sessionName:d,sessionStore:f,logPath:p,planActions:m,planDigest:h}=e;if(t.ok)return t;let g=ip(t.error.details?.replaySource),_=Ne(l),v=Xf(t.error),y=await kf({error:v,action:n,index:r,sourcePath:g?.path??a,sourceLine:g?.line??o,session:f.get(d),sessionName:d,sessionStore:f,logPath:p,responseLevel:u.meta?.responseLevel,scrubVars:_,planActions:m,planDigest:h});return Zf({error:v,action:n,step:r+1,replayPath:i,artifactPaths:s,snapshotDiagnostics:c,divergence:y,scrubVars:_})}function ip(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=typeof t.path==`string`&&t.path.length>0?t.path:void 0,r=typeof t.line==`number`?t.line:void 0;if(!(n===void 0&&r===void 0))return{path:n,line:r}}function ap(e,t){return{...e??{},...t.platform!==void 0&&e?.platform===void 0?{platform:t.platform}:{},...t.target!==void 0&&e?.target===void 0?{target:t.target}:{}}}function op(e){return{platform:typeof e?.platform==`string`?e.platform:void 0,target:typeof e?.target==`string`?e.target:void 0}}function sp(e,t,n,r,i){let a=e?.replayFrom,o=e?.replayPlanDigest;if(a===void 0&&o===void 0)return{ok:!0,value:0};if(a===void 0||o===void 0)return cp(`replay --from requires --plan-digest (and --plan-digest requires --from).`);let s=lp({from:a,digest:o,planDigest:n,actionCount:t,pendingRecordAndHeal:r,sessionActionsLength:i});return s?cp(s):{ok:!0,value:a-1}}function cp(e){return{ok:!1,response:R(`INVALID_ARGS`,e)}}function lp(e){let{from:t,digest:n,planDigest:r,actionCount:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e,s=[()=>up({from:t,actionCount:i,pendingRecordAndHeal:a}),()=>dp({from:t,pendingRecordAndHeal:a,sessionActionsLength:o}),()=>fp(n,r)];for(let e of s){let t=e();if(t)return t}}function up(e){let{from:t,actionCount:n,pendingRecordAndHeal:r}=e,i=t===n+1&&r!==void 0&&r.expectedFrom===t;return Number.isInteger(t)&&t>=1&&(t<=n||i)?void 0:`replay --from ${t} is out of range for a ${n}-step plan.`}function dp(e){let{from:t,pendingRecordAndHeal:n,sessionActionsLength:r}=e;if(!(n?.expectedFrom!==t||r!==n.actionsCountAtDivergence))return`replay --from ${t} continues a record-and-heal-shaped repair, but no corrective action was recorded in this repair segment; press the correct control via a blessed @ref from the divergence's screen.refs (recorded, no --no-record) — or, if your corrective action was a read (get/is/find/snapshot), re-run it with --record so it lands in the heal — before resuming with --from ${t}.`}function fp(e,t){if(e!==t)return`replay --plan-digest does not match the current plan digest; the script, its includes, or its platform-conditioned expansion changed since the divergence report was generated. Run a fresh full replay to get a new digest.`}function pp(e){let{recorded:t,token:n,nodes:r,platform:i,refLabel:a,requireRect:o,allowDisambiguation:s}=e,c=mp({token:n,nodes:r,platform:i,refLabel:a,requireRect:o,allowDisambiguation:s}),l=xt(r),u=st(t),d=wt(c.matchedNodes,l,u,t.ancestry),f=d.filter(e=>Ei(r,e)===t.sibling),p=d.filter(e=>Ti(wi(e,l),t.scrollRegion)),m=Ci(p)[t.viewportOrder]?.ref,h=dt({winnerRef:c.winnerRef,matchedRefs:c.matchedNodes.map(e=>e.ref),identitySetRefs:d.map(e=>e.ref),siblingMatchRefs:f.map(e=>e.ref),regionMemberRefs:p.map(e=>e.ref),viewportCandidateRef:m}),g=c.matchedNodes.find(e=>e.ref===c.winnerRef);return h.outcome===`verified`&&g?{verified:!0,winnerNode:g,matchCount:c.matchedNodes.length}:h.outcome===`verified`?{verified:!1,kind:`identity-unverifiable`,matchCount:c.matchedNodes.length,observedNode:void 0,candidateNodes:d.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Verification isolated a member that is not part of the matched-node domain (capture anomaly).`}:{verified:!1,..._p({classification:h,matchCount:c.matchedNodes.length,winnerNode:g,identitySet:d,byIndex:l,recorded:t})}}function mp(e){let{token:t,nodes:n,platform:r,refLabel:i,requireRect:a,allowDisambiguation:o}=e;return t.startsWith(`@`)?hp(n,t,i,a):gp(n,t,r,a,o)}function hp(e,t,n,r){let o=e=>e!==null&&(!r||!!e.rect),s=a(t),c=s?i(e,s):null;if(o(c))return{matchedNodes:[c],winnerRef:c.ref};let l=n?tt(e,n):null;return o(l)?{matchedNodes:[l],winnerRef:l.ref}:{matchedNodes:[],winnerRef:``}}function gp(e,t,n,r,i){let a=b(t);if(!a)return{matchedNodes:[],winnerRef:``};let o=ct(e,a,{platform:n,requireRect:r,requireUnique:!0,disambiguateAmbiguous:i});return o?{matchedNodes:e.filter(e=>r&&!e.rect?!1:at(e,o.selector,n)),winnerRef:o.node.ref}:{matchedNodes:ut(e,a,{platform:n,requireRect:r})?.matchedNodes??[],winnerRef:``}}function _p(e){let{classification:t,matchCount:n,winnerNode:r,identitySet:i,byIndex:a,recorded:o}=e;switch(t.reason){case`selector-miss`:return{kind:`selector-miss`,matchCount:0,observedNode:void 0,candidateNodes:[],mismatches:[],causeCode:`SELECTOR_MISS`,causeMessage:`The recorded target no longer matches any current element.`};case`identity-set-empty`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?vp(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`The recorded selector/ref still matches, but nothing in the current tree carries the recorded identity.`};case`unique-but-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?vp(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`Exactly one current element carries the recorded identity, but the resolved target is a different element.`};case`signal-isolated-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?vp(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`A disambiguation signal (sibling or viewport position) isolated a different element than the resolved target.`};case`no-signal-isolation`:return{kind:`identity-unverifiable`,matchCount:n,observedNode:r,candidateNodes:i.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`${i.length} current elements carry the recorded identity and neither disambiguation signal isolated one.`}}}function vp(e,t,n){let r=Di(t),i=St(t,n,Math.max(e.ancestry.length,1)).chain;return[...yp(e,r),...Sp(e.ancestry,i)].slice(0,5)}function yp(e,t){let n=[];return e.id!==t.id&&n.push(`id: recorded=${e.id??`(none)`} observed=${t.id??`(none)`}`),e.role!==t.role&&n.push(`role: recorded=${e.role} observed=${t.role}`),e.label!==t.label&&n.push(`label: recorded=${e.label??`(none)`} observed=${t.label??`(none)`}`),n}function bp(e){return e?`${e.role}${e.label?`/${e.label}`:``}`:`(missing)`}function xp(e,t){return!t||t.role!==e.role?!0:e.label!==void 0&&t.label!==e.label}function Sp(e,t){for(let[n,r]of e.entries()){let e=t[n];if(xp(r,e))return[`ancestry[${n}]: recorded=${bp(r)} observed=${bp(e)}`]}return[]}function Cp(e){let t=e.positionals??[];if(e.command===`get`)return t[1];if(e.command===`is`)return mt(t).split?.selectorExpression;if(!Oe(e.command)&&e.command!==`fill`)return;let n=t[0];if(n!==void 0&&!(Tp(n)&&Tp(t[1])))return n}function wp(e){let t=e.result?.refLabel;return typeof t==`string`&&t.length>0?t:void 0}function Tp(e){return e!==void 0&&e.trim().length>0&&!Number.isNaN(Number(e))}function Ep(e,t){let{recorded:n,action:r,step:i,sourcePath:a,sourceLine:o,replayPath:s,artifactPaths:c,sessionName:l,sessionStore:u,responseLevel:d,scrubVars:f,planActions:p,planDigest:m}=e,h=le(f),g={classification:t.kind,...t.matchCount===void 0?{}:{matchCount:t.matchCount},recorded:Lp(st(n),h),...t.observed?{observed:Lp(t.observed,h)}:{},mismatches:t.mismatches.slice(0,5).map(e=>h(e)),candidates:t.candidateNodes.slice(0,5).map(e=>Rp(e,h))},_=Cf({kind:t.kind,targetEvidence:n,capture:t.repairCapture}),v=Hd({failedIndex:i,actions:p,planDigest:m,repairHint:_,sessionStore:u,sessionName:l}),y=Af({sessionStore:u,sessionName:l,divergence:{version:1,kind:t.kind,step:{index:i,source:{path:h(a),line:o}},action:h(Ge(r)),cause:{code:t.causeCode,message:h(t.causeMessage),...t.causeHint?{hint:h(t.causeHint)}:{}},screen:t.screen,suggestions:[],suggestionCount:0,resume:v,repairHint:_,targetBinding:g},responseLevel:d});return Zf({error:{code:t.causeCode,message:t.causeMessage},action:r,step:i,replayPath:s,artifactPaths:c,divergence:y,scrubVars:f})}async function Dp(e){let{action:t,scope:n,sourcePath:r,sourceLine:i,replayPath:a,step:o,sessionName:s,sessionStore:c,logPath:l,artifactPaths:u,responseLevel:d,planActions:f,planDigest:p}=e,m=t.targetEvidence;if(!m)return{verified:!0};let h=c.get(s);if(!h)return{verified:!0};let _=Me(t,n,{file:r,line:i}),y=Ne(n),x=le(y),S={recorded:m,action:t,step:o,sourcePath:r,sourceLine:i,replayPath:a,artifactPaths:u,sessionName:s,sessionStore:c,responseLevel:d,scrubVars:y,planActions:f,planDigest:p},C=async()=>{let e=await Nf({session:h,sessionName:s,sessionStore:c,logPath:l,action:t});return Ep(S,{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`The recorded target evidence could not verify itself when it was captured (a structural capture anomaly), so replay cannot trust it before acting.`,screen:Lf(e,x),repairCapture:jf(e)})};if(g(t.command)===`post-resolution`)return v(_.positionals??[])?.kind===`selector`?m.verification===`unverifiable`?{verified:!1,response:await C()}:{verified:!0,deferredLandmark:m}:{verified:!0};let w=Cp(_);if(w===void 0||!w.startsWith(`@`)&&!b(w))return{verified:!0};if(m.verification===`unverifiable`)return{verified:!1,response:await C()};let T=await Nf({session:h,sessionName:s,sessionStore:c,logPath:l,action:t,retryLaunchRace:!0});if(T.state!==`available`)return{verified:!1,response:Ep(S,{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Could not capture a fresh snapshot to verify the recorded target before acting (${T.reason}).`,causeHint:T.hint,screen:Lf(T,x),repairCapture:jf(T)})};let ee=Gf(t),E=pp({recorded:m,token:w,nodes:T.nodes,platform:h.device.platform,refLabel:wp(t),requireRect:ee.requiresRect,allowDisambiguation:ee.allowDisambiguation});return E.verified?{verified:!0,guard:{expected:{identity:Di(E.winnerNode),structural:ot(E.winnerNode,T.nodes)},matchCount:E.matchCount}}:{verified:!1,response:Ep(S,{kind:E.kind,matchCount:E.matchCount,observed:E.observedNode?Di(E.observedNode):void 0,candidateNodes:E.candidateNodes,mismatches:E.mismatches,causeCode:E.causeCode,causeMessage:E.causeMessage,screen:Lf(T,x),repairCapture:jf(T)})}}function Op(e){return!e.ok&&e.error.details?.reason===`replay_target_guard_mismatch`}async function kp(e,t){let{action:n,scope:r,failedResponse:i,sessionName:a,sessionStore:o,logPath:s}=e,c=n.targetEvidence;if(!c)return i;let l=Ne(r),u=le(l),d=t(c,i.ok?void 0:i.error.details),f=o.get(a),p=f?await Nf({session:f,sessionName:a,sessionStore:o,logPath:s,action:n}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`};return Ep({recorded:c,action:n,step:e.step,sourcePath:e.sourcePath,sourceLine:e.sourceLine,replayPath:e.replayPath,artifactPaths:e.artifactPaths,sessionName:a,sessionStore:o,responseLevel:e.responseLevel,scrubVars:l,planActions:e.planActions,planDigest:e.planDigest},{kind:`identity-mismatch`,matchCount:d.matchCount,observed:d.observed,candidateNodes:[],mismatches:d.mismatches,causeCode:`IDENTITY_MISMATCH`,causeMessage:d.causeMessage,screen:Lf(p,u),repairCapture:jf(p)})}async function Ap(e){return await kp(e,(t,n)=>{let r=Pp(n?.observed),i=Fp(n?.expectedStructural,n?.observedStructural);return{matchCount:e.guard.matchCount,observed:r,mismatches:[...r?yp(t,r):[],...i?[i]:[]],causeMessage:`Dispatch resolution (with occlusion/visibility guards) resolved a different element than pre-action verification isolated; the action was not sent.`}})}function jp(e){return!e.ok&&e.error.details?.reason===`wait_landmark_identity_mismatch`}async function Mp(e){return await kp(e,(e,t)=>{let n=Pp(t?.observed),r=Np(t?.observedAncestry);return{matchCount:typeof t?.matchCount==`number`?t.matchCount:void 0,observed:n,mismatches:n?[...yp(e,n),...Sp(e.ancestry,r)]:[],causeMessage:`Candidates matched the recorded wait selector during polling, but none carried the recorded landmark identity before the timeout; the wait did not report success.`}})}function Np(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))return[];let e=n;if(typeof e.role!=`string`)return[];t.push({role:e.role,...typeof e.label==`string`?{label:e.label}:{}})}return t}function Pp(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.role==`string`)return{...typeof t.id==`string`?{id:t.id}:{},role:t.role,...typeof t.label==`string`?{label:t.label}:{}}}function Fp(e,t){let n=Ip(e),r=Ip(t);if(!(!n||!r)&&!(n.documentOrder===r.documentOrder&&n.sibling===r.sibling))return`position: recorded=doc${n.documentOrder}/sibling${n.sibling} observed=doc${r.documentOrder}/sibling${r.sibling}`}function Ip(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(!(typeof t.documentOrder!=`number`||typeof t.sibling!=`number`))return{documentOrder:t.documentOrder,sibling:t.sibling}}function Lp(e,t){return{...e.id===void 0?{}:{id:t(e.id)},role:t(e.role),...e.label===void 0?{}:{label:t(e.label)}}}function Rp(e,t){let n=pe(e.type??`Element`),r=ve(e,n);return{...e.ref?{ref:e.ref}:{},role:t(n),...r?{label:t(r)}:{}}}function zp(e){let{req:t,sessionName:n,metadata:r,resolvedPath:i}=e,a=t.flags??{},o={AD_SESSION:n,AD_FILENAME:Bp(t,i)};return Hp(o,`AD_PLATFORM`,a.platform??r.platform),Hp(o,`AD_TARGET`,a.target??r.target),Hp(o,`AD_DEVICE`,a.device),Hp(o,`AD_DEVICE_ID`,Vp(a)),Up(o,`AD_SHARD_INDEX`,a.shardIndex),Up(o,`AD_SHARD_COUNT`,a.shardCount),Hp(o,`AD_ARTIFACTS`,a.artifactsDir),o}function Bp(e,t){let n=e.meta?.cwd??process.cwd();return H.relative(n,t)||t}function Vp(e){return typeof e.serial==`string`?e.serial:e.udid}function Hp(e,t,n){typeof n==`string`&&n.length>0&&(e[t]=n)}function Up(e,t,n){typeof n==`number`&&(e[t]=String(n))}const Wp=3e4,Gp=1e3;function Kp(t){let{scriptPath:r,env:i}=t,a=V.readFileSync(r,`utf8`),o=Object.create(null);try{Ni.runInNewContext(a,qp(i,o),{filename:r,timeout:Wp})}catch(t){let i=e(t);throw new n(i.code,`Maestro runScript failed: ${i.message}`,y({...i.details??{},hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,retriable:i.retriable,supportedOn:i.supportedOn,scriptPath:r}),t instanceof Error?t:void 0)}return Zp(o,r),Object.fromEntries(Object.entries(o).map(([e,t])=>[`output.${e}`,Qp(t)]))}function qp(e,t){return{...e,output:t,json:Jp,http:{post:(e,t)=>Xp(`POST`,e,t)}}}function Jp(e){if(typeof e!=`string`)throw new n(`COMMAND_FAILED`,`Maestro runScript json() expected a string body, received ${typeof e}.`);if(e.trim().length===0)throw new n(`COMMAND_FAILED`,`Maestro runScript json() received an empty body.`,{hint:`Check the preceding HTTP response status and setup server output.`});try{return JSON.parse(e,Yp)}catch(t){throw new n(`COMMAND_FAILED`,`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,Gp)},t instanceof Error?t:void 0)}}function Yp(e,t){return e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t}function Xp(e,t,r){let i=c(process.execPath,[`-e`,`
1
+ import{S as e,T as t,_ as n,c as r,d as i,p as a,t as o,v as s}from"./sdk-contracts.js";import{C as c,N as l,P as u,j as d,p as f,s as p,v as m}from"./sdk-android-adb.js";import{$ as h,G as g,I as _,L as v,R as y,T as b,et as x,m as S,n as C,t as ee}from"./sdk-batch-runner.js";import{At as w,Ct as T,Dn as te,Dt as E,Et as ne,Gt as re,On as D,Ot as ie,Wt as ae,_t as oe,an as se,en as ce,i as le,kt as ue,m as de,nn as fe,nt as pe,pn as me,rn as O,tn as he,tt as ge,u as _e,vn as ve,w as ye,wt as be,xt as xe,yn as Se,yt as Ce}from"./recording-export-quality.js";import{$ as we,A as Te,B as Ee,F as De,H as Oe,K as ke,O as k,Y as Ae,a as je,at as Me,et as Ne,it as Pe,j as Fe,mt as Ie,n as Le,nt as Re,ot as ze,pt as Be,rt as Ve,st as He,t as Ue,tt as We,z as Ge}from"./snapshot-diagnostics.js";import{n as Ke}from"./version.js";import{_ as qe,c as A,d as Je,h as j,l as Ye,m as Xe,o as M,p as Ze,s as N}from"./sdk-device.js";import{A as Qe,B as $e,E as et,F as tt,H as nt,I as rt,M as it,_ as at,c as ot,ft as st,h as ct,ht as lt,m as ut,pt as dt,rt as ft,t as pt,w as mt}from"./sdk-selectors.js";import{L as ht,_ as gt,v as _t}from"./gesture-plan-types.js";import{t as vt}from"./timeouts.js";import{n as yt,r as bt,t as xt}from"./runtime-transport.js";import{a as St,i as Ct,l as wt,o as Tt}from"./android-input-method-overlays.js";import{n as Et}from"./sdk-app-inventory.js";import{o as Dt}from"./runtime.js";import{f as Ot,p as kt,s as At}from"./app-lifecycle.js";import{a as jt,d as Mt,l as Nt,u as Pt}from"./install-artifact.js";import{a as Ft,o as It,r as Lt,s as Rt}from"./boot-diagnostics.js";import{a as zt,l as Bt,o as Vt,p as Ht,s as Ut}from"./device.js";import{o as Wt}from"./selector-vocabulary.js";import{A as Gt,D as Kt,E as qt,F as Jt,I as Yt,L as Xt,M as Zt,N as Qt,P as $t,T as P,j as en,u as tn,w as nn}from"./runner-disposal.js";import{C as F,S as rn,a as an,c as on,d as sn,g as cn,h as ln,i as un,l as I,m as dn,n as fn,s as L,t as R,u as pn,x as mn,y as hn}from"./context.js";import{i as gn,n as _n,o as vn,s as yn,t as bn}from"./register-builtins.js";import{a as xn}from"./tool-provider.js";import{r as Sn}from"./helper.js";import{L as Cn}from"./physical-device-control.js";import{c as wn,i as Tn,l as En,n as Dn,r as On,s as kn,t as An}from"./runner-client.js";import{n as jn,s as Mn}from"./agent-browser-tool.js";import{$ as Nn,$t as Pn,A as Fn,B as In,C as Ln,D as Rn,E as zn,F as Bn,Ft as Vn,G as Hn,H as Un,Ht as Wn,I as Gn,It as Kn,J as qn,K as Jn,L as Yn,M as Xn,N as Zn,O as Qn,P as $n,Q as er,Qt as tr,R as nr,S as rr,T as ir,U as ar,Ut as or,V as sr,Vt as cr,W as lr,Wt as ur,X as dr,Xt as fr,Y as pr,Z as mr,Zt as hr,_ as gr,_t as _r,a as vr,an as yr,b as br,bt as xr,c as Sr,ct as Cr,d as wr,dt as Tr,en as Er,et as Dr,f as Or,ft as kr,g as z,gt as Ar,h as jr,ht as Mr,i as Nr,in as Pr,it as Fr,j as Ir,jt as Lr,k as Rr,kt as zr,l as Br,lt as Vr,m as Hr,mt as Ur,n as Wr,nn as Gr,nt as Kr,o as qr,ot as Jr,p as Yr,pt as Xr,q as Zr,r as Qr,rn as $r,rt as ei,s as ti,sn as ni,st as ri,t as ii,tn as ai,tt as oi,u as si,ut as ci,v as li,vt as ui,w as di,wt as fi,x as pi,y as mi,yt as hi,z as gi,zt as _i}from"./internal/daemon.js";import{i as vi,n as B,r as yi,t as bi}from"./compatibility-policy.js";import"./apps.js";import{a as xi,n as Si}from"./simulator.js";import{i as Ci}from"./app-resolution.js";import{a as wi,n as Ti,o as Ei,r as Di,t as Oi}from"./session-target-evidence.js";import{createHash as ki}from"node:crypto";import V,{promises as Ai}from"node:fs";import ji from"node:os";import H from"node:path";import{access as Mi}from"node:fs/promises";import{setTimeout as Ni}from"node:timers/promises";import Pi from"node:vm";function Fi(e){throw new n(`UNSUPPORTED_OPERATION`,`install_from_source ${String(e.kind)} sources require a compatible remote daemon`)}function Ii(e){let t=e.meta?.installSource;if(!t)throw new n(`INVALID_ARGS`,`install_from_source requires a source payload`);switch(t.kind){case`url`:if(!t.url||t.url.trim().length===0)throw new n(`INVALID_ARGS`,`install_from_source url source requires a non-empty url`);return t;case`path`:if(!t.path||t.path.trim().length===0)throw new n(`INVALID_ARGS`,`install_from_source path source requires a non-empty path`);return t;case`github-actions-artifact`:throw new n(`UNSUPPORTED_OPERATION`,`install_from_source github-actions-artifact sources require a compatible remote daemon`);default:Fi(t)}}function Li(e){let t=Ii(e),n=e.meta?.uploadedArtifactId;return!n||t.kind!==`path`?{source:t,cleanup:()=>{}}:{source:{kind:`path`,path:ni(n,e.meta?.tenantId)},cleanup:()=>{yr(n)}}}function Ri(e){return e===`ios`||e===`android`?e:void 0}function zi(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(r!==void 0&&r<=0)throw new n(`INVALID_ARGS`,`install_from_source retentionMs must be a positive integer`);return{enabled:!0,ttlMs:r}}async function Bi(e){let t=Ri(e.flags?.platform);if(e.session){if(t&&e.session.device.platform!==t)throw new n(`INVALID_ARGS`,`install_from_source requested platform ${t}, but session is bound to ${e.session.device.platform}`);return await z(e.session.device),e.session.device}if(!t)throw new n(`INVALID_ARGS`,`install_from_source requires platform "ios" or "android" when no session is provided`);let r=await cn(e.flags??{});return await z(r),r}async function Vi(e){let{prepared:t,retention:n,req:r,session:i,sessionName:a}=e;if(n.enabled)return await pi({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:r.meta?.tenantId,sessionName:i?a:void 0,ttlMs:n.ttlMs})}function Hi(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}function Ui(e){let{session:t,sessionStore:n,req:r,data:i}=e;jr(n,t,r,`install_source`,i,{positionals:[]})}async function Wi(t){let{req:n,sessionName:r,sessionStore:i}=t,a=i.get(r);try{let e=Li(n),t=zi(n),o=await Bi({session:a,flags:n.flags}),s=I(`install`,o,{message:`install_from_source is not supported on this device`});if(s)return s;let c=Zt(n.meta?.requestId);if(N(o)){let{prepareIosInstallArtifact:s}=await import(`./install-artifact2.js`).then(e=>e.t),l=await s(e.source,{signal:c});return await Gi({prepared:l,retention:t,req:n,resolvedSourceCleanup:()=>e.cleanup(),session:a,sessionName:r,sessionStore:i,buildResult:async e=>await Ki(o,l,e)})}let{prepareAndroidInstallArtifact:l}=await import(`./install-artifact.js`).then(e=>e.t),u=await l(e.source,{signal:c});return await Gi({prepared:u,retention:t,req:n,resolvedSourceCleanup:()=>e.cleanup(),session:a,sessionName:r,sessionStore:i,buildResult:async e=>await qi(o,u,e)})}catch(t){return{ok:!1,error:e(t)}}}async function Gi(e){let t;try{t=await Vi(e);let n=await e.buildResult(t),r=Se(n,Qi(n));return Ui({session:e.session,sessionStore:e.sessionStore,req:e.req,data:r}),{ok:!0,data:r}}catch(n){throw t&&await mi(t.materializationId,e.req.meta?.tenantId).catch(()=>{}),n}finally{await e.prepared.cleanup(),e.resolvedSourceCleanup()}}async function Ki(e,t,n){let r=await rn(e,t.installablePath,{appIdentifierHint:t.bundleId});if(!r){let{installIosInstallablePath:n}=await import(`./apps.js`).then(e=>e.t);await n(e,t.installablePath)}return Ji(t,r,n)}async function qi(e,t,n){let r=await rn(e,t.installablePath,{packageNameHint:t.packageName}),i=await Zi(e,t,r),{inferAndroidAppName:a}=await import(`./app-lifecycle.js`).then(e=>e.t),o=a(i);return{...Hi(n),packageName:i,...Xi(r?.appName??o),launchTarget:r?.launchTarget??i}}function Ji(e,t,n){let r=Yi(e,t),i=t?.appName??e.appName;return{...Hi(n),bundleId:r,...Xi(i),launchTarget:t?.launchTarget??r}}function Yi(e,t){let r=t?.bundleId??e.bundleId;if(r)return r;throw new n(`COMMAND_FAILED`,`Installed iOS app identity could not be resolved from the artifact`)}function Xi(e){return e?{appName:e}:{}}async function Zi(e,t,r){let i=r?.packageName??r?.launchTarget;if(i)return i;let{installAndroidInstallablePathAndResolvePackageName:a}=await import(`./app-lifecycle.js`).then(e=>e.t),o=await a(e,t.installablePath,t.packageName);if(!o)throw new n(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return o}function Qi(e){return`Installed: ${pe(e)}`}async function $i(t){let{req:r}=t;try{let e=r.meta?.materializationId?.trim();if(!e)throw new n(`INVALID_ARGS`,`release_materialized_paths requires a materializationId`);return await mi(e,r.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(t){return{ok:!1,error:e(t)}}}function U(e){return N(e)&&e.kind===`simulator`}function ea(e){return e.platform===`android`&&e.kind===`emulator`}function W(e,t,n){return t||hr(n)?null:L(`INVALID_ARGS`,`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}function ta(e){return typeof e?.session==`string`&&e.session.trim().length>0}async function na(e,t){F(e)||!U(e)||t<=0||await new Promise(e=>setTimeout(e,t))}async function G(e){let t=hr(e.flags)||!e.session?await cn(e.flags??{},{allowStoppedAndroidAvdPlaceholders:e.allowStoppedAndroidAvdPlaceholders}):await ra(e.session.device);return e.ensureReady!==!1&&await z(t),t}async function ra(e){if(F(e)||!N(e)||e.kind!==`simulator`||process.platform!==`darwin`)return e;if(kn(e.id)?.alive)return{...e,booted:!0};let t={platform:`ios`,target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await cn(t)}catch(e){if(!(e instanceof n)||e.code!==`DEVICE_NOT_FOUND`)throw e}return await cn({platform:`ios`,target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function ia(e){let t=e.flags?.device?.trim();if(t)return t;if(e.resolvedDevice?.platform===`android`&&e.resolvedDevice.kind===`emulator`)return e.resolvedDevice.name;if(e.sessionDevice?.platform===`android`&&e.sessionDevice.kind===`emulator`)return e.sessionDevice.name}function aa(e,t){return t?hi(t,e).length===0:!1}const oa=`debug_http_host`,sa=`dev_server_https`,ca=`RCT_jsLocation`,la=`RCT_packager_scheme`,ua=`React Native runtime hints require adb run-as access to the app sandbox. Verify the app is debuggable and the selected package/device are correct.`,da=[`<?xml version="1.0" encoding="utf-8" standalone="yes" ?>`,`<map>`,`</map>`,``].join(`
2
+ `);function fa(e){return xt(e)!==void 0}async function pa(e){let{device:t,appId:n,runtime:r}=e;if(F(t)||!n)return;let i=xt(r);if(i){if(t.platform===`android`){await ga(t,n,i);return}N(t)&&t.kind===`simulator`&&await wa(t,n,i)}}async function ma(e){let{device:t,appId:n}=e;if(n){if(t.platform===`android`){await _a(t,n);return}N(t)&&t.kind===`simulator`&&await Ta(t,n)}}function ha(e){return[`shared_prefs/${e}_preferences.xml`,`shared_prefs/ReactNativeDevPrefs.xml`]}async function ga(e,t,n){ja(t);let r=[];for(let i of ha(t)){let a=Da(await va(e,t,i),oa,`${n.host}:${n.port}`);a=Oa(a,sa,n.scheme===`https`),r.push({path:i,xml:a})}await ya(e,t,r)}async function _a(e,t){ja(t);let n=[];for(let r of ha(t)){let i=await va(e,t,r),a=Aa(Aa(i,oa),sa);a!==i&&n.push({path:r,xml:a})}n.length!==0&&await ya(e,t,n)}async function va(e,t,n){let r=await jt(e,[`shell`,`run-as`,t,`cat`,n],{allowFailure:!0});return r.exitCode===0?Ea(r.stdout):da}async function ya(e,t,n){await ba(e,t);try{await Sa(e,t,n)}catch(e){throw Ca(e,t)}}async function ba(e,t){let n=[`shell`,`run-as`,t,`id`],r=await jt(e,n,{allowFailure:!0});if(r.exitCode!==0)throw xa(r,t,n)}function xa(e,t,r){let i=Pa(e.stdout,e.stderr);return new n(`COMMAND_FAILED`,i?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,f(e,{package:t,cmd:`adb`,args:r,hint:i?ua:`adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information.`}))}async function Sa(e,t,n){await jt(e,[`shell`,`run-as`,t,`mkdir`,`-p`,`shared_prefs`]);for(let r of n)await jt(e,[`shell`,`run-as`,t,`tee`,r.path],{stdin:r.xml.trimEnd()})}function Ca(e,t){let r=s(e);if(r.code===`TOOL_MISSING`)return r;let i=Pa(typeof r.details?.stdout==`string`?r.details.stdout:``,typeof r.details?.stderr==`string`?r.details.stderr:``);return new n(`COMMAND_FAILED`,i?`Failed to access Android app sandbox for ${t}`:`Failed to write Android runtime hints for ${t}`,{...r.details??{},package:t,cmd:`adb`,phase:`write-runtime-hints`,hint:i?ua:`adb run-as succeeded, but writing React Native dev-server preferences failed. Inspect stderr/details for the failing shell command.`},r)}async function wa(e,t,n){await xn(Cn(e,[`spawn`,e.id,`defaults`,`write`,t,ca,`-string`,`${n.host}:${n.port}`])),await xn(Cn(e,[`spawn`,e.id,`defaults`,`write`,t,la,`-string`,n.scheme]))}async function Ta(e,t){await xn(Cn(e,[`spawn`,e.id,`defaults`,`delete`,t,ca]),{allowFailure:!0}),await xn(Cn(e,[`spawn`,e.id,`defaults`,`delete`,t,la]),{allowFailure:!0})}function Ea(e){let t=e.trim();return!t.includes(`<map`)||!t.includes(`</map>`)?da:`${t}\n`}function Da(e,t,n){let r=` <string name="${Na(t)}">${Na(n)}</string>`;return ka(Aa(e,t),r)}function Oa(e,t,n){let r=` <boolean name="${Na(t)}" value="${n?`true`:`false`}" />`;return ka(Aa(e,t),r)}function ka(e,t){return Ea(e).replace(`</map>`,`${t}\n</map>`)}function Aa(e,t){let n=Ma(t);return Ea(e).replace(RegExp(`^\\s*<string name="${n}">[\\s\\S]*?<\\/string>\\n?`,`m`),``).replace(RegExp(`^\\s*<boolean name="${n}" value="(?:true|false)"\\s*\\/?>\\n?`,`m`),``)}function ja(e){if(Ot(e)!==`binary`)return;let t=kt(e);throw new n(`INVALID_ARGS`,t,{package:e,hint:t})}function Ma(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Na(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`).replaceAll(`'`,`&apos;`)}function Pa(e,t){let n=`${e}\n${t}`.toLowerCase();return[`run-as: package not debuggable`,`run-as: permission denied`,`run-as: package is unknown`,`run-as: unknown package`,`is unknown`,`is not an application`,`could not set capabilities`].some(e=>n.includes(e))}const Fa=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function Ia(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function La(e,t){if(e!==void 0){if(typeof e!=`string`)throw new n(`INVALID_ARGS`,`Invalid open runtime ${t}: expected string.`);return yt(e)}}function Ra(e){if(e!==void 0){if(!Number.isInteger(e)||e<1||e>65535)throw new n(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function za(e){if(e!==void 0){if(typeof e!=`number`)throw new n(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Ra(e)}}function Ba(e,t,r){if(e===void 0)return r;if(e!==`ios`&&e!==`android`)throw new n(`INVALID_ARGS`,`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new n(`INVALID_ARGS`,`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}function Va(e){if(e===`ios`||e===`android`)return e}function Ha(e,t){return{platform:t,metroHost:yt(e?.metroHost),metroPort:Ra(e?.metroPort),bundleUrl:yt(e?.bundleUrl),launchUrl:yt(e?.launchUrl)}}function Ua(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Wa(e){if(ea(e))return`10.0.2.2`;if(U(e))return`127.0.0.1`}function Ga(e,t){if(!e||yt(e.metroHost)||yt(e.bundleUrl)||e.metroPort===void 0)return e;let n=Wa(t);return n?{...e,metroHost:n}:e}function Ka(e){let{runtime:t,sessionName:r,platform:i}=e;if(t===void 0)return;if(!t||typeof t!=`object`||Array.isArray(t))throw new n(`INVALID_ARGS`,`open runtime must be an object.`);let a=t,o=Object.keys(a).find(e=>!Fa.includes(e));if(o)throw new n(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Fa.join(`, `)}.`);return{platform:Ba(a.platform,r,i),metroHost:La(a.metroHost,`metroHost`),metroPort:za(a.metroPort),bundleUrl:La(a.bundleUrl,`bundleUrl`),launchUrl:La(a.launchUrl,`launchUrl`)}}function qa(e,t,n){if(n){if(Ia(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Ja(e,t,r,i){let a=e.getRuntimeHints(t);if(!a)return;let o=r?j(r):void 0,s=Va(o)??i;if(a.platform&&r&&!s)throw new n(`INVALID_ARGS`,`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new n(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Ya(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?Va(j(i)):e.platform,o=n.getRuntimeHints(r),s=Ka({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=Ja(n,r,i,a);return{runtime:i?Ga(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&Ia(s)>0?s:void 0;return{runtime:i?Ga(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Xa(e){return Ya(e).runtime}function Za(e){try{return{ok:!0,data:Ya(e)}}catch(e){let t=s(e);return L(t.code,t.message,t.details)}}async function Qa(e){let{replacedStoredRuntime:t,previousRuntime:n,runtime:r,session:i}=e;!t||!i?.appBundleId||!fa(n)||fa(r)||await ma({device:i.device,appId:i.appBundleId})}async function $a(e){let{req:t,sessionName:n,sessionStore:r}=e,i=(t.positionals?.[0]??`show`).toLowerCase();if(i===`port-reverse`)return await ao(t);if(!eo(i))return L(`INVALID_ARGS`,`runtime requires set, show, clear, or port-reverse`);let a=r.get(n),o=r.getRuntimeHints(n);return i===`clear`?await to(n,r,a,o):i===`show`?no(n,o):io({req:t,sessionName:n,sessionStore:r,session:a,current:o})}function eo(e){return e===`set`||e===`show`||e===`clear`}async function to(e,t,n,r){return fa(r)&&n?.appBundleId&&await ma({device:n.device,appId:n.appBundleId}),{ok:!0,data:{session:e,cleared:t.clearRuntimeHints(e)}}}function no(e,t){return{ok:!0,data:{session:e,configured:!!t,runtime:t}}}function ro(e){return e?j(e.device):void 0}function io(e){let{req:t,sessionName:n,sessionStore:r,session:i,current:a}=e,o=ro(i),s=Va(t.flags?.platform??a?.platform??o);if(!s)return L(`INVALID_ARGS`,`runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.`);if(o!==void 0&&o!==s)return L(`INVALID_ARGS`,`runtime set targets ${s}, but session "${n}" is already bound to ${o}.`);let c=Ua(a,Ha(t.flags,s));return Ia(c)===0?L(`INVALID_ARGS`,`runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url.`):(r.setRuntimeHints(n,c),{ok:!0,data:{session:n,configured:!0,runtime:c}})}async function ao(e){let t=oo(e);if(!t.ok)return t.response;let n=await hn(t.options);return n?{ok:!0,data:{action:`port-reverse`,...n}}:L(`UNSUPPORTED_OPERATION`,`No active provider device runtime supports port reverse for this lease.`)}function oo(e){let t=so(e);if(!t.ok)return t;let n=co(e);if(!n.ok)return n;let r=e.flags?.portReverseName?.trim()||`runtime`;return{ok:!0,options:{leaseId:t.leaseId,provider:t.provider,devicePort:n.devicePort,hostPort:n.hostPort,name:r}}}function so(e){let t=e.flags?.leaseId,n=e.flags?.leaseProvider;return t?n?{ok:!0,leaseId:t,provider:n}:{ok:!1,response:L(`INVALID_ARGS`,`runtime port-reverse requires a lease provider.`)}:{ok:!1,response:L(`INVALID_ARGS`,`runtime port-reverse requires a resolved remote lease.`)}}function co(e){let t=lo(e.flags?.devicePort),n=lo(e.flags?.hostPort??e.flags?.devicePort);return!t||!n?{ok:!1,response:L(`INVALID_ARGS`,`runtime port-reverse requires numeric devicePort and hostPort values from 1 to 65535.`)}:{ok:!0,devicePort:t,hostPort:n}}function lo(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<1||e>65535))return e}const uo=`open-command-roundtrip`,fo=`Not implemented for this platform in this release.`;function po(e){let{sessionName:t,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a,appName:o,appBundleId:s,surface:c,startup:l,timing:u,device:d,runtime:f,runtimeHintCount:p,sessionReused:m}=e,h={session:t,surface:c,sessionStateDir:n,runnerLogPath:r,requestLogPath:i,eventLogPath:a,sessionReused:m};return o&&(h.appName=o),s&&(h.appBundleId=s),l&&(h.startup=l),u&&(h.timing=u),f&&p(f)>0&&(h.runtime=f),d&&(h.platform=j(d),h.target=d.target??`mobile`,h.device=d.name,h.id=d.id,h.kind=d.kind,Je(d.platform)&&(h.serial=d.id)),d&&N(d)&&(h.device_udid=d.id,h.ios_simulator_device_set=d.simulatorSetPath??null),{...h,...ve(`Opened: ${o??s??t}`)}}function mo(e){let{existingSession:t,sessionName:n,sessionScope:r,device:i,surface:a,appBundleId:o,appName:s,saveScript:c}=e;return t?{...t,device:i,surface:a,appBundleId:o,appName:s,recordSession:t.recordSession||c,snapshot:void 0}:{name:n,sessionScope:r,device:i,createdAt:Date.now(),surface:a,appBundleId:o,appName:s,recordSession:c,actions:[]}}const ho=new Set([`app`,`desktop`,`frontmost-app`]);function go(e,t,r){if(e.platform===`linux`){if(!t)return`app`;let e=me(t);if(!ho.has(e))throw new n(`INVALID_ARGS`,`Linux supports --surface app, desktop, and frontmost-app (got "${t}")`);if(e!==`app`&&r)throw new n(`INVALID_ARGS`,`open --surface ${e} does not accept an app target`);return e}if(!A(e)){if(t)throw new n(`INVALID_ARGS`,`surface is only supported on macOS and Linux`);return`app`}let i=t?me(t):`app`;if(i!==`app`&&i!==`menubar`&&r)throw new n(`INVALID_ARGS`,`open --surface ${i} does not accept an app target`);return i}function _o(e){let{device:t,surfaceFlag:n,openTarget:r,existingSurface:i}=e;return(A(t)||t.platform===`linux`)&&!n?i??`app`:go(t,n,r)}async function vo(e){if(e===`app`||e===`desktop`||e===`menubar`)return{};let t=await Sn();return{appBundleId:t.bundleId,appName:t.appName}}async function yo(e,t,n){if(!(!M(e.platform)||!t))return Nt(t)?A(e)?void 0:e.kind===`device`?Mt(n,t):Pt(t)?void 0:n??await bo(e,t):await xo(e,t)}async function bo(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:n}=await import(`./apps.js`).then(e=>e.t);return await n(e,t)}catch{return}}async function xo(e,t){try{let{resolveIosApp:n}=await import(`./apps.js`).then(e=>e.t);return await n(e,t)}catch{return}}async function So(e,t){if(!(e.platform!==`android`||!t||Nt(t)))try{let{resolveAndroidApp:n}=await import(`./app-lifecycle.js`).then(e=>e.t),r=await n(e,t);return r.type===`package`?r.value:void 0}catch{return}}async function Co(e,t,n){if(n||e.platform!==`android`||!t||!Nt(t))return n;try{let{getAndroidAppState:t}=await import(`./app-lifecycle.js`).then(e=>e.t);return(await t(e)).package?.trim()||n}catch{return n}}function wo(e,t){return e.platform===`android`&&!!(t&&Nt(t))}async function To(e,t,n,r){return N(e)&&F(e)?n:await yo(e,t,n)??await r(e,t)??(wo(e,t)?n:void 0)}function Eo(e){let{openPositionals:t,runtime:n,flags:r,foldRuntimeLaunchUrl:i}=e,a=n?.launchUrl;if(!a||t.length!==1)return{openPositionals:t};let o=t[0]?.trim();if(!o||Nt(o))return{openPositionals:t};let s=r?.clearAppState===!0||!!r?.launchConsole?.trim()||!!r?.launchArgs?.length;return i&&!s?{openPositionals:[o,a]}:{openPositionals:t,followUpLaunchUrl:a}}async function Do(e){let{launchUrl:t,device:n,req:r,logPath:i,appBundleId:a,traceLogPath:o}=e,s=R(i,r.flags?{...r.flags,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}:void 0,a,o);await fn(n,`open`,[t],r.flags?.out,s)}function Oo(e){return L(`INVALID_ARGS`,e)}function ko(e,t,r,i){try{return _o({device:e,surfaceFlag:t,openTarget:r,existingSurface:i})}catch(e){return L(e instanceof n?e.code:`INVALID_ARGS`,String(e.message))}}function Ao(e){let{shouldRelaunch:t,openTarget:n,surface:r,device:i}=e;return t?n&&Nt(n)?Oo(`open --relaunch does not support URL targets.`):r===`app`?i.platform===`android`&&n&&Ot(n)===`binary`?Oo(kt(n)):null:Oo(`open --relaunch is supported only for app surfaces.`):null}function jo(e){let{shouldRelaunch:t,openTarget:n,platform:r}=e;return t?n&&Nt(n)?Oo(`open --relaunch does not support URL targets.`):r===`android`&&n&&Ot(n)===`binary`?Oo(kt(n)):null:null}async function Mo(e){let{req:t,sessionName:n,sessionStore:r,device:i,surface:a,openTarget:o,existingSession:s,onIosSimulatorColdBootStart:c}=e;await z(i,{deviceHub:t.flags?.deviceHub===!0,onIosSimulatorColdBootStart:c});let{appBundleId:l,appName:u}=await No({device:i,surface:a,openTarget:o,existingAppBundleId:s?.appBundleId}),d=Za({req:t,sessionStore:r,sessionName:n,device:i});if(!d.ok)return{type:`response`,response:d};if(s){let{runtime:e,previousRuntime:t,replacedStoredRuntime:n}=d.data;await Qa({replacedStoredRuntime:n,previousRuntime:t,runtime:e,session:s})}return{type:`details`,details:{appBundleId:l,appName:u,runtime:d.data.runtime}}}async function No(e){let{device:t,surface:n,openTarget:r,existingAppBundleId:i}=e,a=await vo(n);return{appBundleId:a.appBundleId??await To(t,r,i,So),appName:a.appName??r}}const Po=new Map;function Fo(e){return e.internal?.resolvedSessionScope??Mr(e)}function Io(e){let{session:t,existingSession:n,saveScriptRequested:r,responseData:i}=e;if(!n&&r){t.scriptRecordingState=`armed`,t.recordSession=!0;return}n?.scriptRecordingState===`armed`&&(t.scriptRecordingState=`aborted`,t.recordSession=!1,i.warnings=[...Array.isArray(i.warnings)?i.warnings.filter(e=>typeof e==`string`):[],`Script publication was aborted because this session completed a second open. Start a fresh session with open --save-script to author another script.`])}async function Lo(e){let{device:t,closeTarget:n,outFlag:r,context:i}=e;M(t.platform)&&!U(t)&&await En(t.id),await fn(t,`close`,[n],r,i),await na(t,300)}function Ro(e,t){if(e.platform!==`android`)return!1;let n=t.flags?.testIme;return n===void 0?e.kind===`emulator`:n}async function zo(e,t,n){if(Ro(e,t))try{await Vt(e,{stateDir:n})}catch(t){d({level:`warn`,phase:`android_test_ime_activate_failed`,data:{device:e.id,error:t instanceof Error?t.message:String(t)}})}}function Bo(e,t,n){return{durationMs:Math.max(0,Date.now()-e),measuredAt:new Date().toISOString(),method:uo,appTarget:t,appBundleId:n}}function Vo(e){return!(!e.shouldRelaunch||!e.openTarget||e.collapseSimulatorRelaunch||!e.existingSession&&F(e.device))}async function Ho(e){let{req:t,sessionName:n,sessionStore:r,logPath:i,device:a,openTarget:o,openPositionals:s,appName:c,surface:u,appBundleId:f,runtime:p,existingSession:m,deviceClaim:h}=e,g=t.flags?.relaunch===!0,_=m?.trace?.outPath,v=f,y=Date.now(),b={},x=U(a)&&!F(a),S=N(a)&&!F(a)&&u===`app`&&s.length>0&&!!v,C=wr({req:t,logPath:i,appBundleId:v,traceLogPath:_}),ee=t.flags?.maestro?.prewarmRunnerBeforeOpen===!0,w,T=!1,te=!1,E=(e=C)=>{T=!0,b.runnerPrewarmKind=`session`,b.runnerPrewarmScheduled=!0,w=Tn(a,e)},ne=async()=>{if(!w||te)return;te=!0;let e=Date.now();await w,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)};S&&x&&!ee&&E();let re=Eo({openPositionals:s,runtime:p,flags:t.flags,foldRuntimeLaunchUrl:x}),D=g&&x&&t.flags?.clearAppState!==!0;if(Vo({shouldRelaunch:g,openTarget:o,collapseSimulatorRelaunch:D,device:a,existingSession:m})&&o){m&&Vn(m);let e=v??o,n=Date.now();await Lo({device:a,closeTarget:e,outFlag:t.flags?.out,context:{...R(i,t.flags,v??m?.appBundleId,_)}}),b.relaunchCloseDurationMs=Math.max(0,Date.now()-n)}let ie=Date.now();await pa({device:a,appId:v,runtime:p}),b.runtimeHintsDurationMs=Math.max(0,Date.now()-ie),S&&ee&&(E({...C,propagateError:!0}),await ne());let ae=te,oe=Date.now(),se=await Uo({req:t,sessionName:n,sessionStore:r,device:a,surface:u,sessionAppBundleId:v,appName:c,existingSession:m});if(se.type===`response`)return se.response;let ce=se.session??m;ce&&Vn(ce),await fn(a,`open`,re.openPositionals,t.flags?.out,{...R(i,t.flags,v),...D?{terminateRunningApp:!0}:{}}),b.openDispatchDurationMs=Math.max(0,Date.now()-oe),await zo(a,t,r.resolveDaemonStateDir());let le=Date.now();re.followUpLaunchUrl&&await Do({launchUrl:re.followUpLaunchUrl,device:a,req:t,logPath:i,appBundleId:v,traceLogPath:_}),b.launchUrlDurationMs=Math.max(0,Date.now()-le),S&&!T&&E(),g?await ne():w&&!te&&(b.runnerPrewarmWaited=!1),x&&(g||ae)&&await An(a,C),v=await Co(a,o,v),a.platform===`android`&&v&&await Gn(a,v);let ue=o?Bo(oe,o,v):void 0,de=Date.now();if(await na(a,300),b.postOpenSettleDurationMs=Math.max(0,Date.now()-de),Qt(t.meta?.requestId)){let e=en();return L(e.code,e.message,e.details)}m&&fr(m,`open`,m.snapshot);let fe=mo({existingSession:ce,sessionName:m?.name??Ar(t),sessionScope:m?.sessionScope??Fo(t),device:a,surface:u,appBundleId:v,appName:c,saveScript:!!t.flags?.saveScript});fe.lease=Pn({req:t,existingLease:m?.lease}),h&&(fe.deviceClaim=h),t.runtime!==void 0&&qa(r,n,p);let pe=r.ensureSessionDir(n),me=Te(pe,t.meta?.requestId??l().requestId);b.totalDurationMs=Math.max(0,Date.now()-y),d({level:`info`,phase:`open_timing`,durationMs:b.totalDurationMs,data:b});let O=po({sessionName:fe.name,sessionStateDir:pe,runnerLogPath:Fe(pe),requestLogPath:me,eventLogPath:r.resolveEventLogPath(n),appName:c,appBundleId:v,surface:u,startup:ue,timing:b,device:a,runtime:p,runtimeHintCount:Ia,sessionReused:m!==void 0});return Io({session:fe,existingSession:m,saveScriptRequested:!!t.flags?.saveScript,responseData:O}),r.set(n,fe),r.recordAction(fe,{command:`open`,positionals:s,flags:t.flags??{},runtime:t.runtime===void 0?void 0:p,result:O}),{ok:!0,data:O}}async function Uo(e){let{req:t,sessionName:n,sessionStore:r,device:i,surface:a,sessionAppBundleId:o,appName:s,existingSession:c}=e,l=t.internal?.openLifecycle?.beforeDispatch;if(!l)return{type:`session`,session:c};let u=mo({existingSession:c,sessionName:c?.name??Ar(t),sessionScope:c?.sessionScope??Fo(t),device:i,surface:a,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});u.lease=Pn({req:t,existingLease:c?.lease}),r.set(n,u);let d=await l(u);return d&&!d.ok?{type:`response`,response:d}:{type:`session`,session:r.get(n)??u}}function Wo(e){let{req:t,device:n,sessionStore:r}=e,i=r.toArray().find(e=>e.device.id===n.id);if(i)return Ur(t,i)?L(`DEVICE_IN_USE`,`Device is already in use by another workspace session.`,{deviceId:n.id,deviceName:n.name,hint:`Use a different device selector, wait for the other workspace to close its session, or run agent-device devices to choose another target.`}):Go(i,n)}function Go(e,t){return L(`DEVICE_IN_USE`,`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:t.id,deviceName:t.name,hint:xr(e,`device-in-use`)})}async function Ko(e){let{req:t,device:n,sessionName:r,logPath:i}=e;return $r(t.meta,F(n))?await ai({device:n,session:r,workspace:t.meta?.cwd??process.cwd(),stateDir:H.dirname(i)}):{}}async function qo(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,device:a,surface:o,openTarget:s}=e,c=Wo({req:t,device:a,sessionStore:i});if(c)return c;let l=await Ko({req:t,device:a,sessionName:n,logPath:r}),u={mayHaveStarted:!1};try{let e=await Mo({req:t,sessionName:n,sessionStore:i,device:a,surface:o,openTarget:s,onIosSimulatorColdBootStart:Or({req:t,logPath:r,device:a,surface:o,openTarget:s})});if(e.type===`response`)return await Jo(l.ownership,u),e.response;u.mayHaveStarted=!0;let c=await Ho({req:t,sessionName:n,sessionStore:i,logPath:r,device:a,openTarget:s,openPositionals:t.positionals??[],appBundleId:e.details.appBundleId,appName:e.details.appName,runtime:e.details.runtime,surface:o,deviceClaim:l.ownership});return c.ok||await Jo(l.ownership,u),c}catch(e){throw await Jo(l.ownership,u),e}}async function Jo(e,t){if(e){if(t.mayHaveStarted){d({level:`warn`,phase:`device_claim_open_effects_unconfirmed`,data:{deviceKey:e.deviceKey}});return}await Gr(e)}}async function Yo(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=i.get(n);if(a){if(t.flags?.saveScript)return L(`INVALID_ARGS`,`open --save-script can only arm a fresh session. Use the current session without --save-script, or close it and start a fresh session.`);let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?a.appName:void 0),c=ko(a.device,t.flags?.surface,s,a.surface);if(typeof c!=`string`)return c;if(!s&&c===`app`)return Oo(e?`open --relaunch requires an app name or an active session app.`:`Session already active. Close it first or pass a new --session name.`);let l=Ao({shouldRelaunch:e,openTarget:s,surface:c,device:a.device});if(l)return l;let u=await ra(a.device);await t.internal?.retainDeviceExecutionLock?.(u.id);let d=await Mo({req:t,sessionName:n,sessionStore:i,device:u,surface:c,openTarget:s,existingSession:a,onIosSimulatorColdBootStart:Or({req:t,logPath:r,device:u,surface:c,openTarget:s,traceLogPath:a.trace?.outPath})});return d.type===`response`?d.response:await Ho({req:t,sessionName:n,sessionStore:i,logPath:r,device:u,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:d.details.appBundleId,appName:d.details.appName,runtime:d.details.runtime,surface:c,existingSession:a})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return Oo(`open --relaunch requires an app argument.`);let c=jo({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform===`android`?`android`:void 0});if(c)return c;let l=await cn(t.flags??{},Xr(s));await t.internal?.retainDeviceExecutionLock?.(l.id);let u=ko(l,t.flags?.surface,s);return typeof u==`string`?Ao({shouldRelaunch:o,openTarget:s,surface:u,device:l})||await nn(Po,l.id,async()=>await qo({req:t,sessionName:n,logPath:r,sessionStore:i,device:l,surface:u,openTarget:s})):u}function Xo(e){return U(e)||ea(e)}async function Zo(t){if(t.booted===!1)return{success:!0,exitCode:0,stdout:``,stderr:``};try{return U(t)?await Qo(t):await es(t)}catch(t){let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}async function Qo(e){let t=await xi(e);return t.success?t:await $o(e)===`Shutdown`?{...t,success:!0,exitCode:0}:t}async function $o(e){try{return await Si(e)}catch{return null}}async function es(e){let t=await jt(e,[`emu`,`kill`],{allowFailure:!0,timeoutMs:15e3});return{success:t.exitCode===0,exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr}}function ts(e,t){return!!(e.flags?.force||t.saveScriptForce)}function ns(e,t,n){if(t.saveScriptBoundary===void 0)return{kind:`not-armed`};let r=t.actions.length;jr(e,t,n,`close`,{session:t.name,...ve(`Closed: ${t.name}`)});let i=e.writeSessionLog(t,{force:ts(n,t)});return i.written?{kind:`committed`,path:i.path}:i.error?(t.actions.length=r,{kind:`failed`,error:i.error}):t.saveScriptComplete?{kind:`committed`}:{kind:`aborted`}}function rs(t,n){let r=e(n);return{ok:!1,error:{...r,details:{...r.details,session:t.name,...t.saveScriptPath?{savedScript:t.saveScriptPath}:{}},retriable:!0}}}function is(e){let{req:t,session:n,sessionStore:r,platformCloseError:i}=e;i||jr(r,n,t,`close`,{session:n.name,...ve(`Closed: ${n.name}`)}),t.flags?.saveScript&&(n.recordSession=!0);try{r.writeSessionLog(n,{force:ts(t,n)});return}catch(e){return as(e)}}function as(t){let r={hint:`Remove the existing target (or pass --force/--overwrite), then re-record with open --save-script.`,retriable:!1};return t instanceof n?new n(`COMMAND_FAILED`,`The session was closed, but its script was not saved: ${t.message}`,{...t.details,...r},t.cause):new n(`COMMAND_FAILED`,`The session was closed, but its script was not saved: ${e(t).message}`,r)}async function os(e){let{device:t,shutdownRequested:n}=e;if(n&&!F(t)&&Xo(t))return await Zo(t)}function ss(e,t){return U(t.device)&&!e.flags?.shutdown&&!t.recording&&!t.lease&&!t.device.simulatorSetPath}function cs(e){return M(e.device.platform)&&!U(e.device)}function ls(e){return e instanceof n?e:new n(`COMMAND_FAILED`,`The platform close failed: ${e instanceof Error?e.message:String(e)}`,{hint:`The repair transaction was not committed because the platform close failed; fix the underlying issue and retry close --save-script.`})}async function us(e){let{req:t,session:n,sessionName:r,logPath:i,sessionStore:a,cleanupFailures:o,repairArmed:s}=e,c=async(e,t)=>{try{await t()}catch(t){o.push({step:e,error:t})}},l=ss(t,n);await ds(n,a,c);let u=s?void 0:await hs({req:t,session:n,logPath:i});await _s(l,n,c),await gs(n,a,r);let d=s?void 0:is({req:t,session:n,sessionStore:a,platformCloseError:u});return await c(`materialized_paths`,()=>br(r)),{platformCloseError:u,saveScriptError:d}}async function ds(e,t,n){await n(`recording`,()=>Br(e)),await n(`app_log`,()=>qr(e)),await n(`audio_probe`,async()=>{await li(e,`session-close`)}),await n(`apple_perf`,()=>ti(e)),await n(`android_native_perf`,()=>Nr(e)),await n(`android_snapshot_helper`,()=>vr(e)),await n(`android_ime`,()=>Wr(e,t.resolveDaemonStateDir()))}function fs(e){return JSON.stringify(e.positionals??[])}async function ps(e){let{req:t,session:n,logPath:r,sessionStore:i}=e,a=n.saveScriptBoundary!==void 0,o=fs(t);if(a&&n.repairPlatformCloseReceipt!==o){let e=await hs({req:t,session:n,logPath:r});if(e)return{response:rs(n,ls(e))};n.repairPlatformCloseReceipt=o}let s=ns(i,n,t);return s.kind===`failed`?{response:rs(n,s.error)}:(n.repairPlatformCloseReceipt=void 0,{repairArmed:a,...s.kind===`committed`&&s.path?{healedScriptPath:s.path}:{},...s.kind===`aborted`?{aborted:!0}:{}})}async function ms(t){try{return{providerData:await tr(t)}}catch(n){let r=e(n);return{response:{ok:!1,error:{...r,hint:`The provider device could not be released. Retry close after the provider is reachable.`,details:{...r.details,session:t.session.name},retriable:!0}}}}}async function hs(e){let{req:t,session:n,logPath:r}=e;if(Cs(t,n)){if(cs(n))try{await Qr(n)}catch(e){return e}try{Vn(n),await fn(n.device,`close`,t.positionals??[],t.flags?.out,{...R(r,t.flags,n.appBundleId,n.trace?.outPath)}),await na(n.device,300);return}catch(e){return e}}}async function gs(e,t,n){!fa(t.getRuntimeHints(n))||!e.appBundleId||await ma({device:e.device,appId:e.appBundleId}).catch(()=>{})}async function _s(e,t,n){if(M(t.device.platform)){if(!e){await n(`apple_runner`,()=>Qr(t));return}d({level:`debug`,phase:`ios_runner_retained_after_close`,data:{session:t.name,deviceId:t.device.id}}),wn(t.device.id)}}function vs(e,t){if(e.flags?.saveScript&&!(t.scriptRecordingState!==`aborted`&&t.scriptRecordingState!==`published`))throw new n(`INVALID_ARGS`,`close --save-script cannot ${t.scriptRecordingState===`published`?`re-publish`:`publish`} this terminal recording. Retry with plain close; it will tear down the session without writing.`)}async function ys(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o}=e,s=i.get(n);if(!s)return await Ts(t,r);if(vs(t,s),t.internal?.closeAppOnly===!0)return await Ss({req:t,session:s,logPath:r});let c=await ps({req:t,session:s,logPath:r,sessionStore:i});if(`response`in c)return c.response;let l=await bs({req:t,session:s,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o,repairArmed:c.repairArmed});if(l.kind===`response`)return l.response;let u=await os({device:s.device,shutdownRequested:t.flags?.shutdown});return xs({session:s,repair:c,requestedSaveScript:!!t.flags?.saveScript,shutdownResult:u,providerData:l.providerData})}async function bs(e){let{req:t,session:n,sessionName:r,logPath:i,sessionStore:a,leaseRegistry:o,leaseLifecycleProvider:s}=e,c=[],{platformCloseError:l,saveScriptError:u}=await us({req:t,session:n,sessionName:r,logPath:i,sessionStore:a,cleanupFailures:c,repairArmed:e.repairArmed}),d=await ms({session:n,leaseRegistry:o,leaseLifecycleProvider:s});if(d.response)return{kind:`response`,response:d.response};let f=ii({sessionName:r,phase:`session_close_cleanup_failed`,failures:c}),p=l??f;if(p||await Gr(n.deviceClaim),a.delete(r),p)throw p;if(u)throw u;return{kind:`closed`,providerData:d.providerData}}function xs(e){let{session:t,repair:n,requestedSaveScript:r,shutdownResult:i,providerData:a}=e;if(n.aborted&&r)return{ok:!1,error:{code:`COMMAND_FAILED`,message:`The repair was aborted and no script was written.`,hint:`Recovery: replay --from <n> --plan-digest <digest> before closing.`,details:{session:t.name}}};let o=n.healedScriptPath?{savedScript:n.healedScriptPath}:{},s=a?{provider:a}:{},c=`Closed: ${t.name}`;return i?{ok:!0,data:Se({session:t.name,shutdown:i,...o,...s},c)}:{ok:!0,data:{session:t.name,...ve(c),...o,...s}}}async function Ss(e){let{req:t,session:n,logPath:r}=e,i=t.positionals?.[0];if(!i)return L(`INVALID_ARGS`,`App-only close requires an app target`);let a=await hs({req:t,session:n,logPath:r});if(a)throw a;return{ok:!0,data:{app:i,...ve(`Closed: ${i}`)}}}function Cs(e,t){return ws(e)||t.device.platform===`web`}function ws(e){return(e.positionals?.length??0)>0}async function Ts(e,t){if(!e.positionals||e.positionals.length===0)return L(`SESSION_NOT_FOUND`,`No active session`);let n=await G({session:void 0,flags:e.flags,ensureReady:!0});return await fn(n,`close`,e.positionals,e.flags?.out,{...R(t,e.flags)}),await na(n,300),{ok:!0,data:{app:e.positionals[0],...ve(`Closed: ${e.positionals[0]}`)}}}const Es={ios:async(e,t,n)=>{let r=await mn(e,t,n,{relaunch:!0,appIdentifierHint:t});if(r)return{bundleId:r.bundleId??r.launchTarget??t};let{reinstallIosApp:i}=await import(`./apps.js`).then(e=>e.t);return await i(e,t,n)},android:async(e,t,n)=>{let r=await mn(e,t,n,{relaunch:!0,packageNameHint:t});if(r)return{package:r.packageName??r.launchTarget??t};let{reinstallAndroidApp:i}=await import(`./app-lifecycle.js`).then(e=>e.t);return await i(e,t,n)}},Ds={ios:async(e,t,n)=>{let r=await mn(e,t,n,{appIdentifierHint:t});if(r)return{bundleId:r.bundleId,appName:r.appName,launchTarget:r.launchTarget};let{installIosApp:i}=await import(`./apps.js`).then(e=>e.t),a=await i(e,n,{appIdentifierHint:t});return{bundleId:a.bundleId,appName:a.appName,launchTarget:a.launchTarget}},android:async(e,t,n)=>{let r=await mn(e,t,n,{packageNameHint:t});if(r)return{package:r.packageName,appName:r.appName,launchTarget:r.launchTarget};let{installAndroidApp:i}=await import(`./app-lifecycle.js`).then(e=>e.t),a=await i(e,n);return{package:a.packageName,appName:a.appName,launchTarget:a.launchTarget}}};async function Os(e){let{req:t,command:n,sessionName:r,sessionStore:i,deployOps:a}=e,o=i.get(r),s=t.flags??{},c=W(n,o,s);if(c)return c;let l=Ms(n,t.positionals??[]);if(!l.ok)return l.response;let{app:u,appPathInput:d}=l,f=t.meta?.uploadedArtifactId;try{let e=f?ni(f,t.meta?.tenantId):k.expandHome(d);if(!V.existsSync(e))return L(`INVALID_ARGS`,`App binary not found: ${e}`);let r=await G({session:o,flags:s,ensureReady:!1}),c=I(n,r);if(c)return c;o&&Vn(o);let l=N(r)?As(u,e,await a.ios(r,u,e)):js(u,e,await a.android(r,u,e)),p=Se(l,ks(l));return jr(i,o,t,n,p),{ok:!0,data:p}}finally{f&&yr(f)}}function ks(e){return`Installed: ${e.appName??ge(e)}`}function As(e,t,n){let r=n.bundleId;return{app:e||r||n.launchTarget||t,appPath:t,platform:`ios`,...r?{appId:r,bundleId:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function js(e,t,n){let r=n.package;return{app:e||r||n.launchTarget||t,appPath:t,platform:`android`,...r?{appId:r,package:r,packageName:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function Ms(e,t){let n=t[0]?.trim(),r=t[1]?.trim();if(e===`install`){let e=r??n;return e?{ok:!0,app:r?n??``:``,appPathInput:e}:{ok:!1,response:L(`INVALID_ARGS`,`install requires: install <path-to-app-binary>`)}}return!n||!r?{ok:!1,response:L(`INVALID_ARGS`,`reinstall requires: reinstall <app> <path-to-app-binary>`)}:{ok:!0,app:n,appPathInput:r}}async function Ns(e,t,n){return await C(e,t,n)}async function Ps(e){let{req:t,sessionName:n,sessionStore:r}=e;if(t.command===`session_list`){let e=Mr(t);return{ok:!0,data:{sessions:r.toArray().filter(t=>_r(t,e)).map(e=>{let t=r.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:Fe(t),platform:j(e.device),...M(e.device.platform)&&e.device.appleOs?{appleOs:e.device.appleOs}:{},target:e.device.target??`mobile`,surface:e.surface??`app`,device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,...M(e.device.platform)&&!A(e.device)&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if(t.command===`devices`)try{let e=Ft(t.flags?.androidDeviceAllowlist),n=t.flags?.platform,r=qe({simulatorSetPath:It(t.flags?.iosSimulatorDeviceSet),platform:n,target:t.flags?.target}),i=await ln({platform:n,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:r,androidSerialAllowlist:e?Array.from(e).sort():void 0}),a=n?i.filter(e=>Is(e,n)):i;return{ok:!0,data:{devices:(t.flags?.target?a.filter(e=>(e.target??`mobile`)===t.flags?.target):a).map(Fs)}}}catch(e){let t=s(e);return L(t.code,t.message,t.details)}if(t.command===`capabilities`){let e=r.get(n),i=t.flags??{},a=W(t.command,e,i);if(a)return a;let o=await G({session:e,flags:i,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0});return{ok:!0,data:{device:Fs(o),availableCommands:sn().filter(e=>pn(e,o))}}}if(t.command===`apps`){let e=r.get(n),i=t.flags??{},a=W(t.command,e,i);if(a)return a;let o=await G({session:e,flags:i,ensureReady:!0}),s=I(`apps`,o);if(s)return s;let c=Et(t.flags?.appsFilter);return M(o.platform)?{ok:!0,data:{apps:(await Ci(o,c)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await At(o,c)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}function Fs({simulatorSetPath:e,iosPhysicalDeviceBackend:t,appleOs:n,...r}){return{...r,platform:j({platform:r.platform,appleOs:n}),...M(r.platform)&&n?{appleOs:n}:{}}}function Is(e,t){return Xe(e,t)}async function Ls(e){let{ensureAndroidEmulatorBooted:t}=await import(`./install-artifact.js`).then(e=>e.o);return await t(e)}const Rs=`iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).`,zs=`macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").`;async function Bs(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),a=t.flags??{},o=a.platform;if(!i&&ta(a))return L(`SESSION_NOT_FOUND`,o===`ios`?`No active session "${n}". Run open with --session ${n} first.`:`No active session "${n}". Run open with --session ${n} first, or omit --session to query by device selector.`);let s=W(`appstate`,i,a);if(s)return s;let c=M(i?.device.platform)&&aa(a,i),l=o===`ios`,u=o===`macos`;if(l&&!c)return L(`SESSION_NOT_FOUND`,Rs);if(u&&!c)return L(`SESSION_NOT_FOUND`,zs);if(c&&i){let e=i.appName??i.appBundleId;return!i.appName&&!i.appBundleId?A(i.device)&&i.surface&&i.surface!==`app`&&i.surface!==`frontmost-app`?{ok:!0,data:{platform:j(i.device),appName:i.surface,appBundleId:i.appBundleId,source:`session`,surface:i.surface}}:L(`COMMAND_FAILED`,`No foreground app is tracked for this ${A(i.device)?`macOS`:`iOS`} session. Open an app in the session, then retry appstate.`):{ok:!0,data:{platform:j(i.device),appName:e??`unknown`,appBundleId:i.appBundleId,source:`session`,surface:i.surface??`app`,...N(i.device)?{device_udid:i.device.id,ios_simulator_device_set:i.device.simulatorSetPath??null}:{}}}}let d=await G({session:i,flags:a,ensureReady:!0});if(N(d))return L(`SESSION_NOT_FOUND`,Rs);if(A(d))return L(`SESSION_NOT_FOUND`,zs);if(d.platform===`web`)return L(`UNSUPPORTED_OPERATION`,`appstate is not supported on web.`);let{getAndroidAppState:f}=await import(`./app-lifecycle.js`).then(e=>e.t),p=await f(d);return{ok:!0,data:{platform:`android`,package:p.package,activity:p.activity}}}async function Vs(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e;if(t.command===`boot`){let e=i.get(n),a=t.flags??{},o=W(t.command,e,a);if(o)return o;let c=(a.platform??e?.device.platform)===`android`,l=a.headless===!0;if(l&&!c)return L(`INVALID_ARGS`,`boot --headless is supported only for Android emulators.`);let u=ia({flags:a,sessionDevice:e?.device}),d=c&&!!u,f,p=!1;try{f=await G({session:e,flags:a,ensureReady:!1,allowStoppedAndroidAvdPlaceholders:!0})}catch(e){let t=s(e);if(c&&l&&!u&&t.code===`DEVICE_NOT_FOUND`)return L(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`);if(!d||t.code!==`DEVICE_NOT_FOUND`||!u)throw e;f=await Ls({avdName:u,serial:a.serial,headless:l}),p=!0}if(a.target&&(f.target??`mobile`)!==a.target)return L(`DEVICE_NOT_FOUND`,`No ${f.platform} device found matching --target ${a.target}.`);if(c&&l){if(f.platform!==`android`||f.kind!==`emulator`)return L(`INVALID_ARGS`,`boot --headless is supported only for Android emulators.`);if(!p){let t=ia({flags:a,sessionDevice:e?.device,resolvedDevice:f});if(!t)return L(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`);f=await Ls({avdName:t,serial:a.serial,headless:!0})}await z(f)}else f.platform===`android`&&f.kind===`emulator`&&f.booted!==!0?(f=await Ls({avdName:f.name,serial:a.serial,headless:!1}),await z(f)):(f.platform!==`android`||f.booted!==!0)&&await z(f,{onIosSimulatorColdBootStart:Yr({req:t,logPath:r,device:f,enabled:!0})});return I(`boot`,f)||(N(f)&&f.kind===`simulator`&&On(f,{}),{ok:!0,data:{platform:j(f),target:f.target??`mobile`,device:f.name,id:f.id,kind:f.kind,booted:!0,...M(f.platform)&&f.appleOs?{appleOs:f.appleOs}:{}}})}if(t.command===`shutdown`){let e=i.get(n),r=t.flags??{},a=W(t.command,e,r);if(a)return a;let o=await G({ensureReady:!1,flags:r,session:e}),s=I(`shutdown`,o,{message:`shutdown is supported only for Apple simulators and Android emulators.`});if(s)return s;if(e&&e.device.platform===o.platform&&e.device.id===o.id)return L(`DEVICE_IN_USE`,`Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.`,{hint:`Run agent-device close --shutdown --session ${n}`,session:n,platform:j(o),target:o.target??`mobile`,device:o.name,id:o.id,kind:o.kind});let c=await Zo(o);return c.success?{ok:!0,data:{platform:j(o),target:o.target??`mobile`,device:o.name,id:o.id,kind:o.kind,shutdown:c,...M(o.platform)&&o.appleOs?{appleOs:o.appleOs}:{}}}:L(c.error?.code??`COMMAND_FAILED`,Hs(c),{platform:j(o),target:o.target??`mobile`,device:o.name,id:o.id,kind:o.kind,shutdown:c})}return t.command===`appstate`?await Bs({req:t,sessionName:n,sessionStore:i}):null}function Hs(e){let t=e.error?.message??e.stderr.trim();return t.length>0?t:`Shutdown failed`}bn();function Us(e){let t=[];for(let n of e){if(n.command!==`open`)continue;let e=n.result?.startup;if(!e||typeof e!=`object`)continue;let r=e;typeof r.durationMs!=`number`||!Number.isFinite(r.durationMs)||typeof r.measuredAt!=`string`||r.measuredAt.trim().length===0||r.method!==`open-command-roundtrip`||t.push({durationMs:Math.max(0,Math.round(r.durationMs)),measuredAt:r.measuredAt,method:uo,appTarget:typeof r.appTarget==`string`&&r.appTarget.length>0?r.appTarget:void 0,appBundleId:typeof r.appBundleId==`string`&&r.appBundleId.length>0?r.appBundleId:void 0})}return t.slice(-20)}async function Ws(e,t={}){let n=Js(e);if(!nc(e))return n;if(!e.appBundleId)return $s(n,e),n;let r=Gs(e.device);return r&&ec(n,e,await r(e,e.appBundleId,t)),n}function Gs(e){let t=gn(e.platform)?.perf?.metricsSamplerTag(e);return t?uc[t]:void 0}async function Ks(e,t={}){let n=Zs(e);return nc(e)?e.appBundleId?(await tc(n,e,e.appBundleId,t),n):(n.metrics.fps={available:!1,reason:rc(e)},n):n}async function qs(e,t){let n=Qs(e);return nc(e)?t.action===`sample`?(n.metrics={memory:await dc(e,t)},n):(n.artifact=await pc(e,t),n.support=yc(n.artifact.support)??vc(e),n):t.action===`snapshot`?(n.artifact=gc(e,mc(e,t.kind)),n.support=yc(n.artifact.support)??vc(e),n):(n.metrics={memory:{available:!1,reason:fo}},n)}function Js(e){let t=Us(e.actions),n=t.at(-1),r=n?{available:!0,lastDurationMs:n.durationMs,lastMeasuredAt:n.measuredAt,method:uo,sampleCount:t.length,samples:t}:{available:!1,reason:`No startup sample captured yet. Run open <app|url> in this session first.`,method:uo};return{session:e.name,platform:j(e.device),device:e.device.name,deviceId:e.device.id,metrics:{startup:r,...Ys()},sampling:{startup:{method:uo,description:`Elapsed wall-clock time around dispatching the open command for the active session app target.`,unit:`ms`},...ic(e)}}}function Ys(){return{fps:Xs(),memory:{available:!1,reason:fo},cpu:{available:!1,reason:fo}}}function Xs(){return{available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`}}function Zs(e){return{session:e.name,platform:j(e.device),device:e.device.name,deviceId:e.device.id,metrics:{fps:Xs()},sampling:{fps:sc(e)}}}function Qs(e){return{session:e.name,platform:j(e.device),device:e.device.name,deviceId:e.device.id,sampling:{memory:ac(e),snapshot:oc(e)}}}function $s(e,t){let n=rc(t);e.metrics.fps={available:!1,reason:n},e.metrics.memory={available:!1,reason:n},e.metrics.cpu={available:!1,reason:n}}function ec(e,t,n){e.metrics.memory=xc(n.memory),e.metrics.cpu=xc(n.cpu),e.metrics.fps=Sc(xc(n.fps),t)}async function tc(e,t,n,r){let i=t.device.platform===`android`?await bc(Yn(t.device,n,{adb:r.androidAdb})):await bc(pr(t.device,n));e.metrics.fps=Sc(xc(i),t)}function nc(e){return gn(e.device.platform)?.perf?.supportsMetrics(e.device)??!1}function rc(e){return e.device.platform===`android`?`No Android app package is associated with this session. Run open <app> first.`:`No Apple app bundle ID is associated with this session. Run open <app> first.`}function ic(e){return e.device.platform===`android`?{memory:{method:Rn,description:zn,unit:`kB`},cpu:{method:Ln,description:rr,unit:`percent`},fps:{method:gi,description:nr,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}}:Zr(e.device)}function ac(e){return e.device.platform===`android`?{method:Rn,description:zn,unit:`kB`,topConsumerLimit:5}:Zr(e.device).memory}function oc(e){return e.device.platform===`android`?{method:ir,description:di,defaultKind:`android-hprof`,artifactOnly:!0}:{method:lr,description:ar,defaultKind:`memgraph`,artifactOnly:!0}}function sc(e){return e.device.platform===`android`?{method:gi,description:nr,unit:`percent`,primaryField:`droppedFramePercent`,window:`since previous Android gfxinfo reset or app process start`,resetsAfterRead:!0,relatedActionsLimit:12}:Hn(e.device)}async function cc(e,t,n){let r={adb:n.androidAdb},[i,a,o]=await Promise.allSettled([Fn(e.device,t,r),Rr(e.device,t,r),Yn(e.device,t,r)]);return{memory:i,cpu:a,fps:o}}async function lc(e,t){let n=await bc(pr(e.device,t)),r=await bc(dr(e.device,t));if(r.status===`fulfilled`){let e=r.value;return{memory:{status:`fulfilled`,value:e.memory},cpu:{status:`fulfilled`,value:e.cpu},fps:n}}return{memory:{status:`rejected`,reason:r.reason},cpu:{status:`rejected`,reason:r.reason},fps:n}}const uc={android:cc,apple:lc};async function dc(e,t){return e.appBundleId?xc(e.device.platform===`android`?await bc(Fn(e.device,e.appBundleId,{adb:t.androidAdb})):await bc(fc(e))):{available:!1,reason:rc(e)}}async function fc(e){if(!e.appBundleId)throw new n(`INVALID_ARGS`,rc(e));return(await dr(e.device,e.appBundleId)).memory}async function pc(e,t){if(!e.appBundleId)throw new n(`INVALID_ARGS`,rc(e),{hint:`Run open <app> first so perf memory snapshot can resolve the app process.`});let r=mc(e,t.kind),i=hc(t,r);return e.device.platform===`android`?r===`android-hprof`?await Qn(e.device,e.appBundleId,i,{adb:t.androidAdb}):gc(e,r):r===`memgraph`?await qn(e.device,e.appBundleId,i):gc(e,r)}function mc(e,t){return t||(e.device.platform===`android`?`android-hprof`:`memgraph`)}function hc(e,t){if(e.out)return k.expandHome(e.out,e.cwd);let n=t===`android-hprof`?`hprof`:t===`memgraph`?`memgraph`:`artifact`,r=new Date().toISOString().replace(/[:.]/g,`-`),i=e.sessionStore.ensureSessionDir(e.sessionName);return H.join(i,`artifacts`,`memory-${t}-${r}.${n}`)}function gc(e,t){let n=vc(e),r=_c(e,t);return{available:!1,kind:t,reason:r.reason,hint:r.hint,support:n}}function _c(e,t){return e.device.platform===`android`?{reason:`Android perf memory snapshot supports android-hprof, not ${t}.`,hint:`Use perf memory snapshot --kind android-hprof for Android Java heap artifacts.`}:M(e.device.platform)?{reason:`Apple perf memory snapshot supports memgraph, not ${t}.`,hint:`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`}:{reason:`Memory snapshot artifacts are not supported on ${e.device.platform}.`,hint:`Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS.`}}function vc(e){return e.device.platform===`android`?{platform:e.device.platform,defaultKind:`android-hprof`,androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:`Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice.`}:M(e.device.platform)?{...Jn(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:`Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice.`}:{platform:e.device.platform,defaultKind:`memgraph`,androidHprof:!1,memgraph:!1,heapprofd:!1,reason:`Memory snapshot artifacts are available only on Android, iOS simulator, and macOS.`,hint:`Use perf memory sample where supported, or switch to a platform with memory artifact support.`,heapprofdDecision:`Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice.`}}function yc(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function bc(e){try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}function xc(t){if(t.status===`fulfilled`)return{available:!0,...t.value};let n=e(t.reason);return{available:!1,reason:n.message,error:n}}function Sc(e,t){if(e.available!==!0)return e;let n=Cc(t.actions,e);return n.length===0?e:{...e,relatedActions:n}}function Cc(e,t){let n=wc(t.windowStartedAt),r=wc(t.windowEndedAt)??wc(t.measuredAt);return n===void 0||r===void 0?[]:e.filter(e=>e.ts>=n&&e.ts<=r).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:Tc(e)})).slice(-12)}function wc(e){if(typeof e!=`string`)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Tc(e){let t=e.result;if(t)for(let e of[`refLabel`,`ref`,`appName`,`appBundleId`]){let n=t[e];if(typeof n==`string`&&n.length>0)return n}}async function Ec(t){let n=Dc(t.req,t.area);if(!n.ok)return n;let{session:r}=t;if(r.device.platform!==`android`)return L(`UNSUPPORTED_OPERATION`,`Android native perf collectors are supported only on Android sessions.`);if(!r.appBundleId)return L(`COMMAND_FAILED`,`No Android app package is associated with this session.`,{hint:`Run open <app> first so perf can resolve the package and process identity.`});try{return{ok:!0,data:n.area===`cpu`?await Ic(t,r,r.appBundleId,n):await Lc(t,r,r.appBundleId,n)}}catch(t){return{ok:!1,error:e(t)}}}function Dc(e,t){let n=Fc(e,t);return t===`cpu`?Oc(e,n):kc(e,n)}function Oc(e,t){let n=Ac(e,1),r=Ac(e,2),i=Ac(e,3);return w(n)?jc(r)?i===`simpleperf`?{ok:!0,area:`cpu`,subject:n,action:r,kind:i,outPath:t}:L(`INVALID_ARGS`,`perf cpu profile requires --kind simpleperf`):L(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`):L(`INVALID_ARGS`,be)}function kc(e,t){let n=Ac(e,1),r=Ac(e,2);return Mc(n)?ie(r)?r===`perfetto`?{ok:!0,area:`trace`,action:n,kind:r,outPath:t}:L(`INVALID_ARGS`,`perf trace requires --kind perfetto`):L(`INVALID_ARGS`,xe):L(`INVALID_ARGS`,`perf trace action must be start or stop`)}function Ac(e,t){return(e.positionals?.[t]??``).toLowerCase()}function jc(e){return e===`start`||e===`stop`||e===`report`}function Mc(e){return e===`start`||e===`stop`}function Nc(e,t){return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),Hc(t)}function Pc(e,t,n){return t?k.expandHome(t,e.req.meta?.cwd):Vc(e.sessionStore,e.sessionName,n)}function Fc(e,t){return typeof e.flags?.out==`string`&&e.flags.out.length>0?e.flags.out:(e.positionals??[])[t===`cpu`?5:4]||void 0}async function Ic(e,t,n,r){if(r.action===`start`){zc(t);let i=Pc(e,r.outPath,`cpu.perf.data`);return Nc(e,await Ir(t.device,n,i,{adb:e.androidAdbExecutor}))}let i=Uc(t,`cpu-profile`,r.kind);if(r.action===`report`){await Rc(i);let n=Pc(e,r.outPath,`cpu-report.json`);return await Zn(t.device,i,n,{adb:e.androidAdbExecutor})}let a=Bc(e,r.outPath,i);return Nc(e,await Xn(t.device,i,a,{adb:e.androidAdbExecutor}))}async function Lc(e,t,n,r){if(r.action===`start`){zc(t);let i=Pc(e,r.outPath,`app.perfetto-trace`);return Nc(e,await $n(t.device,n,i,{adb:e.androidAdbExecutor}))}let i=Uc(t,`trace`,r.kind),a=Bc(e,r.outPath,i);return Nc(e,await Bn(t.device,i,a,{adb:e.androidAdbExecutor}))}function Rc(e){if(e.state===`running`)throw new n(`COMMAND_FAILED`,`Stop the Android Simpleperf CPU profile before generating a report.`,{hint:`Run perf cpu profile stop --kind simpleperf, then retry perf cpu profile report --kind simpleperf.`})}function zc(e){let t=e.nativePerf?.android;if(t?.state===`running`)throw new n(`COMMAND_FAILED`,`Android ${t.kind} ${t.type} is already running for this session.`,{hint:t.type===`cpu-profile`?`Run perf cpu profile stop --kind simpleperf before starting another Android native perf capture.`:`Run perf trace stop --kind perfetto before starting another Android native perf capture.`})}function Bc(e,t,n){return t?Pc(e,t,n.outPath):n.outPath}function Vc(e,t,n){let r=new Date().toISOString().replace(/[:.]/g,`-`);return H.join(e.ensureSessionDir(t),`${r}-${n}`)}function Hc(e){return{action:e.action,platform:`android`,type:e.type,kind:e.kind,packageName:e.packageName,appPid:e.appPid,profilerPid:e.profilerPid,state:e.state,startedAt:new Date(e.startedAt).toISOString(),stoppedAt:typeof e.stoppedAt==`number`?new Date(e.stoppedAt).toISOString():void 0,durationMs:e.durationMs,outPath:e.outPath,sizeBytes:e.sizeBytes,remotePath:e.remotePath,method:e.method,summary:e.summary,message:e.message}}function Uc(e,t,r){let i=e.nativePerf?.android;if(i?.type===t&&i.kind===r)return i;throw new n(`COMMAND_FAILED`,`No Android ${r} ${t} is active for this session.`,{hint:t===`cpu-profile`?`Run perf cpu profile start --kind simpleperf first, then stop or report in the same session.`:`Run perf trace start --kind perfetto first, then stop in the same session.`})}async function Wc(e){if(!_n(e))return;let{macOsScreenCaptureKitAudioProbeBackend:t}=await import(`./audio-probe.js`);return t}const Gc=[`probe`],Kc=[`start`,`status`,`stop`],qc=`audio probe requires ${Kc.join(`, `)}`;async function Jc(t){let n=Yc(t);if(!n.ok)return n;let r=await Wc(n.session.device);if(r)return await Zc(t,n,r);let i=Hr();if(!i.probeAudio)return L(`UNSUPPORTED_OPERATION`,`audio is not supported by this web provider`);try{return{ok:!0,data:await i.probeAudio({action:n.probeAction,durationMs:n.durationMs,bucketMs:n.bucketMs})}}catch(t){return{ok:!1,error:e(t)}}}function Yc(e){let t=Xc(e);if(!t.ok)return t;let n=Qc(e.req);if(!n.ok)return n;let r=$c(e.req,n.probeAction);return r.ok?{ok:!0,session:t.session,probeAction:n.probeAction,...r.timing}:r}function Xc(e){let t=e.sessionStore.get(e.sessionName);return t?pn(`audio`,t.device)?{ok:!0,session:t}:L(`UNSUPPORTED_OPERATION`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`):L(`SESSION_NOT_FOUND`,`audio requires an active session`)}async function Zc(t,n,r){try{return{ok:!0,data:await gr({session:n.session,sessionName:t.sessionName,sessionStore:t.sessionStore,backend:r,probeAction:n.probeAction,durationMs:n.durationMs,bucketMs:n.bucketMs})}}catch(t){return{ok:!1,error:e(t)}}}function Qc(e){if(!el(e.positionals?.[0]))return L(`INVALID_ARGS`,`audio requires probe`);let t=tl(e.positionals?.[1]);return t?{ok:!0,probeAction:t}:L(`INVALID_ARGS`,qc)}function $c(e,t){if(t!==`start`&&e.positionals&&e.positionals.length>2)return L(`INVALID_ARGS`,`audio probe duration and bucket are only supported with audio probe start`);let n=nl(e.positionals?.[2],{defaultValue:1e4,min:100,max:12e4,message:`audio probe duration must be an integer in range 100..120000 ms`});if(n instanceof Error)return L(`INVALID_ARGS`,n.message);let r=nl(e.positionals?.[3],{defaultValue:1e3,min:100,max:1e4,message:`audio probe bucket must be an integer in range 100..10000 ms`});return r instanceof Error?L(`INVALID_ARGS`,r.message):{ok:!0,timing:{durationMs:n,bucketMs:r}}}function el(e){let t=(e??`probe`).toLowerCase();return Gc.includes(t)?`probe`:void 0}function tl(e){let t=(e??`status`).toLowerCase();return Kc.includes(t)?t:void 0}function nl(e,t){if(e===void 0)return t.defaultValue;let n=Number.parseInt(e,10);return!Number.isInteger(n)||String(n)!==e||n<t.min||n>t.max?Error(t.message):n}async function rl(t,n){let r=il(t.req);if(!r.ok)return r;if(n.device.platform===`android`)return L(`UNSUPPORTED_OPERATION`,`Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.`);if(!M(n.device.platform))return L(`UNSUPPORTED_OPERATION`,`Apple xctrace perf is not supported on ${n.device.platform}.`);if(!n.appBundleId)return L(`INVALID_ARGS`,`Apple xctrace perf requires an active app session. Run open <app> first.`);try{return r.action===`start`?await ll(t,n,r):r.action===`stop`?await ul(t,n,r):await hl(t,n,r)}catch(t){return{ok:!1,error:e(t)}}}function il(e){let t=e.positionals??[],n=t[0]?.toLowerCase();return n===`cpu`?al(t):n===`trace`?ol(t):L(`INVALID_ARGS`,Ce)}function al(e){if(e[1]?.toLowerCase()!==`profile`)return L(`INVALID_ARGS`,`perf cpu requires profile`);let t=sl(e[2],`perf cpu profile`,!0);if(!t.ok)return t;let n=cl(e[3]);return n.ok?{ok:!0,area:`cpu`,mode:`cpu-profile`,action:t.value,kind:`xctrace`,template:e[4]||void 0,outPath:e[5]||void 0,tracePath:e[6]||void 0}:n}function ol(e){let t=sl(e[1],`perf trace`,!1);if(!t.ok)return t;let n=cl(e[2]);return n.ok?{ok:!0,area:`trace`,mode:`trace`,action:t.value,kind:`xctrace`,template:e[3]||void 0,outPath:e[4]||void 0,tracePath:e[5]||void 0}:n}function sl(e,t,n){let r=e?.toLowerCase();return r===`start`||r===`stop`||n&&r===`report`?{ok:!0,value:r}:L(`INVALID_ARGS`,n?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function cl(e){return e?.toLowerCase()===`xctrace`?{ok:!0}:L(`INVALID_ARGS`,`perf native collection currently supports --kind xctrace`)}async function ll(e,t,n){if(t.applePerf?.active)return L(`INVALID_ARGS`,`Apple xctrace perf capture already in progress`);let r=n.template??yl(n.mode),i=vl(e,n),a=await In({device:t.device,appBundleId:t.appBundleId,mode:n.mode,template:r,outPath:i});t.applePerf={...t.applePerf??{},active:a},e.sessionStore.set(e.sessionName,t);let o=bl(`started`,a);return _l(e,t,o),{ok:!0,data:o}}async function ul(e,t,n){let r=t.applePerf?.active;if(!r)return L(`INVALID_ARGS`,`no active Apple xctrace perf capture`);let i=n.outPath?k.expandHome(n.outPath,e.req.meta?.cwd):r.outPath,a;try{a=await sr(r,i)}catch(n){throw fl(n)&&dl(e,t),n}pl(e,t,a);let o=bl(`stopped`,a);return _l(e,t,o),{ok:!0,data:o}}function dl(e,t){t.applePerf={...t.applePerf??{},active:void 0},e.sessionStore.set(e.sessionName,t)}function fl(e){return s(e).details?.captureCleanedUp===!0}function pl(e,t,n){t.applePerf={...t.applePerf??{},active:void 0,lastMode:n.mode,...ml(n)},e.sessionStore.set(e.sessionName,t)}function ml(e){return e.mode===`cpu-profile`?{lastProfileTracePath:e.outPath,lastProfileTemplate:e.template}:{lastTracePath:e.outPath}}async function hl(e,t,n){if(n.mode!==`cpu-profile`)return L(`INVALID_ARGS`,`perf trace does not support report`);if(t.applePerf?.active)return L(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace; stop the active capture first.`);let r=vl(e,n),i=gl(t,n);if(!i.ok)return i;let a={perf:`reported`,...await Un({tracePath:k.expandHome(i.value,e.req.meta?.cwd),outPath:r,mode:n.mode,template:t.applePerf?.lastProfileTemplate??n.template,appBundleId:t.appBundleId})};return _l(e,t,a),{ok:!0,data:a}}function gl(e,t){let n=t.tracePath??e.applePerf?.lastProfileTracePath??e.applePerf?.active?.outPath;return n?{ok:!0,value:n}:L(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace or tracePath option`)}function _l(e,t,n){jr(e.sessionStore,t,e.req,`perf`,n)}function vl(e,t){if(t.outPath)return k.expandHome(t.outPath,e.req.meta?.cwd);let n=e.sessionStore.ensureSessionDir(e.sessionName),r=new Date().toISOString().replace(/[:.]/g,`-`),i=t.action===`report`?`json`:`trace`;return`${n}/perf-${t.mode}-${r}.${i}`}function yl(e){return e===`cpu-profile`?`Time Profiler`:`Animation Hitches`}function bl(e,t){return{perf:e,kind:t.kind,mode:t.mode,template:t.template,outPath:t.outPath,appBundleId:t.appBundleId,deviceId:t.deviceId,platform:t.platform,targetPids:t.targetPids,targetProcesses:t.targetProcesses,startedAt:t.startedAt,endedAt:t.endedAt}}const xl=`logs requires ${le.slice(0,-1).join(`, `)}, or ${le.at(-1)}`,Sl=[`dump`,`log`],Cl=`network requires ${Sl.join(` or `)}`,wl=`network include mode must be one of: ${o.join(`, `)}`,Tl={path:({session:e,sessionName:t,sessionStore:n})=>Zl(e,t,n),doctor:({session:e,sessionName:t,sessionStore:n})=>Ql(e,t,n),mark:({req:e,sessionName:t,sessionStore:n})=>$l(e,t,n),clear:({session:e,sessionName:t,sessionStore:n,restart:r})=>eu(e,t,n,r),start:({session:e,sessionName:t,sessionStore:n})=>tu(e,t,n),stop:({session:e,sessionName:t,sessionStore:n})=>nu(e,t,n)};function El(e){if(e.appLog){let t=e.appLog.getState();return{active:t===`active`||t===`recovering`,state:t,backend:e.appLog.backend,startedAt:e.appLog.startedAt,notes:kl(t)}}return e.appLogFailure?{active:!1,state:`failed`,backend:e.appLogFailure.backend,failureCode:e.appLogFailure.code,failureMessage:e.appLogFailure.message,hint:e.appLogFailure.hint,notes:[Ol(e.appLogFailure)]}:{active:!1,state:`inactive`,backend:Kr(e.device)}}function Dl(e,t){return{backend:t,code:e.code,message:e.message,hint:e.hint}}function Ol(e){return e.hint?`${e.message} ${e.hint}`:e.message}function kl(e){if(e===`failed`)return[`The app log stream process exited with an error. Run logs doctor for backend diagnostics.`];if(e===`ended`)return[`The app log stream process ended. Run logs clear --restart before the next capture window.`]}function Al(e,t){return mr([...e,...t.notes??[]])}function jl(e,t,n){return{...n,platform:e.device.platform,outPath:t}}function Ml(t,n,r,i){let a=e(i);return t.set(n,{...r,appLog:void 0,appLogFailure:Dl(a,Kr(r.device))}),{ok:!1,error:a}}async function Nl(e){let{req:t}=e;return t.command===`perf`?Fl(e):t.command===`logs`?Yl(e):t.command===`events`?await Pl(e):t.command===`network`?ru(e):t.command===`audio`?await Jc(e):null}async function Pl(t){let{req:n,sessionName:r,sessionStore:i}=t;try{return await i.flushEvents(r),{ok:!0,data:i.readEvents(r,{limit:n.positionals?.[0],cursor:n.positionals?.[1]})}}catch(t){return{ok:!1,error:e(t)}}}async function Fl(t){let{req:n,sessionName:r,sessionStore:i,androidAdbExecutor:a}=t,o=i.get(r);if(!o)return L(`SESSION_NOT_FOUND`,`perf requires an active session. Run open first.`);let s=(n.positionals?.[0]??`metrics`).toLowerCase();if(Il(s))return o.device.platform===`android`?await Ec({req:n,sessionName:r,sessionStore:i,session:o,androidAdbExecutor:a,area:s}):await rl(t,o);let c=Ll(n);if(!c.ok)return c;if(c.native)return await rl(t,o);try{return{ok:!0,data:await Rl(t,o,c)}}catch(t){return{ok:!1,error:e(t)}}}function Il(e){return e===`cpu`||e===`trace`}function Ll(t){let r=zl(t.positionals?.[0]);if(!r)return L(`INVALID_ARGS`,Ce);if(r===`cpu`||r===`trace`)return{ok:!0,native:!0};let i=Bl(t.positionals?.[1]);if(!i)return L(`INVALID_ARGS`,oe);let a=Vl(t.flags?.kind);return a instanceof n?{ok:!1,error:e(a)}:(Hl(r,i)??Gl(t,r,i,a))||{ok:!0,native:!1,area:r,action:i,kind:a,out:Jl(t.flags?.out)}}async function Rl(e,t,n){let{sessionName:r,sessionStore:i,androidAdbExecutor:a}=e;return n.area===`memory`?await qs(t,{action:Wl(n.action),kind:n.kind,out:n.out,cwd:e.req.meta?.cwd,sessionName:r,sessionStore:i,androidAdb:a}):n.area===`frames`?await Ks(t,{androidAdb:a}):await Ws(t,{androidAdb:a})}function zl(e){let t=(e??`metrics`).toString().toLowerCase();return E(t)?t:void 0}function Bl(e){let t=(e??`sample`).toString().toLowerCase();return ne(t)?t:void 0}function Vl(e){if(e!==void 0)return typeof e!=`string`||!ie(e)?new n(`INVALID_ARGS`,xe):e}function Hl(e,t){if(e===`memory`)return Ul(t)?void 0:L(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(t!==`sample`)return L(`INVALID_ARGS`,`perf metrics and perf frames only support sample`)}function Ul(e){return e===`sample`||e===`snapshot`}function Wl(e){if(Ul(e))return e;throw new n(`INVALID_ARGS`,`perf memory requires sample or snapshot`)}function Gl(e,t,n,r){return Kl(e.flags?.out,t,n)??ql(r,t,n)}function Kl(e,t,n){if(!(!e||t===`memory`&&n===`snapshot`))return L(`INVALID_ARGS`,`--out is only supported with perf memory snapshot`)}function ql(e,t,n){if(e){if(t!==`memory`||n!==`snapshot`)return L(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(!ue(e))return L(`INVALID_ARGS`,T)}}function Jl(e){return typeof e==`string`&&e.length>0?e:void 0}async function Yl(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n);if(!i)return L(`SESSION_NOT_FOUND`,`logs requires an active session`);let a=I(`logs`,i.device);if(a)return a;let o=Xl(t);return o.ok?await Tl[o.action]({...e,session:i,restart:o.restart}):o}function Xl(e){let t=(e.positionals?.[0]??`path`).toLowerCase(),n=!!e.flags?.restart;return le.includes(t)?n&&t!==`clear`?L(`INVALID_ARGS`,`logs --restart is only supported with logs clear`):{ok:!0,action:t,restart:n}:L(`INVALID_ARGS`,xl)}function Zl(e,t,n){let r=n.resolveAppLogPath(t),i=Dr(r),a=El(e);return{ok:!0,data:{path:r,active:a.active,state:a.state,backend:a.backend,sizeBytes:i.sizeBytes,modifiedAt:i.modifiedAt,startedAt:a.startedAt?new Date(a.startedAt).toISOString():void 0,failureCode:a.failureCode,failureMessage:a.failureMessage,hint:a.hint??`Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>`,notes:a.notes}}}async function Ql(e,t,n){let r=n.resolveAppLogPath(t),i=await Jr(e.device,e.appBundleId),a=El(e);return{ok:!0,data:{path:r,active:a.active,state:a.state,backend:a.backend,checks:i.checks,failureCode:a.failureCode,failureMessage:a.failureMessage,hint:a.hint,notes:Al(i.notes,a)}}}function $l(e,t,n){let r=e.positionals?.slice(1).join(` `)??``,i=n.resolveAppLogPath(t);return er(i,r),{ok:!0,data:{path:i,marked:!0}}}async function eu(e,t,n,r){if(e.appLog&&!r)return L(`INVALID_ARGS`,`logs clear requires logs to be stopped first; run logs stop`);let i=n.resolveAppLogPath(t);if(!r){let r=Nn(i);return n.set(t,{...e,appLogFailure:void 0}),{ok:!0,data:r}}let a=e.appBundleId;if(!a)return L(`INVALID_ARGS`,`logs clear --restart requires an app session; run open <app> first`);e.appLog&&await Fr(e.appLog);let o=Nn(i),s=n.resolveAppLogPidPath(t);try{let r=await ei(e.device,a,i,s);return n.set(t,{...e,appLog:jl(e,i,r),appLogFailure:void 0}),{ok:!0,data:{...o,restarted:!0}}}catch(r){return Ml(n,t,e,r)}}async function tu(e,t,n){if(e.appLog)return L(`INVALID_ARGS`,`app log already streaming; run logs stop first`);if(!e.appBundleId)return L(`INVALID_ARGS`,`logs start requires an app session; run open <app> first`);let r=n.resolveAppLogPath(t),i=n.resolveAppLogPidPath(t);try{let a=await ei(e.device,e.appBundleId,r,i);return n.set(t,{...e,appLog:jl(e,r,a),appLogFailure:void 0}),{ok:!0,data:{path:r,started:!0}}}catch(r){return Ml(n,t,e,r)}}async function nu(e,t,n){if(!e.appLog)return L(`INVALID_ARGS`,`no app log stream active`);let r=e.appLog.outPath;return await Fr(e.appLog),n.set(t,{...e,appLog:void 0,appLogFailure:void 0}),{ok:!0,data:{path:r,stopped:!0}}}async function ru(e){let t=au(e);if(!t.ok)return t;let{include:n,maxEntries:r,session:i}=t;if(i.device.platform===`web`)return await iu({include:n,maxEntries:r});let a=await oi({device:i.device,appBundleId:i.appBundleId,appLogState:i.appLog?.getState(),appLogStartedAt:i.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:r,include:n,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...a.dump,active:!!i.appLog,state:i.appLog?.getState()??`inactive`,backend:a.backend,notes:a.notes}}}async function iu(t){let n=Hr();if(!n.dumpNetwork)return L(`UNSUPPORTED_OPERATION`,`network is not supported by this web provider`);try{let e=await n.dumpNetwork({include:t.include,limit:t.maxEntries});return{ok:!0,data:{entries:e.entries,active:!0,state:`active`,backend:e.backend??`agent-browser`,include:t.include,matchedLines:e.entries.length,scannedLines:e.entries.length,limits:{maxEntries:t.maxEntries,maxPayloadChars:2048,maxScanLines:e.entries.length},notes:e.notes}}}catch(t){return{ok:!1,error:e(t)}}}function au(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n);if(!i)return L(`SESSION_NOT_FOUND`,`network requires an active session`);let a=I(`network`,i.device);if(a)return a;let o=(t.positionals?.[0]??`dump`).toLowerCase();if(!Sl.includes(o))return L(`INVALID_ARGS`,Cl);let s=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(s)||s<1||s>200)return L(`INVALID_ARGS`,`network dump limit must be an integer in range 1..200`);let c=ou(t);return c.ok?{ok:!0,session:i,maxEntries:s,include:c.include}:c}function ou(e){let t=e.positionals?.[2]?.toLowerCase(),n=e.flags?.networkInclude;if(t&&n&&t!==n)return L(`INVALID_ARGS`,`network include mode was provided both positionally and via --include with different values`);let r=(n??t??`summary`).toLowerCase();return o.includes(r)?{ok:!0,include:r}:L(`INVALID_ARGS`,wl)}function su(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=k.expandHome(t??`.agent-device/test-artifacts`,n);return H.join(i,r)}function cu(e,t){let n=t?H.relative(t,e):H.basename(e);return(n.length===0||n.startsWith(`..`)?H.basename(e):n).toLowerCase().replace(/[\\/]+/g,`__`).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)||`test`}function lu(e,t){V.mkdirSync(t,{recursive:!0}),pu(e,t)}function uu(e){let{response:t,filePath:n,sessionName:r,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=[...du(t)];!t.ok&&typeof t.error.logPath==`string`&&s.push(t.error.logPath);let c=fu(s,o),l=[`file: ${n}`,`session: ${r}`,`attempt: ${i}/${a}`,`status: ${t.ok?`passed`:`failed`}`];if(t.ok){let e=typeof t.data?.replayed==`number`?t.data.replayed:0,n=typeof t.data?.healed==`number`?t.data.healed:0;l.push(`replayed: ${e}`,`healed: ${n}`)}else l.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&l.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&l.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&l.push(`logPath: ${t.error.logPath}`),t.error.details?.reason===`timeout`&&l.push(`timeoutMode: cooperative`);c.length>0&&l.push(`copiedArtifacts: ${c.map(e=>H.basename(e)).join(`, `)}`);let u=H.join(o,`result.txt`),d=`${l.join(`
3
+ `)}\n`;V.writeFileSync(u,d),t.ok||V.writeFileSync(H.join(o,`failure.txt`),d)}function du(e){let t=e.ok?e.data?.artifactPaths:e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>typeof e==`string`))]:[]}function fu(e,t){let n=[],r=new Map;for(let i of e){if(!gu(i))continue;let e=hu(H.basename(i),r),a=H.join(t,e);H.resolve(i)!==H.resolve(a)&&V.copyFileSync(i,a),n.push(a)}return n}function pu(e,t){let n=H.join(t,`replay.ad`);if(V.copyFileSync(e,n),!mu(e))return;let r=H.join(t,H.basename(e));H.resolve(r)!==H.resolve(n)&&V.copyFileSync(e,r)}function mu(e){let t=H.extname(e).toLowerCase();return t===`.yml`||t===`.yaml`}function hu(e,t){let n=H.extname(e),r=n?e.slice(0,-n.length):e,i=t.get(e)??0;return t.set(e,i+1),i===0?e:`${r}-${i+1}${n}`}function gu(e){try{return V.statSync(e).isFile()}catch{return!1}}const _u=/[*?[\]{}]/;function vu(e){let{inputs:t,cwd:r,platformFilter:i,replayBackend:a}=e,o=Ou(a),s=wu(t,r??process.cwd(),o,a),c=[];for(let e of s){let t=V.readFileSync(e,`utf8`),n=Wt(t),r=Fu(t,e,a);if(!i){c.push({kind:`run`,path:e,title:r,metadata:n});continue}if(!n.platform){Pu(a)?c.push({kind:`run`,path:e,title:r,metadata:n}):c.push({kind:`skip`,path:e,reason:`skipped-by-filter`,message:`missing platform metadata for --platform ${i}`});continue}Lu(i,n.platform)&&c.push({kind:`run`,path:e,title:r,metadata:n})}if(c.filter(e=>e.kind===`run`).length===0)throw new n(`INVALID_ARGS`,`No replay tests matched${i?` for --platform ${i}`:``}.`);return c}function yu(e,t,n,r,i=0){let a=H.basename(n,H.extname(n)).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return`${e}:test:${t}:${r+1}${a?`-${a}`:``}:attempt-${i+1}`}function bu(e){return(e?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`suite`}function xu(e){let{requestId:t,suiteInvocationId:n,filePath:r,caseIndex:i,attemptIndex:a,shardIndex:o}=e,s=o===void 0?``:`:shard:${o+1}`;return Xt(`${t??n}${s}:test:${i+1}:${H.basename(r)}:attempt:${a+1}`,n)}function Su(e,t){return typeof e==`number`?e:t}function Cu(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function wu(e,t,n,r){if(!Pu(r))return[...new Set(e.flatMap(e=>Du(e,t,n).paths))].map(e=>H.normalize(e)).sort((e,t)=>e.localeCompare(t));let i=[],a=[];for(let r of e){let e=Tu(r,t,n);e.source===`file`?i.push(...e.paths):a.push(e.source===`directory`?Nu(e.paths):Au(e.paths))}return Nu([...i,...a.flat()])}function Tu(e,t,n){let r=k.expandHome(e,t);return V.existsSync(r)&&V.statSync(r).isDirectory()?{paths:Eu(r,n),source:`directory`}:Du(e,t,n)}function Eu(e,t){let n=[],r=V.opendirSync(e);try{let i;for(;(i=r.readSync())!==null;){let r=H.join(e,i.name);i.isDirectory()?n.push(...Eu(r,t)):i.isFile()&&t.has(H.extname(i.name))&&n.push(r)}}finally{r.closeSync()}return n}function Du(e,t,r){let i=k.expandHome(e,t);if(V.existsSync(i)){let t=V.statSync(i);if(t.isDirectory())return{paths:ku(r).flatMap(e=>V.globSync(e,{cwd:i}).map(e=>H.join(i,e))),source:`directory`};if(t.isFile()){if(!r.has(H.extname(i)))throw new n(`INVALID_ARGS`,`test does not support this file type: ${e}`);return{paths:[i],source:`file`}}return{paths:[],source:`file`}}if(!Iu(e)&&!Iu(i))throw new n(`INVALID_ARGS`,`test input not found: ${e}`);let a=H.isAbsolute(i)?i:e;return{paths:V.globSync(a,{cwd:H.isAbsolute(i)?void 0:t}).map(e=>H.isAbsolute(e)?e:H.resolve(t,e)).filter(e=>r.has(H.extname(e))&&Ru(e)),source:`glob`}}function Ou(e){return Pu(e)?new Set([`.yaml`,`.yml`,`.ad`]):new Set([`.ad`])}function ku(e){return[...e].map(e=>`**/*${e}`)}function Au(e){return e.map(e=>H.normalize(e)).sort(ju)}function ju(e,t){let n=Mu(e),r=Mu(t);return n===r?e.localeCompare(t):n-r}function Mu(e){return+(H.extname(e)===`.ad`)}function Nu(e){return[...new Set(e.map(e=>H.normalize(e)))]}function Pu(e){return e===`maestro`}function Fu(e,t,n){return Pu(n)&&H.extname(t)!==`.ad`?Vr(e,{sourcePath:t}).config.name:void 0}function Iu(e){return _u.test(e)}function Lu(e,t){return e===`apple`?M(t):t===e}function Ru(e){try{return V.statSync(e).isFile()}catch{return!1}}const zu=[`failed to start daemon`,`runner did not accept connection`,`xcodebuild exited early`,`device is offline`,`device offline`,`device unauthorized`];function Bu(e){let t=Vu(e);return t?Hu(t.details)||Uu(t.code,t.message):!1}function Vu(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function Hu(e){let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`?!0:t?Lt(t):!1}function Uu(e,t){let n=`${e}\n${t}`.toLowerCase();return zu.some(e=>n.includes(e))}const Wu=2e3;async function Gu(t){let{filePath:n,sessionName:r,requestId:i,parentRequestId:a,timeoutMs:o,platform:s,target:c,artifactsDir:l,shard:u,progress:f,runReplay:p,cleanupSession:m,finalizeAttempt:h}=t;Yt(i);let g=Ku(i,a),_=new Set,v,y=!1,b,x=Date.now(),S=Qu({artifactsDir:l,artifactPaths:_,filePath:n,sessionName:r,requestId:i,timeoutMs:o,platform:s,target:c}),C=Kt(f,async()=>await p({filePath:n,sessionName:r,platform:s,target:c,requestId:i,artifactsDir:l,artifactPaths:_,tracePath:S,shard:u})).catch(t=>({ok:!1,error:e(t)})).finally(()=>{g(),Gt(i)});try{b=typeof o==`number`?await Promise.race([C,new Promise(e=>{v=setTimeout(()=>{y=!0,Jt(i),e($u(o,[..._]))},o)})]):await C,K(S,{type:`replay_test_attempt_stop`,ts:new Date().toISOString(),session:r,ok:b.ok,timedOut:y,durationMs:Date.now()-x,errorCode:b.ok?void 0:b.error.code})}finally{v&&clearTimeout(v),y&&(await qu(C)||(Xu(b),d({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:r,requestId:i,graceMs:Wu}}),Ju({replayPromise:C,cleanupSession:m,sessionName:r,requestId:i})));let t=await Yu({finalizeAttempt:h,sessionName:r,artifactPaths:_,artifactsDir:l,tracePath:S});b?.ok&&t&&!t.ok&&Zu(b,`Replay test finalization failed: ${t.error.message}`);let n=Date.now();try{K(S,{type:`replay_test_cleanup_start`,ts:new Date().toISOString(),session:r}),await m(r),K(S,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!0,durationMs:Date.now()-n})}catch(t){let i=e(t);K(S,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-n,errorCode:i.code}),d({level:`warn`,phase:`test_cleanup_failed`,data:{session:r,error:i.message}})}}return b??{ok:!1,error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}}}function Ku(e,t){if(!t||t===e)return()=>{};let n=Zt(t);if(!n)return()=>{};let r=()=>{Jt(e)};return n.aborted?(r(),()=>{}):(n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r)})}async function qu(e){return await Promise.race([e.then(()=>!0),Ni(Wu).then(()=>!1)])}async function Ju(t){let{replayPromise:n,cleanupSession:r,sessionName:i,requestId:a}=t;try{await n}finally{try{await r(i)}catch(t){d({level:`warn`,phase:`test_late_cleanup_failed`,data:{session:i,requestId:a,error:e(t).message}})}}}async function Yu(t){let{finalizeAttempt:n,sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o}=t;if(!n)return;let s=Date.now();K(o,{type:`replay_test_finalize_start`,ts:new Date().toISOString(),session:r});try{let e=await n({sessionName:r,artifactPaths:i,artifactsDir:a,tracePath:o});return K(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:e?.ok??!0,durationMs:Date.now()-s,errorCode:e?.ok===!1?e.error.code:void 0}),e}catch(t){let n=e(t);return K(o,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:r,ok:!1,durationMs:Date.now()-s,errorCode:n.code}),d({level:`warn`,phase:`test_finalize_failed`,data:{session:r,error:n.message}}),{ok:!1,error:n}}}function Xu(e){!e||e.ok||(e.error.details={...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0})}function Zu(e,t){let n=e.data??={};n.warnings=[...Array.isArray(n.warnings)?n.warnings.filter(e=>typeof e==`string`):[],t]}function Qu(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=H.join(t,`replay-timing.ndjson`);return V.mkdirSync(H.dirname(l),{recursive:!0}),V.writeFileSync(l,``),n.add(l),K(l,{type:`replay_test_attempt_start`,ts:new Date().toISOString(),replayPath:r,session:i,requestId:a,timeoutMs:o,platform:s,target:c}),l}function K(e,t){e&&V.appendFileSync(e,`${JSON.stringify(t)}\n`)}function $u(e,t=[]){return{ok:!1,error:{code:`COMMAND_FAILED`,message:`TIMEOUT after ${e}ms`,hint:`Replay test timeouts are cooperative; the active command may take a short grace period to stop.`,details:{reason:`timeout`,timeoutMs:e,timeoutMode:`cooperative`,artifactPaths:t}}}}async function ed(e){let t=td(e);return cd(e,t,await nd(e,t))}function td(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:H.join(i,...a?[`shard-${a.shardIndex+1}`]:[],cu(t.path,n)),maxAttempts:r+1}}async function nd(e,t){id(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!Qt(e.requestId);r+=1){let i=await rd(e,t,r);if(ad(n,i),od(e,i.response,r))break;sd(e,t,i)}return n}async function rd(e,t,n){let{entry:r,sessionName:i,suiteInvocationId:a,caseIndex:o,suiteIndex:s,suiteTotal:c,requestId:l,timeoutMs:u,shard:d}=e,f=n+1,p=Date.now(),m=yu(i,a,r.path,o,n),h=H.join(t.testArtifactsDir,`attempt-${f}`);lu(r.path,h);let g=xu({requestId:l,suiteInvocationId:a,filePath:r.path,caseIndex:o,attemptIndex:n,shardIndex:d?.shardIndex}),_=await Gu({filePath:r.path,sessionName:m,requestId:g,parentRequestId:l,timeoutMs:u,platform:r.metadata.platform,target:r.metadata.target,artifactsDir:h,shard:d,progress:{file:r.path,title:r.title,index:s,total:c,attempt:f,maxAttempts:t.maxAttempts,session:m,artifactsDir:t.testArtifactsDir,..._d(d)},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt}),v=Date.now()-p;return uu({response:_,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{response:_,sessionName:m,attempt:f,durationMs:v}}function id(e,t){let{entry:n,sessionName:r,suiteInvocationId:i,caseIndex:a,suiteIndex:o,suiteTotal:s,shard:c}=e;P({type:`replay-test`,file:n.path,title:n.title,status:`start`,index:o,total:s,maxAttempts:t.maxAttempts,session:yu(r,i,n.path,a),artifactsDir:t.testArtifactsDir,..._d(c)})}function ad(e,t){e.finalResponse=t.response,e.finalSessionName=t.sessionName,e.attempts=t.attempt,e.finalAttemptDurationMs=t.durationMs,!t.response.ok&&e.attemptFailures.push({attempt:t.attempt,message:t.response.error.message,durationMs:t.durationMs})}function od(e,t,n){return t.ok||Qt(e.requestId)||Bu(t)||n>=e.retries}function sd(e,t,n){n.response.ok||P({type:`replay-test`,file:e.entry.path,title:e.entry.title,status:`fail`,index:e.suiteIndex,total:e.suiteTotal,attempt:n.attempt,maxAttempts:t.maxAttempts,durationMs:n.durationMs,retrying:!0,message:n.response.error.message,hint:n.response.error.hint,session:n.sessionName,artifactsDir:t.testArtifactsDir,..._d(e.shard)})}function cd(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalResponse?.ok?ld(e,t,n,r):ud(e,t,n,r)}function ld(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalResponse;if(!c?.ok)throw Error(`Expected passing replay test response.`);return P({type:`replay-test`,file:i.path,title:i.title,status:`pass`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,..._d(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`passed`,durationMs:r,finalAttemptDurationMs:n.finalAttemptDurationMs,attempts:n.attempts,artifactsDir:t.testArtifactsDir,...fd(c),...pd(c.data?.warnings),...md(c.data?.snapshotDiagnostics),...gd(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function ud(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=dd(n.finalResponse);return P({type:`replay-test`,file:i.path,title:i.title,status:`fail`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,message:c.message,hint:c.hint,..._d(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`failed`,durationMs:r,attempts:n.attempts,artifactsDir:t.testArtifactsDir,error:c,...md(hd(n.finalResponse)),...gd(s)}}function dd(e){return e&&!e.ok?e.error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}}function fd(e){return{replayed:typeof e.data?.replayed==`number`?e.data.replayed:0,healed:typeof e.data?.healed==`number`?e.data.healed:0}}function pd(e){if(!Array.isArray(e))return{};let t=e.filter(e=>typeof e==`string`);return t.length>0?{warnings:t}:{}}function md(e){let t=Le(e);return t?{snapshotDiagnostics:t}:{}}function hd(e){return e?.ok?e.data?.snapshotDiagnostics:e?.error.details?.snapshotDiagnostics}function gd(e){return _d(e)}function _d(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function vd(e,t,n){let r=bd(e);if(!r||t.length===0)return;let i=await Sd(e,r.count);return{mode:r.kind,shardCount:r.count,total:n+(r.kind===`all`?t.length*r.count:t.length),shards:i.map((e,n)=>({shardIndex:n,shardCount:r.count,device:e,entries:r.kind===`all`?t:t.filter((e,t)=>t%r.count===n)}))}}function yd(e,t){if(!t)return e;let n={...e??{},device:void 0,udid:void 0,serial:void 0,platform:t.device.platform,target:t.device.target,shardAll:void 0,shardSplit:void 0,shardCount:t.shardCount,shardIndex:t.shardIndex};return t.device.platform===`android`?{...n,serial:t.device.id}:{...n,udid:t.device.id}}function bd(e){let t=xd(e?.shardAll,`--shard-all`),r=xd(e?.shardSplit,`--shard-split`);if(t!==void 0&&r!==void 0)throw new n(`INVALID_ARGS`,`--shard-all and --shard-split are mutually exclusive`);if(t!==void 0)return{kind:`all`,count:t};if(r!==void 0)return{kind:`split`,count:r}}function xd(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<1)throw new n(`INVALID_ARGS`,`${t} requires a positive integer`);return e}}async function Sd(e,t){let r=Ed(e),i=wd(await ln(Cd(e)),r,e);if(i.length<t)throw new n(`DEVICE_NOT_FOUND`,`test sharding requires ${Td(t)}, but only ${i.length} matched`);return i.slice(0,t)}function Cd(e){let t=Ft(e?.androidDeviceAllowlist);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:qe({simulatorSetPath:It(e?.iosSimulatorDeviceSet),platform:e?.platform,target:e?.target}),androidSerialAllowlist:t?Array.from(t).sort():void 0}}function wd(e,t,n){return t.length>0?Dd(e,t,n):e.filter(e=>Od(e,n)).sort(jd)}function Td(e){return`${e} device${e===1?``:`s`}`}function Ed(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function Dd(e,t,r){return t.map(t=>{let i=Ad(t),a=e.find(e=>kd(e,r)&&(e.id===t||Ad(e.name)===i));if(!a)throw new n(`DEVICE_NOT_FOUND`,`No shard device matched ${t}`);return a})}function Od(e,t){return!kd(e,t)||!Ye(e)?!1:e.booted!==!1}function kd(e,t){return!(!Xe(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function Ad(e){return e.toLowerCase().replace(/_/g,` `).replace(/\s+/g,` `).trim()}function jd(e,t){return e.id.localeCompare(t.id)}async function Md(e){let{req:t,sessionName:n,runReplay:r,cleanupSession:i,finalizeAttempt:a}=e;if((t.positionals?.length??0)===0)return L(`INVALID_ARGS`,`test requires at least one path or glob`);try{let e=Date.now(),o=await Nd(t);Ld(o);let s=o.shardPlan?Rd({entries:o.entries,total:o.total}):[];return o.shardPlan?s.push(...await zd({shards:o.shardPlan.shards,sessionName:n,suiteInvocationId:o.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:o.suiteArtifactsDir,suiteTotal:o.total,runReplay:r,cleanupSession:i,finalizeAttempt:a})):s.push(...await Ud({discoveryEntries:o.entries,sessionName:n,suiteInvocationId:o.suiteInvocationId,cwd:t.meta?.cwd,requestId:t.meta?.requestId,flags:t.flags,suiteArtifactsDir:o.suiteArtifactsDir,suiteTotal:o.total,runReplay:r,cleanupSession:i,finalizeAttempt:a})),{ok:!0,data:Kd(o.total,s,Date.now()-e)}}catch(e){let t=s(e);return L(t.code,t.message)}}async function Nd(e){let t=Pd(e),n=Fd(t),r=t.length-n.length,i=bu(e.meta?.requestId),a=await vd(e.flags,n,r);return{entries:t,runnable:n,shardPlan:a,suiteInvocationId:i,suiteArtifactsDir:Id(e,i),total:a?.total??t.length}}function Pd(e){return vu({inputs:e.positionals??[],cwd:e.meta?.cwd,platformFilter:e.flags?.platform,replayBackend:e.flags?.replayBackend})}function Fd(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function Id(e,t){return su({artifactsDir:typeof e.flags?.artifactsDir==`string`?e.flags.artifactsDir:void 0,cwd:e.meta?.cwd,suiteInvocationId:t})}function Ld(e){P({type:`replay-test-suite`,status:`start`,total:e.total,runnable:e.runnable.length,skipped:e.entries.length-e.runnable.length,artifactsDir:e.suiteArtifactsDir,shardMode:e.shardPlan?.mode,shardCount:e.shardPlan?.shardCount})}function Rd(e){let{entries:t,total:n}=e,r=[];for(let[e,i]of t.entries())i.kind===`skip`&&(P({type:`replay-test`,file:i.path,status:`skip`,index:e+1,total:n,message:i.message}),r.push({file:i.path,status:`skipped`,durationMs:0,reason:i.reason,message:i.message}));return r}async function zd(e){return(await Promise.allSettled(e.shards.map(async t=>await Vd({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[Bd(r,e.sessionName,t.reason)]:[]})}function Bd(t,n,r){let i=e(r);return{file:t.entries[0]?.entry.path??`shard-${t.shardIndex+1}`,session:Hd(n,t),status:`failed`,durationMs:0,attempts:1,error:{code:i.code,message:i.message,hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,details:i.details},shardIndex:t.shardIndex,shardCount:t.shardCount,deviceId:t.device.id,deviceName:t.device.name}}async function Vd(e){let{shard:t,sessionName:n}=e;return await Wd({...e,entries:t.entries,sessionName:Hd(n,t),shard:t})}function Hd(e,t){return`${e}:shard-${t.shardIndex+1}`}async function Ud(e){let{discoveryEntries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,flags:o,suiteArtifactsDir:s,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d}=e,f=[],p=0;for(let[e,m]of t.entries()){if(Qt(a))break;if(m.kind===`skip`){P({type:`replay-test`,file:m.path,status:`skip`,index:e+1,total:c,message:m.message}),f.push({file:m.path,status:`skipped`,durationMs:0,reason:m.reason,message:m.message});continue}p+=1;let t=await ed({entry:m,sessionName:n,suiteInvocationId:r,caseIndex:p-1,cwd:i,requestId:a,retries:Cu(o?.retries,m.metadata.retries),timeoutMs:Su(o?.timeoutMs,m.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d});if(f.push(t),Gd(t,o,a))break}return f}async function Wd(e){let{entries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,flags:o,suiteArtifactsDir:s,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f}=e,p=[];for(let[e,m]of t.entries()){if(Qt(a))break;let{entry:t,suiteIndex:h}=m,g=await ed({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:Cu(o?.retries,t.metadata.retries),timeoutMs:Su(o?.timeoutMs,t.metadata.timeoutMs),suiteArtifactsDir:s,suiteIndex:h,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f});if(p.push(g),Gd(g,o,a))break}return p}function Gd(e,t,n){return Qt(n)||t?.failFast===!0&&e.status===`failed`||Bu(e)}function Kd(e,t,n){let r=t.filter(e=>e.status===`passed`).length,i=t.filter(e=>e.status===`failed`),a=i.length,o=t.filter(e=>e.status===`skipped`).length,s=r+a,c=Ue(t.map(e=>e.status===`skipped`?void 0:e.snapshotDiagnostics));return{total:e,executed:s,passed:r,failed:a,skipped:o,notRun:Math.max(0,e-s-o),durationMs:n,failures:i,tests:t,...c?{snapshotDiagnostics:c}:{}}}function qd(e){let t=e.sessionStore.get(e.sessionName),n=Jd({failedIndex:e.failedIndex,actions:e.actions,planDigest:e.planDigest,repairHint:e.repairHint,sessionExists:t!==void 0});return t&&(Xd({session:t,resume:n,repairHint:e.repairHint,failedIndex:e.failedIndex,actions:e.actions}),e.sessionStore.set(e.sessionName,t)),n}function Jd(e){let{failedIndex:t,actions:n,planDigest:r,repairHint:i,sessionExists:a}=e,o=i===`record-and-heal`?t+1:t,s=Yd({failedIndex:t,actions:n,repairHint:i,sessionExists:a});return{allowed:!0,from:o,planDigest:r,...s===void 0?{}:{alternateFrom:s}}}function Yd(e){let{failedIndex:t,actions:n,repairHint:r,sessionExists:i}=e;if(r!==`caution`&&r!==`manual`)return;let a=t+1;if(!(a>n.length&&!i))return a}function Xd(e){let{session:t,resume:n,repairHint:r,failedIndex:i,actions:a}=e;t.pendingRecordAndHeal=Qd({resume:n,repairHint:r,failedIndex:i,actions:a,actionsCountAtDivergence:t.actions.length})}function Zd(e){e.pendingRecordAndHeal=void 0}function Qd(e){let{resume:t,repairHint:n,failedIndex:r,actions:i,actionsCountAtDivergence:a}=e;if(n===`record-and-heal`)return t.allowed?{expectedFrom:t.from,actionsCountAtDivergence:a}:void 0;if(!(n!==`caution`&&n!==`manual`)&&r===i.length)return{expectedFrom:r+1,actionsCountAtDivergence:a}}function $d(e){return JSON.stringify(ef(e))}function ef(e){if(Array.isArray(e))return e.map(ef);if(!e||typeof e!=`object`)return e;let t=e;return Object.fromEntries(Object.keys(t).sort().map(e=>[e,ef(t[e])]))}function tf(e){let t=$d(nf(e));return ki(`sha256`).update(t,`utf8`).digest(`hex`)}function nf(e){let{actions:t,actionLines:n,actionSourcePaths:r,metadata:i}=e;return{platform:i.platform??null,target:i.target??null,steps:t.map((e,t)=>rf(e,n[t]??null,r?.[t]??null))}}function rf(e,t,n){return{command:e.command,positionals:e.positionals??[],flags:e.flags??{},runtime:e.runtime??null,targetEvidence:e.targetEvidence??null,source:{path:n,line:t}}}function af(e,n){if(e)try{V.appendFileSync(e,`${JSON.stringify(t(n))}\n`)}catch(t){d({level:`warn`,phase:`replay_trace_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}}async function of(t){let{req:r,sessionName:i,action:a,scope:o,filePath:s,line:c,step:l,sourcePath:u,tracePath:d,invoke:f}=t,p=Me(a,o,{file:u??s,line:c}),m=Date.now();af(d,{type:`replay_action_start`,ts:new Date(m).toISOString(),replayPath:s,...u?{sourcePath:u}:{},line:c,step:l,command:p.command,positionals:De(p)??[]});let h;try{h=await cf({req:r,sessionName:i,resolved:p,sourceAction:a,scope:o,line:c,step:l,invoke:f})}catch(t){if(!(t instanceof n))throw t;h={ok:!1,error:e(t)}}let g=Date.now();return af(d,{type:`replay_action_stop`,ts:new Date(g).toISOString(),replayPath:s,...u?{sourcePath:u}:{},line:c,step:l,command:p.command,ok:h.ok,durationMs:g-m,resultTiming:h.ok?uf(h.data):void 0,errorCode:h.ok?void 0:h.error.code}),sf(h,u??s,c)}function sf(e,t,n){return e.ok||e.error.details?.replaySource!==void 0?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},replaySource:{path:t,line:n}}}}}async function cf(e){let{req:t,sessionName:n,resolved:r,sourceAction:i,invoke:a}=e,o=df(t.flags,r.flags),s=i.command===`fill`?Ae(ze(i)):void 0;return s&&(o.recordAs=s),await a(lf({token:t.token,session:n,flags:o,runtime:r.runtime,meta:t.meta,internal:{...t.internal,replayPlanStep:!0,...r.command===`open`?{resolvedSessionScope:t.internal?.resolvedSessionScope??Mr(t)}:{}}},r))}function lf(e,t){let n=t.positionals??[];return t.command===`gesture`?{...e,command:t.command,positionals:[],input:_e(n,e.flags?.pointerCount)}:t.command===`swipe`?{...e,command:t.command,positionals:[],input:de(n,{count:e.flags?.count,pauseMs:e.flags?.pauseMs,pattern:e.flags?.pattern})}:{...e,command:t.command,positionals:n}}function uf(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.timing;if(!(!t||typeof t!=`object`||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return t===`number`||t===`string`||t===`boolean`}))}function df(e,t){return ee(e,{...t??{}})}function ff(e){return yf(e.ok?mf(e.data):pf(e.error.details?.artifactPaths))}function pf(e){return Array.isArray(e)?e.filter(vf):[]}function mf(e){return e?[_f(e.path),_f(e.outPath),...hf(e.artifacts)].filter(vf):[]}function hf(e){return Array.isArray(e)?e.map(gf).filter(vf):[]}function gf(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;return _f(t.localPath)??_f(t.path)}function _f(e){return typeof e==`string`?e:void 0}function vf(e){return typeof e==`string`}function yf(e){return[...new Set(e.filter(bf))]}function bf(e){try{return V.statSync(e).isFile()}catch{return!1}}function xf(e){if(e.length===0)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],n=t!==void 0&&/^\d+$/.test(t)?t:null,r=h(n===null?e.slice():e.slice(0,-1));return!r||r.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:r.selectorExpression,selectorTimeout:n}}function Sf(e){let t=[],n=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];if(t.push(...n),Oe(e.command)){let n=Cf(e),r=n[0]??``;r&&!r.startsWith(`@`)&&t.push(n.join(` `))}if(e.command===`fill`){let n=e.positionals?.[0]??``;n&&!n.startsWith(`@`)&&Number.isNaN(Number(n))&&t.push(n)}if(e.command===`get`){let n=e.positionals?.[1]??``;n&&!n.startsWith(`@`)&&t.push(e.positionals.slice(1).join(` `))}if(e.command===`is`){let{split:n}=mt([...e.positionals]);n&&t.push(n.selectorExpression)}if(e.command===`wait`){let{selectorExpression:n}=xf([...e.positionals]);n&&t.push(n)}return mr(t).filter(e=>e.trim().length>0)}function Cf(e){let t=e.positionals;if(e.command!==`longpress`)return t;let n=t.at(-1);return t.length>1&&wf(n)?t.slice(0,-1):t}function wf(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}const Tf={id:0,"role-label":1,label:2,other:3};function Ef(e){let t=new Map;for(let n of e){let e=t.get(n.nodeIndex);(!e||Df(n.basis)<Df(e.basis))&&t.set(n.nodeIndex,n)}return[...t.values()].sort((e,t)=>Df(e.basis)-Df(t.basis)||e.nodeIndex-t.nodeIndex)}function Df(e){return Tf[e]}function Of(e){let{kind:t,targetEvidence:n,capture:r}=e;if(t===`identity-mismatch`)return`caution`;if(t===`identity-unverifiable`||!n||r.state!==`available`||!kf(n))return`manual`;let i=Af(n,r.nodes);return t===`selector-miss`?i?`record-and-heal`:`state-repair`:i?`record-and-heal`:`manual`}function kf(e){return e.ancestry.length>0?!0:e.scrollRegion!==void 0&&jf(e.scrollRegion)}function Af(e,t){let n=St(t),r=Nf(e.ancestry,n,t),i=e.scrollRegion;return i&&jf(i)?r&&Mf(i,n,t):r}function jf(e){return e.id!==void 0||e.label!==void 0}function Mf(e,t,n){return n.some(n=>Ei(Ti(n,t),e))}function Nf(e,t,n){return e.length===0?n.length>0:n.some(n=>{let r=Ct(n,t,e.length);return!r.broken&&lt(r.chain,e)})}const Pf=new WeakMap;function Ff(e){return{store:t=>If(e,t),finalize:(t,n)=>Lf({...e,evidence:t,projection:n})}}function If(e,t){let{sessionStore:n,sessionName:r}=e,i=n.get(r);if(!i)throw Error(`Internal observation session is no longer available.`);Lr(i,t),n.set(r,i);let a=i.snapshotGeneration;if(a===void 0)throw Error(`Internal observation did not establish a snapshot generation.`);let o={};return Pf.set(o,{sessionName:r,session:i,sessionCreatedAt:i.createdAt,snapshot:t,snapshotGeneration:a,runtimeRevision:Kn(i),refFrame:zf(i)}),{evidence:o,refsGeneration:a}}function Lf(e){let t=Pf.get(e.evidence);Pf.delete(e.evidence);let n=Vf(e.projection.refs);return n.size===0?{published:!1,reason:`empty`}:e.signal?.aborted===!0?{published:!1,reason:`cancelled`}:!t||!Rf(e,t)?{published:!1,reason:`stale-capture`}:e.projection.refsGeneration!==t.snapshotGeneration||!Hf(n,t.snapshot)?{published:!1,reason:`invalid-projection`}:(zr(t.session,n),{published:!0,refsGeneration:t.snapshotGeneration,refCount:n.size})}function Rf(e,t){let n=e.sessionStore.get(e.sessionName);return e.sessionName===t.sessionName&&n===t.session&&n.createdAt===t.sessionCreatedAt&&n.snapshot===t.snapshot&&n.snapshotGeneration===t.snapshotGeneration&&Kn(n)===t.runtimeRevision&&Bf(zf(n),t.refFrame)}function zf(e){return{state:e.refFrameState,scope:e.refFrameScope,tree:e.refFrameTree,generation:e.refFrameGeneration}}function Bf(e,t){return e.state===t.state&&e.scope===t.scope&&e.tree===t.tree&&e.generation===t.generation}function Vf(e){let t=new Set;for(let n of e){let e=n.startsWith(`@`)?n.slice(1):n,r=e.indexOf(`~`),i=r===-1?e:e.slice(0,r);i.length>0&&t.add(i)}return t}function Hf(e,t){let n=new Set(t.nodes.flatMap(e=>typeof e.ref==`string`?[e.ref]:[]));return[...e].every(e=>n.has(e))}function Uf(e){let{sessionStore:n,sessionName:r,divergence:i,responseLevel:a}=e,o,s,c=fe({divergence:i,level:a,writeOverflowArtifact:e=>{let i=t(e),a=Kf(n,r,i);return`artifactPath`in a&&(o=i,s=a.artifactPath),a}}),l=(o??c).screen;if(l.state!==`available`||l.refs.length===0)return e.evidence&&Ff({sessionStore:n,sessionName:r,...e.signal?{signal:e.signal}:{}}).finalize(e.evidence,{refsGeneration:l.state===`available`?l.refsGeneration:void 0,refs:[]}),c;if(!e.evidence)return Gf(s),Wf(c,`missing-evidence`);let u=Ff({sessionStore:n,sessionName:r,...e.signal?{signal:e.signal}:{}}).finalize(e.evidence,{refsGeneration:l.refsGeneration,refs:l.refs.map(e=>e.ref)});return u.published===!0?c:(Gf(s),Wf(c,u.reason))}function Wf(e,t){let{overflow:n,...r}=e;return{...r,screen:{state:`unavailable`,reason:`ref-publication-${t}`,hint:`The replay observation changed before its refs could be published. Take a new snapshot before targeting an element.`},suggestions:e.suggestions.map(({ref:e,...t})=>t),...e.targetBinding?{targetBinding:{...e.targetBinding,candidates:e.targetBinding.candidates.map(({ref:e,...t})=>t)}}:{}}}function Gf(e){if(e)try{V.unlinkSync(e)}catch{}}function Kf(e,t,n){try{let r=H.join(e.ensureSessionDir(t),`replay-divergence`);V.mkdirSync(r,{recursive:!0});let i=`${Date.now()}-step${n.step.index}.json`,a=H.join(r,i);return V.writeFileSync(a,`${JSON.stringify(n,null,2)}\n`),{artifactPath:a}}catch{return{artifactUnavailable:!0}}}async function qf(e){let{error:t,action:n,index:r,sourcePath:i,sourceLine:a,session:o,sessionName:s,sessionStore:c,logPath:l,responseLevel:u,scrubVars:d=[],planActions:f,planDigest:p,signal:m}=e,h=O(d),g={code:t.code,message:h(t.message),...t.hint?{hint:h(t.hint)}:{}},_=o?await Xf({session:o,sessionName:s,sessionStore:c,logPath:l,action:n}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},v=ep(_,h),y=_.state===`available`&&o?op({action:n,session:o,nodes:_.nodes,sanitize:h}):[],b=Of({kind:`action-failure`,targetEvidence:n.targetEvidence,capture:Jf(_)}),x=qd({failedIndex:r+1,actions:f,planDigest:p,repairHint:b,sessionStore:c,sessionName:s});return Uf({sessionStore:c,sessionName:s,divergence:{version:1,kind:`action-failure`,step:{index:r+1,source:{path:h(i),line:a}},action:h(Ge(n)),cause:g,screen:v,suggestions:y.slice(0,5),suggestionCount:y.length,resume:x,repairHint:b},responseLevel:u,evidence:_.state===`available`?_.evidence:void 0,...m?{signal:m}:{}})}function Jf(e){return e.state===`available`?{state:`available`,nodes:e.nodes}:{state:`unavailable`}}const Yf=[300,500,800,1200,2e3,3e3,4e3];async function Xf(e){let{session:t,sessionName:n,sessionStore:r,logPath:i,action:a,retryLaunchRace:o=!1}=e,s=Qf(a),c=Date.now()+12e3,l=await Zf({session:t,sessionName:n,sessionStore:r,logPath:i,flags:s});if(!o)return l.observation;for(let e of Yf){if(l.observation.state===`available`||!l.retryable)break;let a=c-Date.now();if(a<=0)break;await vt(Math.min(e,a)),l=await Zf({session:t,sessionName:n,sessionStore:r,logPath:i,flags:s})}return l.observation}async function Zf(e){let{session:t,sessionName:n,sessionStore:r,logPath:i,flags:a}=e;try{let e=(await _i({device:t.device,session:t,flags:a,logPath:i})).snapshot;if(gt(e.snapshotQuality))return{observation:{state:`unavailable`,reason:`sparse-snapshot`,hint:`The post-failure snapshot was sparse or unavailable; run snapshot -i to observe the current screen.`},retryable:!0};let o=Ff({sessionStore:r,sessionName:n}).store(e);return{observation:{state:`available`,nodes:e.nodes,refsGeneration:o.refsGeneration,evidence:o.evidence,appBundleId:t.appBundleId},retryable:!1}}catch(e){return{observation:{state:`unavailable`,reason:`capture-failed`,hint:`Post-failure snapshot capture failed (${e instanceof Error?e.message:String(e)}); the original replay failure is unaffected.`},retryable:_t(e)}}}function Qf(e){return{snapshotInteractiveOnly:$f(e)}}function $f(e){return sp(e.command)?cp(e).requiresRect:!0}function ep(e,t){if(e.state===`unavailable`)return{state:`unavailable`,reason:t(e.reason),hint:t(e.hint)};let{refs:n,truncated:r}=ip(e.nodes,t,e.appBundleId);return{state:`available`,refsGeneration:e.refsGeneration,refs:n,...r?{truncated:!0}:{}}}function tp(e){return!!ce(e,he(e.type??`Element`))||e.hittable===!0}function np(e,t){return t!==void 0&&e.bundleId!==void 0&&e.bundleId!==t&&e.hittable===!0}function rp(e,t){let n=ye(e,t),r=e.filter(e=>e.ref&&!n.has(e.ref)&&tp(e)),i=r.length>0?r:e.filter(e=>e.ref&&e.hittable===!0),a=i.filter(e=>e.interactionBlocked!==`covered`),o=a.length>0?a:i,s=[...o.filter(e=>np(e,t)),...o.filter(e=>!np(e,t))],c=s.slice(0,20);return{nodes:c,truncated:s.length>c.length}}function ip(e,t,n){let{nodes:r,truncated:i}=rp(e,n);return{refs:r.map(e=>{let n=he(e.type??`Element`),r=ce(e,n);return{ref:e.ref,role:t(n),...r?{label:t(r)}:{}}}),truncated:i}}function ap(e){let t=new Set(e.terms.map(e=>e.key));if(t.has(`id`))return`id`;let n=t.has(`role`),r=t.has(`label`)||t.has(`text`);return n&&r?`role-label`:r||t.has(`value`)?`label`:`other`}function op(e){let{action:t,session:n,nodes:r,sanitize:i}=e;if(!sp(t.command))return[];let a=Sf(t);return a.length===0?[]:lp({candidates:a,nodes:r,session:n,action:t,matching:cp(t),sanitize:i})}function sp(e){return Oe(e)||[`fill`,`get`,`is`,`wait`].includes(e)}function cp(e){let t=Oe(e.command);return{requiresRect:t||e.command===`fill`,allowDisambiguation:t||e.command===`fill`||e.command===`get`&&e.positionals?.[0]===`text`}}function lp(e){let{candidates:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=[];for(let e of t){let t=up({candidate:e,nodes:n,session:r,action:i,matching:a,sanitize:o});t&&s.push(t)}return Ef(s).map(e=>e.suggestion)}function up(e){let{candidate:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=x(t);if(!s)return;let c=ct(n,s,{platform:r.device.platform,requireRect:a.requiresRect,requireUnique:!0,disambiguateAmbiguous:a.allowDisambiguation});if(!c)return;let l=ap(c.selector);return{suggestion:dp({node:c.node,nodes:n,session:r,action:i,basis:l,sanitize:o}),basis:l,nodeIndex:c.node.index}}function dp(e){let{node:t,nodes:n,session:r,action:i,basis:a,sanitize:o}=e,s=pt(t,r.device.platform,{action:i.command===`fill`?`fill`:Oe(i.command)?`click`:`get`,nodes:n}),c=he(t.type??`Element`),l=ce(t,c);return{selector:o(s.join(` || `)),basis:a,...t.ref?{ref:t.ref}:{},role:o(c),...l?{label:o(l)}:{}}}function fp(e){return{...e,hint:e.hint??hp(e.details,`hint`),diagnosticId:e.diagnosticId??hp(e.details,`diagnosticId`),logPath:e.logPath??hp(e.details,`logPath`)}}function pp(e){let{error:t,action:n,step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c}=e;return mp({error:t,actionLabel:Ge(n),action:n.command,positionals:De(n)??[],step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c})}function mp(e){let{error:t,actionLabel:n,action:r,positionals:i,step:a,replayPath:o,artifactPaths:s,snapshotDiagnostics:c,divergence:l,scrubVars:u}=e;return{ok:!1,error:{code:`REPLAY_DIVERGENCE`,message:se(`Replay failed at step ${a} (${n}): ${t.message}`,u),hint:t.hint===void 0?void 0:se(t.hint,u),diagnosticId:t.diagnosticId,logPath:t.logPath,...t.retriable===void 0?{}:{retriable:t.retriable},...t.supportedOn===void 0?{}:{supportedOn:t.supportedOn},details:{..._p(t.details),replayPath:o,step:a,action:r,positionals:i,artifactPaths:s,...c?{snapshotDiagnostics:c}:{},divergence:l}}}}function hp(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}const gp=[`reason`,`retriable`,`supportedOn`];function _p(e){if(!e)return{};let t={};for(let n of gp)e[n]!==void 0&&(t[n]=e[n]);return t}async function vp(e){return await yp({...e,snapshotDiagnostics:je(e.snapshotDiagnosticSamples)})}async function yp(e){let{response:t,action:n,index:r,replayPath:i,sourcePath:a,sourceLine:o,artifactPaths:s=[],snapshotDiagnostics:c,scope:l,req:u,sessionName:d,sessionStore:f,logPath:p,planActions:m,planDigest:h}=e;if(t.ok)return t;let g=bp(t.error.details?.replaySource),_=Ne(l),v=fp(t.error),y=await qf({error:v,action:n,index:r,sourcePath:g?.path??a,sourceLine:g?.line??o,session:f.get(d),sessionName:d,sessionStore:f,logPath:p,responseLevel:u.meta?.responseLevel,scrubVars:_,planActions:m,planDigest:h,signal:Zt(u.meta?.requestId)});return pp({error:v,action:n,step:r+1,replayPath:i,artifactPaths:s,snapshotDiagnostics:c,divergence:y,scrubVars:_})}function bp(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=typeof t.path==`string`&&t.path.length>0?t.path:void 0,r=typeof t.line==`number`?t.line:void 0;if(!(n===void 0&&r===void 0))return{path:n,line:r}}function xp(e,t){return{...e??{},...t.platform!==void 0&&e?.platform===void 0?{platform:t.platform}:{},...t.target!==void 0&&e?.target===void 0?{target:t.target}:{}}}function Sp(e){return{platform:typeof e?.platform==`string`?e.platform:void 0,target:typeof e?.target==`string`?e.target:void 0}}function Cp(e,t,n,r,i){let a=e?.replayFrom,o=e?.replayPlanDigest;if(a===void 0&&o===void 0)return{ok:!0,value:0};if(a===void 0||o===void 0)return wp(`replay --from requires --plan-digest (and --plan-digest requires --from).`);let s=Tp({from:a,digest:o,planDigest:n,actionCount:t,pendingRecordAndHeal:r,sessionActionsLength:i});return s?wp(s):{ok:!0,value:a-1}}function wp(e){return{ok:!1,response:L(`INVALID_ARGS`,e)}}function Tp(e){let{from:t,digest:n,planDigest:r,actionCount:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e,s=[()=>Ep({from:t,actionCount:i,pendingRecordAndHeal:a}),()=>Dp({from:t,pendingRecordAndHeal:a,sessionActionsLength:o}),()=>Op(n,r)];for(let e of s){let t=e();if(t)return t}}function Ep(e){let{from:t,actionCount:n,pendingRecordAndHeal:r}=e,i=t===n+1&&r!==void 0&&r.expectedFrom===t;return Number.isInteger(t)&&t>=1&&(t<=n||i)?void 0:`replay --from ${t} is out of range for a ${n}-step plan.`}function Dp(e){let{from:t,pendingRecordAndHeal:n,sessionActionsLength:r}=e;if(!(n?.expectedFrom!==t||r!==n.actionsCountAtDivergence))return`replay --from ${t} continues a record-and-heal-shaped repair, but no corrective action was recorded in this repair segment; press the correct control via a blessed @ref from the divergence's screen.refs (recorded, no --no-record) — or, if your corrective action was a read (get/is/find/snapshot), re-run it with --record so it lands in the heal — before resuming with --from ${t}.`}function Op(e,t){if(e!==t)return`replay --plan-digest does not match the current plan digest; the script, its includes, or its platform-conditioned expansion changed since the divergence report was generated. Run a fresh full replay to get a new digest.`}function kp(e){let{recorded:t,token:n,nodes:r,platform:i,refLabel:a,requireRect:o,allowDisambiguation:s}=e,c=Ap({token:n,nodes:r,platform:i,refLabel:a,requireRect:o,allowDisambiguation:s}),l=St(r),u=st(t),d=Tt(c.matchedNodes,l,u,t.ancestry),f=d.filter(e=>Di(r,e)===t.sibling),p=d.filter(e=>Ei(Ti(e,l),t.scrollRegion)),m=wi(p)[t.viewportOrder]?.ref,h=dt({winnerRef:c.winnerRef,matchedRefs:c.matchedNodes.map(e=>e.ref),identitySetRefs:d.map(e=>e.ref),siblingMatchRefs:f.map(e=>e.ref),regionMemberRefs:p.map(e=>e.ref),viewportCandidateRef:m}),g=c.matchedNodes.find(e=>e.ref===c.winnerRef);return h.outcome===`verified`&&g?{verified:!0,winnerNode:g,matchCount:c.matchedNodes.length}:h.outcome===`verified`?{verified:!1,kind:`identity-unverifiable`,matchCount:c.matchedNodes.length,observedNode:void 0,candidateNodes:d.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Verification isolated a member that is not part of the matched-node domain (capture anomaly).`}:{verified:!1,...Np({classification:h,matchCount:c.matchedNodes.length,winnerNode:g,identitySet:d,byIndex:l,recorded:t})}}function Ap(e){let{token:t,nodes:n,platform:r,refLabel:i,requireRect:a,allowDisambiguation:o}=e;return t.startsWith(`@`)?jp(n,t,i,a):Mp(n,t,r,a,o)}function jp(e,t,n,r){let o=e=>e!==null&&(!r||!!e.rect),s=a(t),c=s?i(e,s):null;if(o(c))return{matchedNodes:[c],winnerRef:c.ref};let l=n?tt(e,n):null;return o(l)?{matchedNodes:[l],winnerRef:l.ref}:{matchedNodes:[],winnerRef:``}}function Mp(e,t,n,r,i){let a=x(t);if(!a)return{matchedNodes:[],winnerRef:``};let o=ct(e,a,{platform:n,requireRect:r,requireUnique:!0,disambiguateAmbiguous:i});return o?{matchedNodes:e.filter(e=>r&&!e.rect?!1:at(e,o.selector,n)),winnerRef:o.node.ref}:{matchedNodes:ut(e,a,{platform:n,requireRect:r})?.matchedNodes??[],winnerRef:``}}function Np(e){let{classification:t,matchCount:n,winnerNode:r,identitySet:i,byIndex:a,recorded:o}=e;switch(t.reason){case`selector-miss`:return{kind:`selector-miss`,matchCount:0,observedNode:void 0,candidateNodes:[],mismatches:[],causeCode:`SELECTOR_MISS`,causeMessage:`The recorded target no longer matches any current element.`};case`identity-set-empty`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Pp(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`The recorded selector/ref still matches, but nothing in the current tree carries the recorded identity.`};case`unique-but-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Pp(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`Exactly one current element carries the recorded identity, but the resolved target is a different element.`};case`signal-isolated-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Pp(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`A disambiguation signal (sibling or viewport position) isolated a different element than the resolved target.`};case`no-signal-isolation`:return{kind:`identity-unverifiable`,matchCount:n,observedNode:r,candidateNodes:i.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`${i.length} current elements carry the recorded identity and neither disambiguation signal isolated one.`}}}function Pp(e,t,n){let r=Oi(t),i=Ct(t,n,Math.max(e.ancestry.length,1)).chain;return[...Fp(e,r),...Rp(e.ancestry,i)].slice(0,5)}function Fp(e,t){let n=[];return e.id!==t.id&&n.push(`id: recorded=${e.id??`(none)`} observed=${t.id??`(none)`}`),e.role!==t.role&&n.push(`role: recorded=${e.role} observed=${t.role}`),e.label!==t.label&&n.push(`label: recorded=${e.label??`(none)`} observed=${t.label??`(none)`}`),n}function Ip(e){return e?`${e.role}${e.label?`/${e.label}`:``}`:`(missing)`}function Lp(e,t){return!t||t.role!==e.role?!0:e.label!==void 0&&t.label!==e.label}function Rp(e,t){for(let[n,r]of e.entries()){let e=t[n];if(Lp(r,e))return[`ancestry[${n}]: recorded=${Ip(r)} observed=${Ip(e)}`]}return[]}function zp(e){let t=e.positionals??[];if(e.command===`get`)return t[1];if(e.command===`is`)return mt(t).split?.selectorExpression;if(!Oe(e.command)&&e.command!==`fill`)return;let n=t[0];if(n!==void 0&&!(Vp(n)&&Vp(t[1])))return n}function Bp(e){let t=e.result?.refLabel;return typeof t==`string`&&t.length>0?t:void 0}function Vp(e){return e!==void 0&&e.trim().length>0&&!Number.isNaN(Number(e))}function Hp(e,t){let{recorded:n,action:r,step:i,sourcePath:a,sourceLine:o,replayPath:s,artifactPaths:c,sessionName:l,sessionStore:u,responseLevel:d,scrubVars:f,planActions:p,planDigest:m}=e,h=O(f),g={classification:t.kind,...t.matchCount===void 0?{}:{matchCount:t.matchCount},recorded:em(st(n),h),...t.observed?{observed:em(t.observed,h)}:{},mismatches:t.mismatches.slice(0,5).map(e=>h(e)),candidates:t.candidateNodes.slice(0,5).map(e=>tm(e,h))},_=Of({kind:t.kind,targetEvidence:n,capture:t.repairCapture}),v=qd({failedIndex:i,actions:p,planDigest:m,repairHint:_,sessionStore:u,sessionName:l}),y=Uf({sessionStore:u,sessionName:l,divergence:{version:1,kind:t.kind,step:{index:i,source:{path:h(a),line:o}},action:h(Ge(r)),cause:{code:t.causeCode,message:h(t.causeMessage),...t.causeHint?{hint:h(t.causeHint)}:{}},screen:t.screen,suggestions:[],suggestionCount:0,resume:v,repairHint:_,targetBinding:g},responseLevel:d,evidence:t.publicationEvidence,...e.signal?{signal:e.signal}:{}});return pp({error:{code:t.causeCode,message:t.causeMessage},action:r,step:i,replayPath:s,artifactPaths:c,divergence:y,scrubVars:f})}async function Up(e){let{action:t,scope:n,sourcePath:r,sourceLine:i,replayPath:a,step:o,sessionName:s,sessionStore:c,logPath:l,artifactPaths:u,responseLevel:d,planActions:f,planDigest:p,signal:m}=e,h=t.targetEvidence;if(!h)return{verified:!0};let g=c.get(s);if(!g)return{verified:!0};let v=Me(t,n,{file:r,line:i}),b=Ne(n),S=O(b),C={recorded:h,action:t,step:o,sourcePath:r,sourceLine:i,replayPath:a,artifactPaths:u,sessionName:s,sessionStore:c,responseLevel:d,scrubVars:b,planActions:f,planDigest:p,signal:m},ee=async()=>{let e=await Xf({session:g,sessionName:s,sessionStore:c,logPath:l,action:t});return Hp(C,{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`The recorded target evidence could not verify itself when it was captured (a structural capture anomaly), so replay cannot trust it before acting.`,screen:ep(e,S),publicationEvidence:Kp(e),repairCapture:Jf(e)})};if(_(t.command)===`post-resolution`)return y(v.positionals??[])?.kind===`selector`?h.verification===`unverifiable`?{verified:!1,response:await ee()}:{verified:!0,deferredLandmark:h}:{verified:!0};let w=zp(v);if(w===void 0||!w.startsWith(`@`)&&!x(w))return{verified:!0};if(h.verification===`unverifiable`)return{verified:!1,response:await ee()};let T=await Xf({session:g,sessionName:s,sessionStore:c,logPath:l,action:t,retryLaunchRace:!0});if(T.state!==`available`)return{verified:!1,response:Hp(C,{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Could not capture a fresh snapshot to verify the recorded target before acting (${T.reason}).`,causeHint:T.hint,screen:ep(T,S),repairCapture:Jf(T)})};let te=cp(t),E=kp({recorded:h,token:w,nodes:T.nodes,platform:g.device.platform,refLabel:Bp(t),requireRect:te.requiresRect,allowDisambiguation:te.allowDisambiguation});return E.verified?{verified:!0,guard:{expected:{identity:Oi(E.winnerNode),structural:ot(E.winnerNode,T.nodes)},matchCount:E.matchCount}}:{verified:!1,response:Hp(C,{kind:E.kind,matchCount:E.matchCount,observed:E.observedNode?Oi(E.observedNode):void 0,candidateNodes:E.candidateNodes,mismatches:E.mismatches,causeCode:E.causeCode,causeMessage:E.causeMessage,screen:ep(T,S),publicationEvidence:T.evidence,repairCapture:Jf(T)})}}function Wp(e){return!e.ok&&e.error.details?.reason===`replay_target_guard_mismatch`}async function Gp(e,t){let{action:n,scope:r,failedResponse:i,sessionName:a,sessionStore:o,logPath:s}=e,c=n.targetEvidence;if(!c)return i;let l=Ne(r),u=O(l),d=t(c,i.ok?void 0:i.error.details),f=o.get(a),p=f?await Xf({session:f,sessionName:a,sessionStore:o,logPath:s,action:n}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`};return Hp({recorded:c,action:n,step:e.step,sourcePath:e.sourcePath,sourceLine:e.sourceLine,replayPath:e.replayPath,artifactPaths:e.artifactPaths,sessionName:a,sessionStore:o,responseLevel:e.responseLevel,scrubVars:l,planActions:e.planActions,planDigest:e.planDigest,signal:e.signal},{kind:`identity-mismatch`,matchCount:d.matchCount,observed:d.observed,candidateNodes:[],mismatches:d.mismatches,causeCode:`IDENTITY_MISMATCH`,causeMessage:d.causeMessage,screen:ep(p,u),publicationEvidence:Kp(p),repairCapture:Jf(p)})}function Kp(e){return e.state===`available`?e.evidence:void 0}async function qp(e){return await Gp(e,(t,n)=>{let r=Zp(n?.observed),i=Qp(n?.expectedStructural,n?.observedStructural);return{matchCount:e.guard.matchCount,observed:r,mismatches:[...r?Fp(t,r):[],...i?[i]:[]],causeMessage:`Dispatch resolution (with occlusion/visibility guards) resolved a different element than pre-action verification isolated; the action was not sent.`}})}function Jp(e){return!e.ok&&e.error.details?.reason===`wait_landmark_identity_mismatch`}async function Yp(e){return await Gp(e,(e,t)=>{let n=Zp(t?.observed),r=Xp(t?.observedAncestry);return{matchCount:typeof t?.matchCount==`number`?t.matchCount:void 0,observed:n,mismatches:n?[...Fp(e,n),...Rp(e.ancestry,r)]:[],causeMessage:`Candidates matched the recorded wait selector during polling, but none carried the recorded landmark identity before the timeout; the wait did not report success.`}})}function Xp(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))return[];let e=n;if(typeof e.role!=`string`)return[];t.push({role:e.role,...typeof e.label==`string`?{label:e.label}:{}})}return t}function Zp(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.role==`string`)return{...typeof t.id==`string`?{id:t.id}:{},role:t.role,...typeof t.label==`string`?{label:t.label}:{}}}function Qp(e,t){let n=$p(e),r=$p(t);if(!(!n||!r)&&!(n.documentOrder===r.documentOrder&&n.sibling===r.sibling))return`position: recorded=doc${n.documentOrder}/sibling${n.sibling} observed=doc${r.documentOrder}/sibling${r.sibling}`}function $p(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(!(typeof t.documentOrder!=`number`||typeof t.sibling!=`number`))return{documentOrder:t.documentOrder,sibling:t.sibling}}function em(e,t){return{...e.id===void 0?{}:{id:t(e.id)},role:t(e.role),...e.label===void 0?{}:{label:t(e.label)}}}function tm(e,t){let n=he(e.type??`Element`),r=ce(e,n);return{...e.ref?{ref:e.ref}:{},role:t(n),...r?{label:t(r)}:{}}}function nm(e){let{req:t,sessionName:n,metadata:r,resolvedPath:i}=e,a=t.flags??{},o={AD_SESSION:n,AD_FILENAME:rm(t,i)};return am(o,`AD_PLATFORM`,a.platform??r.platform),am(o,`AD_TARGET`,a.target??r.target),am(o,`AD_DEVICE`,a.device),am(o,`AD_DEVICE_ID`,im(a)),om(o,`AD_SHARD_INDEX`,a.shardIndex),om(o,`AD_SHARD_COUNT`,a.shardCount),am(o,`AD_ARTIFACTS`,a.artifactsDir),o}function rm(e,t){let n=e.meta?.cwd??process.cwd();return H.relative(n,t)||t}function im(e){return typeof e.serial==`string`?e.serial:e.udid}function am(e,t,n){typeof n==`string`&&n.length>0&&(e[t]=n)}function om(e,t,n){typeof n==`number`&&(e[t]=String(n))}const sm=3e4,cm=1e3;function lm(t){let{scriptPath:r,env:i}=t,a=V.readFileSync(r,`utf8`),o=Object.create(null);try{Pi.runInNewContext(a,um(i,o),{filename:r,timeout:sm})}catch(t){let i=e(t);throw new n(i.code,`Maestro runScript failed: ${i.message}`,b({...i.details??{},hint:i.hint,diagnosticId:i.diagnosticId,logPath:i.logPath,retriable:i.retriable,supportedOn:i.supportedOn,scriptPath:r}),t instanceof Error?t:void 0)}return mm(o,r),Object.fromEntries(Object.entries(o).map(([e,t])=>[`output.${e}`,hm(t)]))}function um(e,t){return{...e,output:t,json:dm,http:{post:(e,t)=>pm(`POST`,e,t)}}}function dm(e){if(typeof e!=`string`)throw new n(`COMMAND_FAILED`,`Maestro runScript json() expected a string body, received ${typeof e}.`);if(e.trim().length===0)throw new n(`COMMAND_FAILED`,`Maestro runScript json() received an empty body.`,{hint:`Check the preceding HTTP response status and setup server output.`});try{return JSON.parse(e,fm)}catch(t){throw new n(`COMMAND_FAILED`,`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,cm)},t instanceof Error?t:void 0)}}function fm(e,t){return e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t}function pm(e,t,r){let i=c(process.execPath,[`-e`,`
4
4
  const fs = require('node:fs');
5
5
  const input = JSON.parse(fs.readFileSync(0, 'utf8'));
6
6
  if (typeof fetch !== 'function') {
@@ -21,8 +21,8 @@ fetch(input.url, {
21
21
  console.error(error && error.stack ? error.stack : String(error));
22
22
  process.exit(1);
23
23
  });
24
- `],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??``}),timeoutMs:Wp,allowFailure:!0});if(i.exitCode!==0)throw new n(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${$p(i.stderr)}`,{exitCode:i.exitCode,stderr:i.stderr});try{return JSON.parse(i.stdout)}catch(r){throw new n(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:i.stdout.slice(0,Gp),stderr:i.stderr.slice(0,Gp)},r instanceof Error?r:void 0)}}function Zp(e,t){for(let r of Object.keys(e))if(r.includes(`.`))throw new n(`INVALID_ARGS`,`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}function Qp(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function $p(e){let t=e.trim();return t.length>0?t.slice(0,Gp):`request process exited without stderr`}const em=`maestro-test-failure`;function tm(e,t={}){return new n(`COMMAND_FAILED`,e,{...t,reason:em})}function nm(e){return e instanceof n&&e.code===`COMMAND_FAILED`&&e.details?.reason===em}function rm(e,t,n){return new fm(am(im(t.resolve(e))),n).parse()}function im(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function am(e){let t=[],r=0;for(;r<e.length;){let i=e.slice(r),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){r+=a;continue}let o=om(i);if(!o)throw new n(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);t.push(o.value),r+=o.length}return t}function om(e){return sm(e)??cm(e)??lm(e)??um(e)??dm(e)}function sm(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function cm(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function lm(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function um(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function dm(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var fm=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let e=this.parseOr();if(this.peek())throw new n(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new n(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(e.type===`boolean`)return this.index+=1,e.value;if(e.type===`paren`&&e.value===`(`){this.index+=1;let e=this.parseOr();if(!this.consumeParen(`)`))throw new n(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new n(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let e=this.peek();if(e?.type!==`operator`||e.value!==`==`&&e.value!==`!=`)throw new n(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,e}consumeStringLiteral(){let e=this.peek();if(e?.type!==`string`)throw new n(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,e.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function pm(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function mm(e,t){return{...Cm(e,t),source:e.source}}function q(e,t,r){if(e===void 0)return;let i=r??oi[t]??{},a=hi(i),o;if(typeof e==`number`)o=e;else{let r=e.trim();if(r===``)throw new n(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);o=Number(r)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new n(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);return o}function hm(e,t,n,r){return q(e===void 0?t:n.resolve(String(e)),r)}function J(e){if(e?.aborted)throw Wt()}async function gm(e,t){if(e.include.kind===`commands`)return{kind:`program`,source:e.source,config:{},commands:e.include.commands};if(!t.loadProgram)throw new n(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return J(t.signal),t.signal?await t.loadProgram(e.include.path,e.source.path,t.signal):await t.loadProgram(e.include.path,e.source.path)}function _m(e,t){if(e.include.kind===`file`)return H.resolve(t?H.dirname(t):process.cwd(),e.include.path)}function vm(e){return e===void 0?void 0:H.resolve(e)}function ym(e,t){let r=_m(e,e.source.path);if(r&&t.has(r))throw new n(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function bm(e,t,r,i){let a=e.include.kind===`file`?vm(t.source.path):void 0,o=new Set([r,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new n(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function xm(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:rm(e.true,t,n.platform)}function Sm(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function Cm(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>Cm(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Cm(n,t)])):e}function wm(e,t){return y({appId:e.appId,env:e.env,generation:e.generation,invalidateObservation:e.invalidateObservation,source:t?.source,cachedObservation:e.cachedObservation,signal:e.signal})}function Tm(e){return y({env:e.env,generation:e.generation,cachedObservation:e.cachedObservation,signal:e.signal})}async function Em(e,t){let n=jm(await t.observe({condition:e.condition,timeoutMs:e.timeoutMs},Tm(e)),e.generation),r={kind:`selector`,selector:e.condition.selector,visible:n.visible,candidateCount:n.candidateCount,...n.ref?{ref:n.ref}:{},...e.condition.childOf?{childOf:e.condition.childOf}:{}};return{generation:e.generation,matched:Dm(e.condition,n),candidateCount:n.candidateCount,evidence:r}}function Dm(e,t){return e.kind===`visible`?t.matched&&t.visible:!t.matched||!t.visible}async function Om(e,t,n,r){let i=jm(await r.resolveTarget({selector:e,...t},wm(n,n.command)),n.generation);if(!i.matched||!i.visible||!i.rect)throw tm(`Maestro target did not resolve to a visible element.`,{selector:e,candidateCount:i.candidateCount});return{kind:`selector`,selector:e,query:{selector:e,...t},...i,rect:i.rect}}function km(e){let t={kind:`selector`,selector:e.selector,visible:e.visible,candidateCount:e.candidateCount,...e.ref?{ref:e.ref}:{},...e.query.childOf?{childOf:e.query.childOf}:{}};return{generation:e.generation,matched:e.matched&&e.visible,candidateCount:e.candidateCount,evidence:t}}function Am(e){if(!e||typeof e!=`object`)return!1;let t=e;return[`x`,`y`,`width`,`height`].every(e=>typeof t[e]==`number`&&Number.isFinite(t[e]))}function jm(e,t){return Mm(e,t),Nm(e),Pm(e),Fm(e),e}function Mm(e,t){if(e.generation!==t)throw new n(`COMMAND_FAILED`,`Maestro target evidence generation ${e.generation} does not match ${t}.`)}function Nm(e){if(!Number.isInteger(e.candidateCount)||e.candidateCount<0)throw new n(`COMMAND_FAILED`,`Maestro target evidence has an invalid candidate count.`)}function Pm(e){if(e.rect!==void 0&&!Am(e.rect)||e.viewport!==void 0&&!Am(e.viewport))throw new n(`COMMAND_FAILED`,`Maestro target evidence has invalid geometry.`)}function Fm(e){if(e.surfaceSignature!==void 0&&typeof e.surfaceSignature!=`string`)throw new n(`COMMAND_FAILED`,`Maestro target evidence has an invalid surface signature.`)}const Im=new Set(`^$\\.*+?()[]{}|`);function Lm(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function Rm(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if(Im.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!Im.has(i))return;t+=i,n+=1}return t}function zm(e,t){let n=[t.id===void 0?void 0:Vm(e.identifier,t.id),t.text===void 0?void 0:Hm(e,t.text),t.label===void 0?void 0:Vm(e.label,t.label)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function Bm(e){return e.matches.filter(t=>et({predicate:`visible`,node:t,nodes:e.nodes,platform:e.platform}).pass)}function Vm(e,t){let n=e??``;return h(n)===h(t)?!0:Lm(n,t)}function Hm(e,t){return[e.label,it(e),e.identifier].filter(e=>!!e).some(e=>Vm(e,t))}function Um(e,t,n,r,i){let a=Wm(e,t,n,i);if(!a)return;let{start:o,end:s}=Jm(a,n);return{gesture:{from:o,to:s,durationMs:r},viewport:a}}function Wm(e,t,n,r){let i=n===`up`||n===`down`,a=Bm({nodes:e.nodes,matches:e.nodes.filter(e=>Cr(e.type)),platform:r}),o=Lr(e.nodes)??Gm(a);if(!o||!$e(o))return;let s=a.flatMap(e=>{if(!$e(e.rect))return[];let t=Km(e.rect,o);return!t||(i?t.height<=t.width:t.width<t.height)?[]:[{node:e,viewport:t}]}),c=new Map(e.nodes.map(e=>[e.index,e])),l=new Map(s.map(e=>[e.node.index,e]));for(let n of e.nodes.filter(e=>zm(e,t))){let e=ni(n,c,{includeSelf:!0}),t=e?l.get(e.index):void 0;if(t)return t.viewport}return s.sort(qm)[0]?.viewport}function Gm(e){let t;for(let n of e)$e(n.rect)&&(!t||n.rect.width*n.rect.height>t.width*t.height)&&(t=n.rect);return t}function Km(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width)-n,a=Math.min(e.y+e.height,t.y+t.height)-r;return i>0&&a>0?{x:n,y:r,width:i,height:a}:void 0}function qm(e,t){return t.viewport.width*t.viewport.height-e.viewport.width*e.viewport.height}function Jm(e,t){let n=Y(e,.5,.5),r=B.scrollUntilVisibleSwipe.nearEdgeFraction,i=B.scrollUntilVisibleSwipe.farEdgeFraction;switch(t){case`up`:return{start:n,end:Y(e,.5,i)};case`down`:return{start:n,end:Y(e,.5,r)};case`left`:return{start:n,end:Y(e,i,.5)};case`right`:return{start:n,end:Y(e,r,.5)}}}async function Ym(e,t,r){let i=q(e.duration,`swipe.duration`);if(e.kind===`coordinates`){if(e.start.space!==e.end.space)throw new n(`INVALID_ARGS`,`Maestro swipe endpoints must use the same coordinate space.`);let a=e.start.space===`percent`?await r.resolveGestureViewport(wm(t,t.command)):void 0;return{authored:e,gesture:Zm(await Xm(e.start,t,r,a),await Xm(e.end,t,r,a),i),...a?{viewport:a}:{}}}if(e.kind===`screen`){let n=await r.resolveGestureViewport(wm(t,t.command)),{start:a,end:o}=Qm(n,e.direction,r.platform);return{authored:e,gesture:Zm(a,o,i),viewport:n}}let a=await Om(e.from,{purpose:`swipe`,timeoutMs:`optional`in t.command&&t.command.optional===!0?B.command.optionalTargetLookupTimeoutMs:B.command.targetLookupTimeoutMs},t,r),o=a.viewport??await r.resolveGestureViewport(wm(t,t.command)),{start:s,end:c}=$m(a,e.direction,o);return{authored:e,gesture:Zm(s,c,i),target:a,viewport:o}}async function Xm(e,t,n,r){if(e.space===`absolute`)return{x:e.x,y:e.y};let i=r??await n.resolveGestureViewport(wm(t,t.command));return{x:i.x+Math.trunc(i.width*e.x/100),y:i.y+Math.trunc(i.height*e.y/100)}}function Zm(e,t,n){return{from:e,to:t,durationMs:n??B.command.swipeDurationMs}}function Qm(e,t,n){if(t===`left`||t===`right`){let n=Ce(t,{referenceWidth:e.width,referenceHeight:e.height});return{start:{x:e.x+n.x1,y:e.y+n.y1},end:{x:e.x+n.x2,y:e.y+n.y2}}}let r=B.screenSwipe,i=Y(e,r.centerFraction,r.nearEdgeFraction),a=Y(e,r.centerFraction,r.farEdgeFraction),o=Y(e,r.centerFraction,r.downStartFraction),s=Y(e,r.centerFraction,r.upStartFraction[n]);return t===`up`?{start:s,end:i}:{start:o,end:a}}function Y(e,t,n){return{x:e.x+Math.trunc(e.width*t),y:e.y+Math.trunc(e.height*n)}}function $m(e,t,n){let r=Ct(e.rect),i=n.x+Math.trunc(n.width*B.targetSwipe.nearEdgeFraction),a=n.y+Math.trunc(n.height*B.targetSwipe.nearEdgeFraction),o=n.x+Math.trunc(n.width*B.targetSwipe.farEdgeFraction),s=n.y+Math.trunc(n.height*B.targetSwipe.farEdgeFraction);switch(t){case`up`:return{start:r,end:{x:r.x,y:a}};case`down`:return{start:r,end:{x:r.x,y:s}};case`left`:return{start:r,end:{x:i,y:r.y}};case`right`:return{start:r,end:{x:o,y:r.y}}}}const eh={launchApp:ah,stopApp:ah,openLink:ah,tapOn:sh,doubleTapOn:sh,longPressOn:sh,swipe:fh,inputText:ph,eraseText:ph,scroll:mh,scrollUntilVisible:mh,hideKeyboard:mh,pressKey:mh,back:mh,waitForAnimationToEnd:mh,takeScreenshot:_h,runScript:_h,assertVisible:vh,assertNotVisible:vh,extendedWaitUntil:vh},th={launchApp:!0,stopApp:!0,openLink:!0,tapOn:!0,doubleTapOn:!0,longPressOn:!0,swipe:!0,inputText:!0,eraseText:!0,scroll:!0,scrollUntilVisible:!0,hideKeyboard:!0,pressKey:!0,back:!0,waitForAnimationToEnd:!0,takeScreenshot:!1,runScript:!1,assertVisible:!1,assertNotVisible:!1,extendedWaitUntil:!1};function nh(e){return th[e.kind]}async function rh(e,t){let n=e.command;return await ih(n,e,t,wm(e,n))}function ih(e,t,n,r){let i=eh[e.kind];return i(e,t,n,r)}async function ah(e,t,n,r){switch(e.kind){case`launchApp`:return await X(n.launchApp,oh(e,t),r,`invalidate`);case`stopApp`:return await X(n.stopApp,{appId:e.appId??t.appId},r,`invalidate`);case`openLink`:return await X(n.openLink,{link:e.link},r,`invalidate`)}}function oh(e,t){return y({appId:e.appId??t.appId,stopApp:e.stopApp,clearState:e.clearState,arguments:e.arguments,launchArguments:e.launchArguments})}async function sh(e,t,n,r){switch(e.kind){case`tapOn`:return await ch(e,t,n,r);case`doubleTapOn`:{let i=await Eh(e.target,{purpose:`doubleTap`,timeoutMs:uh(e)},t,n),a=q(e.delay,`doubleTapOn.delay`)??B.command.repeatDelayMs;return await X(n.doubleTapOn,{target:i,delay:a},r,`invalidate`,i.resolution?km(i.resolution):void 0)}case`longPressOn`:{let i=await Eh(e.target,{purpose:`longPress`,timeoutMs:uh(e)},t,n);return await X(n.longPressOn,{target:i},r,`invalidate`,i.resolution?km(i.resolution):void 0)}}}async function ch(e,t,n,r){let i=await lh(e,t,n);return await X(n.tapOn,dh(e,i),r,`invalidate`,i.resolution?km(i.resolution):void 0)}async function lh(e,t,n){let r={purpose:`tap`,timeoutMs:uh(e),index:q(e.index,`tapOn.index`),childOf:e.childOf,allowAtomicSelectorDispatch:e.repeat===void 0&&e.delay===void 0,...e.retryTapIfNoChange===!0?{includeSurfaceSignature:!0}:{}};return await Eh(e.target,r,t,n)}function uh(e){return e.optional===!0?B.command.optionalTargetLookupTimeoutMs:B.command.targetLookupTimeoutMs}function dh(e,t){let n=q(e.repeat,`tapOn.repeat`),r=q(e.delay,`tapOn.delay`),i=n===void 0?r:r??B.command.repeatDelayMs;return y({target:t,retryTapIfNoChange:e.retryTapIfNoChange,repeat:n,delay:i})}async function fh(e,t,n,r){let i=await Ym(e.gesture,t,n);return await X(n.gesture,i.gesture,{...r,...i.viewport?{gestureViewport:i.viewport}:{}},`invalidate`,i.target?km(i.target):void 0)}async function ph(e,t,n,r){switch(e.kind){case`inputText`:return await X(n.inputText,y({text:e.text,label:e.label}),r,`invalidate`);case`eraseText`:return await X(n.eraseText,y({charactersToErase:q(e.charactersToErase,`eraseText.charactersToErase`)}),r,`invalidate`)}}async function mh(e,t,n,r){switch(e.kind){case`scroll`:return await X(n.scroll,{direction:`down`},r,`invalidate`);case`scrollUntilVisible`:return await X(n.scrollUntilVisible,hh(e),r,`invalidate`);case`hideKeyboard`:return await X(n.hideKeyboard,{},r,`invalidate`);case`pressKey`:return await X(n.pressKey,{key:e.key},r,`invalidate`);case`back`:return await X(n.back,{},r,`invalidate`);case`waitForAnimationToEnd`:return await X(n.waitForAnimationToEnd,gh(e),r,`preserve`)}}function hh(e){return{selector:e.element,direction:e.direction??`down`,timeoutMs:q(e.timeout,`scrollUntilVisible.timeout`)??B.command.scrollUntilVisibleTimeoutMs,durationMs:_i(B.command.scrollUntilVisibleSpeed)}}function gh(e){return y({timeoutMs:q(e.timeout,`waitForAnimationToEnd.timeout`)})}async function _h(e,t,n,r){switch(e.kind){case`takeScreenshot`:return bh(await n.takeScreenshot({path:e.path},r),[],void 0,r.generation);case`runScript`:return await X(n.runScript,y({file:e.file,env:e.env}),r,`preserve`)}}async function vh(e){throw new n(`COMMAND_FAILED`,`Maestro ${e.kind} must be executed by the observation engine.`)}async function X(e,t,n,r,i){let a=yh(n,r);return bh(await e(t,a),[],r===`preserve`?i:void 0,a.generation)}function yh(e,t){return t===`preserve`?e:(e.invalidateObservation(),{...e,generation:e.generation+1})}function bh(e,t,n,r){let i=e?.observation;return xh(i,r),{...Sh(n??i),...Ch(e?.outputEnv),...wh(t,e?.artifactPaths),...Th(e?.data),...e?.visualStabilityReached===void 0?{}:{visualStabilityReached:e.visualStabilityReached}}}function xh(e,t){if(!(!e||t===void 0||e.generation===t))throw new n(`COMMAND_FAILED`,`Maestro operation evidence generation ${e.generation} does not match ${t}.`)}function Sh(e){return e?{observation:e}:{}}function Ch(e){return e?{outputEnv:{...e}}:{}}function wh(e,t){let n=[...new Set([...e,...t??[]])];return n.length>0?{artifactPaths:n}:{}}function Th(e){return e&&Object.keys(e).length>0?{data:{...e}}:{}}async function Eh(e,t,n,r){if(e.space===`target`){let i=await Om(e.selector,t,n,r);return{authored:e,point:Ct(i.rect),resolution:i}}return{authored:e,point:await Xm(e,n,r)}}async function Dh(e){return await Oh(`tap`,async t=>{let n=H.join(t,`before.png`),r=H.join(t,`after.png`),i=await Ah(e,n);return await e.run({matchesCurrent:async()=>{if(!(!i||!await Ah(e,r)))return await kh(n,r,e.signal,`tap`)}})})}async function Oh(e,t){let n=await ki.mkdtemp(H.join(Ai.tmpdir(),`agent-device-maestro-${e}-`));try{return await t(n)}finally{try{await ki.rm(n,{recursive:!0,force:!0})}catch{}}}async function kh(e,t,n,r){try{let[i,a]=await Promise.all([ki.readFile(e),ki.readFile(t)]);Ph(n);let o=await Et(i,a,`Maestro screenshot`);return Ph(n),jh(o,r)}catch(e){Nh(e,n),u({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:r,result:`error`,error:e instanceof Error?e.message:String(e)}});return}}async function Ah(e,t){try{return await ki.rm(t,{force:!0}),Ph(e.signal),await e.capture(t),Ph(e.signal),!0}catch(t){return Nh(t,e.signal),!1}}function jh(e,t){if(e.status!==`compared`)return Mh(t,e.status,e),!1;let n=e.differencePercent<=B.command.waitForAnimationToEndDifferencePercent;return Mh(t,n?`stable`:`changed`,e),n}function Mh(e,t,n){u({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:e,result:t,first:n.first,second:n.second,...`differencePercent`in n?{differencePercent:n.differencePercent}:{}}})}function Nh(e,t){if(t?.aborted||Jt(e))throw Wt()}function Ph(e){if(e?.aborted)throw Wt()}async function Fh(e){Lh(e.timeoutMs),Ph(e.signal);let t=e.now()+e.timeoutMs;return await Oh(`animation`,async n=>{let r=H.join(n,`first.png`),i=H.join(n,`second.png`);for(;;){if(Ph(e.signal),await Ih(e,r,i))return!0;if(e.now()>=t)return!1}})}async function Ih(e,t,n){let r=[await Ah(e,t),await Ah(e,n)];return!r[0]||!r[1]?!1:await kh(t,n,e.signal,`animation`)===!0}function Lh(e){if(!Number.isFinite(e)||e<0)throw new n(`INVALID_ARGS`,`waitForAnimationToEnd timeout must be a non-negative number.`)}function Rh(e,t,n,r){let i=qh(e,e.nodes.filter(e=>zm(e,t)),r),a=Bm({nodes:e.nodes,matches:i.matches,platform:n});return{matches:i.matches,visible:a,ranked:zh(e.nodes,a,t,n),parentMatched:i.parentMatched}}function zh(e,t,n,r){if(r!==`ios`||!Hh(n))return t;let i=Qe(e);return t.filter(r=>{if(Kh(r))return!0;let a=t.filter(e=>e!==r&&Uh(r,e,n));return a.some(t=>Kh(t)&&rt(e,r,t,i))?!1:!a.some(t=>rt(e,t,r,i))})}function Bh(e,t){let n=t===void 0?e.find(Vh):e[t];return!n||!Vh(n)?null:{node:n,rect:n.rect}}function Vh(e){return $e(e.rect)}function Hh(e){return e.id!==void 0||e.label!==void 0||e.text!==void 0}function Uh(e,t,n){if(n.id!==void 0&&Gh(e.identifier)!==Gh(t.identifier)||n.label!==void 0&&Gh(e.label)!==Gh(t.label))return!1;if(n.text!==void 0){let n=Wh(e),r=new Set(Wh(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Wh(e){return[e.label,e.value,e.identifier].map(Gh).filter(e=>e!==void 0)}function Gh(e){if(e)return h(e)||void 0}function Kh(e){let t=ft(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}function qh(e,t,n){if(!n)return{matches:t,parentMatched:!0};let r=e.nodes.filter(e=>zm(e,n));if(r.length===0)return{matches:[],parentMatched:!1};let i=Qe(e.nodes);return{matches:t.filter(t=>r.some(n=>rt(e.nodes,t,n,i))),parentMatched:!0}}function Jh(e,t,n,r={}){let i=Rh(e,t.selector,n,t.childOf);if(!i.parentMatched)return{ok:!1,message:`Maestro childOf parent did not match.`,evidence:Qh(t,i.matches,[],void 0)};let{matches:a,ranked:o}=i,s=Bh(o,t.index),c=Qh(t,a,o,s?.node);if(!s)return Yh(t,a,o,c);let l=n===`ios`&&(r.interactiveBounds||t.allowAtomicSelectorDispatch)?br(e.nodes):void 0,u=r.interactiveBounds===!0?l?.sourceNodes.get(s.node.index)?.rect??s.rect:s.rect;return{ok:!0,node:s.node,rect:u,matches:o.length,dispatchCandidates:n===`ios`&&t.allowAtomicSelectorDispatch&&!t.childOf?Xh(e,t,{...s,rect:u},l):0,evidence:c}}function Yh(e,t,n,r){return t.length>0&&n.length===0?{ok:!1,message:`Maestro selector matched ${t.length} element(s), but none were visible.`,evidence:r}:{ok:!1,message:`Maestro selector did not match${e.index===void 0?``:` index ${e.index}`}.`,evidence:r}}function Xh(e,t,n,i){let a=Rh({...e,nodes:r((i??br(e.nodes)).nodes)},t.selector,`ios`).ranked;if(a.length!==1)return a.length;let o=Bh(a,void 0);return o&&o.node.hittable!==!1&&Zh(o.rect,n.rect)?1:0}function Zh(e,t){let n=Ct(e),r=Ct(t);return n.x===r.x&&n.y===r.y}function Qh(e,t,n,r){return y({selector:e.selector,childOf:e.childOf,matched:t.length>0,visible:n.length>0,candidateCount:t.length,ref:r?.ref})}const $h=B.observation.pollIntervalMs;async function eg(e,t){for(;;){Z(e.context.signal);try{return await e.snapshot(e.context)}catch(n){if(!gg(n)||(Z(e.context.signal),!await mg(e.dependencies,t,$h,e.context.signal)))throw n}}}function tg(e){return ng({...e,mode:e.query.purpose===`swipe`?`swipe`:`tap`})}function ng(e){let t=Gn(e.snapshot);return sg(Jh(e.snapshot,e.query,e.platform,{interactiveBounds:e.mode===`tap`}),e.snapshot,e.context.generation,t,e.query,e.platform,e.mode)}async function rg(e){hg(e.timeoutMs,`observation`);let t,n=e.dependencies.now()+e.timeoutMs;for(;;){Z(e.context.signal);let r=await eg(e,n),i=ng({query:{selector:e.condition.selector,childOf:e.condition.childOf},context:e.context,snapshot:r,platform:e.platform,mode:`observe`});if(t=i,Dm(e.condition,i))return i;if(e.dependencies.now()>=n)break;await mg(e.dependencies,n,$h,e.context.signal)}return Z(e.context.signal),yg(t)}async function ig(e){hg(e.timeoutMs,`scrollUntilVisible`);let t=e.dependencies.now()+e.timeoutMs,n,r;for(;;){Z(e.context.signal);let i=r??await eg(e,t);if(r=void 0,n=ng({query:{selector:e.selector},context:e.context,snapshot:i,platform:e.platform,mode:`observe`}),n.visiblePercentage===B.command.scrollUntilVisiblePercentage)return n;if(e.dependencies.now()>=t)break;let a=t-e.dependencies.now();a>0&&(r=await e.scroll(a,i))}return Z(e.context.signal),yg(n)}async function ag(e){hg(e.timeoutMs,`waitForAnimationToEnd`);let t=e.dependencies.now()+e.timeoutMs,n=e.initialSnapshot??await eg(e,t),r=_g(n);for(;;){Z(e.context.signal),await mg(e.dependencies,t,$h,e.context.signal);let i=await eg(e,t),a=_g(i);if(a===r)return{snapshot:i,signature:a};if(n=i,r=a,e.dependencies.now()>=t)return{snapshot:n,signature:r}}}function og(e){return e?{x:0,y:0,width:e.referenceWidth,height:e.referenceHeight}:void 0}function sg(e,t,n,r,i,a,o){if(!e.ok){let t=og(r);return{generation:n,matched:e.evidence.matched,visible:e.evidence.visible,candidateCount:e.evidence.candidateCount,...e.evidence.ref?{ref:e.evidence.ref}:{},...t?{viewport:t}:{}}}let s=lg({query:i,platform:a,mode:o,dispatchCandidates:e.dispatchCandidates}),c=og(r);return{generation:n,matched:!0,visible:!0,...c?{visiblePercentage:cg(e.rect,c)}:{},candidateCount:e.evidence.candidateCount,rect:e.rect,...e.evidence.ref?{ref:e.evidence.ref}:{},...c?{viewport:c}:{},...s?{dispatchSelector:s}:{},...i.includeSurfaceSignature?{surfaceSignature:_g(t)}:{}}}function cg(e,t){return!$e(e)||!$e(t)?0:nt(t,e)?100:Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))*100/(e.width*e.height)}function lg(e){let{query:t,platform:n,mode:r,dispatchCandidates:i}=e;if(!(!ug(t,n,r)||i!==1))return dg(t.selector)}function ug(e,t,n){return t===`ios`&&n===`tap`&&e.allowAtomicSelectorDispatch===!0&&e.index===void 0&&e.childOf===void 0}function dg(e){let t=Object.entries(e).filter(([,e])=>e!==void 0);if(t.length!==1)return;let[n,r]=t[0];if(!fg(n)||typeof r!=`string`)return;let i=Rm(r)?.trim();return i?{key:n,value:i}:void 0}function fg(e){return e===`id`||e===`label`||e===`text`}async function pg(e,t,n){try{await e.sleep(t,n)}catch(e){throw n?.aborted?Wt():e}Z(n)}async function mg(e,t,n,r){let i=t-e.now();return i<=0?!1:(await pg(e,Math.min(n,i),r),!0)}function Z(e){if(e?.aborted)throw Wt()}function hg(e,t){if(!Number.isFinite(e)||e<0)throw new n(`INVALID_ARGS`,`${t} timeout must be a non-negative number.`)}function gg(e){return e instanceof n&&e.details?.retriable===!0}function _g(e){return Oi(`sha256`).update(JSON.stringify([...e.nodes].sort((e,t)=>e.index-t.index).map(e=>({index:e.index,parentIndex:e.parentIndex,identifier:e.identifier??``,label:e.label??``,value:e.value??``,enabled:e.enabled??!1,selected:e.selected??!1,focused:e.focused??!1,bounds:vg(e.rect)})))).digest(`hex`)}function vg(e){if(e)return{left:Math.trunc(e.x),top:Math.trunc(e.y),right:Math.trunc(e.x+e.width),bottom:Math.trunc(e.y+e.height)}}function yg(e){if(e)return e;throw new n(`COMMAND_FAILED`,`Maestro observation completed without a snapshot result.`)}function bg(e){return xg(e)?Sg(e):Mg(e)?Ng(e):Eg(e)}function xg(e){return e.kind===`launchApp`||e.kind===`stopApp`||e.kind===`openLink`}function Sg(e){switch(e.kind){case`launchApp`:return Cg(e);case`stopApp`:return wg(e);case`openLink`:return Tg(e)}}function Cg(e){return{command:`open`,positionals:e.appId?[e.appId]:[],flags:{...e.relaunch?{relaunch:!0}:{},...e.clearState?{clearAppState:!0}:{},...e.launchArgs.length>0?{launchArgs:e.launchArgs}:{}}}}function wg(e){return{command:`close`,positionals:e.appId?[e.appId]:[],internal:{closeAppOnly:!0}}}function Tg(e){return{command:`open`,positionals:e.appId?[e.appId,e.link]:[e.link],...e.prewarmRunner?{flags:{maestro:{prewarmRunnerBeforeOpen:!0}}}:{}}}function Eg(e){switch(e.kind){case`typeText`:return{command:`type`,positionals:[e.text]};case`clickSelector`:return Dg(e);case`clickPoint`:return Og(e);case`swipe`:return kg(e);case`scroll`:return Ag(e);case`pressKey`:return jg(e)}}function Dg(e){return{command:`click`,positionals:[`${e.selector.key}=${JSON.stringify(e.selector.value)}`],flags:{...e.options,maestro:{allowNonHittableCoordinateFallback:!0,expectedTapPoint:e.expectedPoint}}}}function Og(e){return{command:`click`,positionals:[String(e.point.x),String(e.point.y)],flags:{...e.options}}}function kg(e){let{from:t,to:n,durationMs:r}=e.gesture;return{command:`gesture`,positionals:[],input:{kind:`pan`,origin:t,delta:{x:n.x-t.x,y:n.y-t.y},durationMs:r},flags:{postGestureStabilization:!1},internal:{gestureExecutionProfile:`endpoint-hold`,...e.viewport?{gestureViewport:e.viewport}:{}}}}function Ag(e){return{command:`scroll`,positionals:[e.direction],...e.durationMs===void 0?{}:{input:{direction:e.direction,durationMs:e.durationMs}},flags:{postGestureStabilization:!1}}}function jg(e){return e.key===`back`||e.key===`home`?{command:e.key,positionals:[]}:{command:`keyboard`,positionals:[e.key]}}function Mg(e){return e.kind===`screenshot`||e.kind===`snapshot`}function Ng(e){switch(e.kind){case`screenshot`:return{command:`screenshot`,positionals:[e.path],...e.stabilize===!1||e.captureBackend===`runner`?{flags:{...e.stabilize===!1?{screenshotNoStabilize:!0}:{},...e.captureBackend===`runner`?{maestro:{screenshotCaptureBackend:`runner`}}:{}}}:{}};case`snapshot`:return{command:`snapshot`,positionals:[],flags:{noRecord:!0}}}}async function Pg(e,t){let n=bg(t),{input:r,flags:i,internal:a,...o}=e.baseReq,s=Fg(i,n.flags??{}),c=n.internal===void 0?a:{...a,...n.internal},l=await e.invoke(y({...o,command:n.command,positionals:n.positionals,input:n.input,flags:s,internal:c}));if(!l.ok)throw Vg(l);return l.data}function Fg(e,t){let n=e?.maestro===void 0&&t.maestro===void 0?void 0:{...e?.maestro,...t.maestro},r=y({...e,...t,maestro:n});return Object.keys(r).length>0?r:void 0}function Ig(e){return e?e.kind===`scalar`?[String(e.value)]:e.kind===`list`?e.values.map(String):Object.entries(e.values).flatMap(([e,t])=>[e,String(t)]):[]}function Lg(e,t){return{generation:t.generation,matched:t.matched&&t.visible,candidateCount:t.candidateCount,evidence:{kind:`selector`,selector:e,visible:t.visible,candidateCount:t.candidateCount,...t.ref?{ref:t.ref}:{}}}}function Rg(e){if(!e)return[];let t=[];if(typeof e.path==`string`&&t.push(e.path),Array.isArray(e.artifactPaths)&&t.push(...e.artifactPaths.filter(e=>typeof e==`string`)),Array.isArray(e.artifacts))for(let n of e.artifacts)typeof n.localPath==`string`?t.push(n.localPath):typeof n.path==`string`&&t.push(n.path);return[...new Set(t)]}function zg(e,t,r){if(H.isAbsolute(e))return e;let i=t.source?.path??r;if(!i)throw new n(`INVALID_ARGS`,`Maestro runScript file paths require a source path.`);return H.resolve(H.dirname(i),e)}function Bg(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function Vg(e){let t=e.error,r=y({...t.details??{},hint:t.hint??Hg(t.details,`hint`),diagnosticId:t.diagnosticId??Hg(t.details,`diagnosticId`),logPath:t.logPath??Hg(t.details,`logPath`),retriable:t.retriable??Ug(t.details,`retriable`),supportedOn:t.supportedOn??Hg(t.details,`supportedOn`)});return new n(t.code,t.message,Object.keys(r).length?r:void 0)}function Hg(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function Ug(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}function Wg(e){let t,r,i,a,o,s=0,c=0,l=async r=>{c+=1;let i=await Pg(e,{kind:`snapshot`});if(!i||!Array.isArray(i.nodes))throw new n(`COMMAND_FAILED`,`Maestro snapshot did not return node data.`);let a=i;return t={generation:r.generation,snapshot:a},a};return{capture:async e=>{if(r?.generation===e.generation){let n=r.snapshot;return r=void 0,t={generation:e.generation,snapshot:n},n}return r=void 0,await l(e)},bindObservation:e=>{if(t?.generation!==e.generation)return e;let n=`maestro-observation-${++s}`;return t.observationIdentity=n,{...e,identity:n}},reuseObservation:e=>{if(e.cachedObservation?.generation===e.generation&&e.cachedObservation.identity!==void 0&&t?.generation===e.generation&&e.cachedObservation.identity===t.observationIdentity)return t.snapshot},readMetrics:()=>({hierarchyCaptures:c}),invalidate:e=>{i=t?.generation===e-1?{generation:e,snapshot:t.snapshot}:void 0,t=void 0,r=void 0},requireStability:e=>{o=e,a=i?.generation===e?i:void 0,i=void 0,r=void 0},consumeStabilityFromVisualWait:e=>{if(o!==void 0){if(o!==e.generation)throw new n(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${e.generation}.`);o=void 0,a=void 0,i=void 0,r=void 0}},prime:(e,t)=>{r={generation:e,snapshot:t}},settlePending:async i=>{if(o===void 0)return;if(o!==i.generation)throw new n(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${i.generation}.`);let s=t?.generation===i.generation?t.snapshot:a?.snapshot,c=await ag({timeoutMs:vi,context:i,snapshot:l,dependencies:e.dependencies,...s?{initialSnapshot:s}:{}});o=void 0,a=void 0,r={generation:i.generation,snapshot:c.snapshot}}}}function Gg(e){let t=Wg(e),r={screenshotCaptures:0,tapRetries:0},i=e.platform,a=t=>(t.kind===`screenshot`&&(r.screenshotCaptures+=1),Pg(e,t)),o=async(e,n,r=`none`)=>{t.invalidate(n.generation);try{return await e()}finally{r===`deferred`&&t.requireStability(n.generation)}},s=async(e,t,n=`none`)=>await o(()=>a(e),t,n),c=async(n,r)=>{await s({kind:`typeText`,text:n},r);let i=await ag({timeoutMs:vi,context:r,snapshot:t.capture,dependencies:e.dependencies});t.prime(r.generation,i.snapshot)};return{operations:{platform:i,resolveTarget:async(n,r)=>await Kg({input:n,context:r,snapshots:t,options:e}),observe:async(n,r)=>await rg({condition:n.condition,timeoutMs:n.timeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies,platform:i}),resolveGestureViewport:async t=>{let r=await e.dependencies.resolveGestureViewport(t);if(!r)throw new n(`COMMAND_FAILED`,`Unable to resolve Maestro gesture viewport.`);return r},launchApp:async(e,t)=>{let n=e.appId??t.appId,r=[...Ig(e.arguments),...Ig(e.launchArguments)],i=e.clearState===!0,a=!i&&e.stopApp!==!1;await s({kind:`launchApp`,...n?{appId:n}:{},relaunch:a,clearState:i,launchArgs:r},t,`deferred`)},stopApp:async(e,t)=>{let n=e.appId??t.appId;await s({kind:`stopApp`,...n?{appId:n}:{}},t)},openLink:async(e,t)=>{await s({kind:`openLink`,...t.appId?{appId:t.appId}:{},link:e.link,prewarmRunner:i===`ios`},t,`deferred`)},tapOn:async(n,i)=>await Xg(e,t,r,n.target,i,{click:{count:n.repeat,intervalMs:n.delay},retryIfNoChange:n.retryTapIfNoChange===!0}),doubleTapOn:async(t,n)=>{await o(()=>r_(e,t.target.point,y({doubleTap:!0,intervalMs:t.delay})),n,`deferred`)},longPressOn:async(t,n)=>{await o(()=>r_(e,t.target.point,{holdMs:B.command.longPressDurationMs}),n,`deferred`)},gesture:async(e,t)=>{let n=await s({kind:`swipe`,gesture:e,...t.gestureViewport?{viewport:t.gestureViewport}:{}},t,`deferred`);return n?{data:n}:void 0},inputText:async(e,t)=>await c(e.text,t),eraseText:async(e,t)=>await c(`\b`.repeat(e.charactersToErase??B.command.eraseTextMaxCharacters),t),scroll:async(e,t)=>{await s({kind:`scroll`,direction:e.direction},t,`deferred`)},scrollUntilVisible:async(n,r)=>{let a=await ig({selector:n.selector,direction:n.direction,timeoutMs:n.timeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies,platform:i,scroll:async(a,o)=>{let c=Um(o,n.selector,n.direction,n.durationMs,i);return await s(c?{kind:`swipe`,...c}:{kind:`scroll`,direction:n.direction,durationMs:n.durationMs},r),(await ag({timeoutMs:Math.min(vi,a),context:r,snapshot:t.capture,dependencies:e.dependencies})).snapshot}});if(a.visiblePercentage!==B.command.scrollUntilVisiblePercentage)throw tm(`Maestro scrollUntilVisible target did not become visible.`,{selector:n.selector,timeoutMs:n.timeoutMs});return{observation:t.bindObservation(Lg(n.selector,a))}},pressKey:async(e,t)=>{await s({kind:`pressKey`,key:e.key},t,`deferred`)},back:async(e,t)=>{await s({kind:`pressKey`,key:`back`},t,`deferred`)},hideKeyboard:async(e,t)=>{await s({kind:`pressKey`,key:`dismiss`},t,`deferred`)},waitForAnimationToEnd:async(t,n)=>({visualStabilityReached:await Fh({timeoutMs:t.timeoutMs??B.command.waitForAnimationToEndTimeoutMs,now:e.dependencies.now,signal:n.signal,capture:async t=>{await a({kind:`screenshot`,path:t,stabilize:!1,...e.platform===`ios`?{captureBackend:`runner`}:{}})}})}),takeScreenshot:async e=>({artifactPaths:Rg(await a({kind:`screenshot`,path:e.path}))}),runScript:async(t,n)=>({outputEnv:Kp({scriptPath:zg(t.file,n,e.sourcePath),env:{...n.env,...t.env?Bg(t.env):{}}})})},snapshots:t,readMetrics:()=>({...t.readMetrics(),...r})}}async function Kg(e){let{input:t,context:n,snapshots:r,options:i}=e,a=i.dependencies.now()+t.timeoutMs,o=e.allowObservationReuse===!1?void 0:r.reuseObservation(n);for(;;){let e=i.dependencies.now(),s=o!==void 0;o??=await eg({context:n,snapshot:r.capture,dependencies:i.dependencies},a);let c=tg({query:t,context:n,snapshot:o,platform:i.platform});if(Jg(c,s))return c;if(o=void 0,!s){if(e>=a)return c;await mg(i.dependencies,a,$h,n.signal)}}}function qg(e){return e.matched&&e.visible&&e.rect!==void 0}function Jg(e,t){return qg(e)?!t||e.dispatchSelector!==void 0:!1}function Yg(e){let{operations:t,snapshots:n,readMetrics:r}=Gg(e);return{execute:async e=>{let r=wm(e,e.command),i=e.command.kind===`waitForAnimationToEnd`;nh(e.command)&&!i&&await n.settlePending(r);let a=await rh(e,t);return i&&a.visualStabilityReached===!0&&n.consumeStabilityFromVisualWait(r),delete a.visualStabilityReached,a},observe:async e=>{let r=await Em(e,t);return n.bindObservation(r)},readMetrics:r}}async function Xg(e,t,n,r,i,a){let o=async()=>await e_(e,t,r,i,a.click);if(!a.retryIfNoChange){try{await o()}finally{t.requireStability(i.generation)}return}if(e.platform===`ios`){await Dh({signal:i.signal,capture:async t=>{n.screenshotCaptures+=1,await Pg(e,{kind:`screenshot`,path:t,stabilize:!1,captureBackend:`runner`})},run:async o=>await Zg(e,t,n,r,i,a.click,o)});return}await Zg(e,t,n,r,i,a.click)}async function Zg(e,t,n,r,i,a,o){let s=async()=>await e_(e,t,r,i,a),c=await Qg(r,t,i,o),l=async()=>await ag({timeoutMs:vi,context:i,snapshot:t.capture,dependencies:e.dependencies});try{let e=await $g({baselineSignature:c,screenshotBaseline:o,dispatch:s,settle:l,onRetry:()=>{n.tapRetries+=1}});t.prime(i.generation,e.snapshot)}catch(e){throw t.requireStability(i.generation),e}}async function Qg(e,t,n,r){if(e.resolution?.surfaceSignature)return e.resolution.surfaceSignature;if(!r)return _g(await t.capture(n))}async function $g(e){await e.dispatch();let t=await e.settle(),n=1;for(;(e.baselineSignature===void 0||t.signature===e.baselineSignature)&&n<B.command.retryTapMaxAttempts&&!(e.screenshotBaseline&&await e.screenshotBaseline.matchesCurrent()!==!0);)e.onRetry(),await e.dispatch(),n+=1,t=await e.settle();return t}async function e_(e,t,n,r,i){let a=n.resolution,o=a?.dispatchSelector;if(o&&n.point){t.invalidate(r.generation);try{await t_(e,o,n.point,i);return}catch(n){if(!n_(n))throw n;let o=await Kg({input:a.query,context:r,snapshots:t,options:e,allowObservationReuse:!1});if(!qg(o))throw n;t.invalidate(r.generation),await r_(e,Ct(o.rect),i);return}}t.invalidate(r.generation),await r_(e,n.point,i)}async function t_(e,t,n,r){u({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`selector`,selectorKey:t.key,expectedPoint:n}}),await Pg(e,{kind:`clickSelector`,selector:t,expectedPoint:n,options:r})}function n_(e){let t=s(e).code;return t===`AMBIGUOUS_MATCH`||t===`ELEMENT_NOT_FOUND`||t===`ELEMENT_OFFSCREEN`}async function r_(e,t,r){if(!t)throw new n(`COMMAND_FAILED`,`Maestro target did not resolve to a point.`);u({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`point`,point:t}}),await Pg(e,{kind:`clickPoint`,point:t,options:r})}function i_(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return Oi(`sha256`).update(Jd(t),`utf8`).digest(`hex`)}function a_(e={},t={}){let r={...t},i=o_(e),a=[],o=new Map,s,c=0,l;return{get values(){return u()},get generation(){return c},get observation(){return l?.generation===c?l:void 0},get expandedVariables(){return Object.fromEntries(o)},enter(e={}){let t=d(e);return a.push(t),s=void 0,()=>{if(a.pop()!==t)throw new n(`COMMAND_FAILED`,`Maestro environment scopes were left out of order.`);s=void 0}},merge(e){i={...i,...e},s=void 0},recordObservation(e){if(e.generation!==c)throw new n(`COMMAND_FAILED`,`Maestro observation generation ${e.generation} does not match ${c}.`);l=e},invalidateObservation(){c+=1,l=void 0},resolve(e){return s_(e,u(),f)},resolveDeferred(e){return s_(e,u(),void 0,new Set,!1)}};function u(){return s||(s={...a.reduce((e,t)=>({...e,...t}),{...i}),...r},s)}function d(e){let t=o_(e),n={};for(let[e,i]of Object.entries(t))n[e]=s_(i,{...u(),...t,...n,...r},void 0,new Set,!1);return n}function f(e,t){o.set(e,t)}}function o_(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function s_(e,t,r,i=new Set,a=!0){let o=e.replace(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,o)=>{if(!Object.hasOwn(t,o)){if(!a)return e;throw new n(`INVALID_ARGS`,`Maestro variable "${o}" is not defined.`)}if(i.has(o)){if(!a)return e;throw new n(`INVALID_ARGS`,`Maestro variable "${o}" has a cyclic reference.`)}let s=s_(t[o],t,r,new Set([...i,o]),a);return r?.(o,s),s});return a&&c_(o),o}function c_(e){for(let t of e.matchAll(/\$\{[^{}]*\}/g))if(!l_(t[0]))throw new n(`INVALID_ARGS`,`Maestro interpolation "${t[0]}" is unresolved or unsupported.`)}function l_(e){return/^\$\{\s*maestro\.platform\s*(?:==|!=)\s*(['"]).*\1(?:\s*(?:&&|\|\|).*)?\s*\}$/.test(e)}async function u_(e,t){J(t.signal);let n=vm(e.source.path),r={options:t,context:a_(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await d_(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function d_(e,t,n,r,i){J(i.options.signal);let a=S_(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await p_(s,a,o,e.source.path??r,i));return n}finally{s()}}async function f_(e,t,n,r,i){let a=[];for(let o of e)a.push(...await p_(o,t,n,r,i));return a}async function p_(e,t,n,r,i){J(i.options.signal);let a=C_(e,r);switch(a.kind){case`runFlow`:{let e=h_(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await m_(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[b_(a,t,n,o)]}case`repeat`:return[b_(a,t,n,await f_(a.commands,t,n,r,i))];case`retry`:return[b_(a,t,n,await f_(a.commands,t,n,r,i))];default:return[y_(a,t,n)]}}async function m_(e,t,n,r,i){let a=__(e,i.context),o=ym(a,i.activeIncludePaths),s=await gm(a,i.options);J(i.options.signal);let c=bm(a,s,o,i.activeIncludePaths),l=S_(t,e.env),u=i.context.enter(e.env);try{return await d_(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function h_(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:g_(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function g_(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return v_(t.context.resolveDeferred(e))?`opaque`:rm(e,t.context,t.options.platform)?void 0:`omit`}function __(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function v_(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function y_(e,t,n){return y({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function b_(e,t,n,r){return y({kind:`opaque`,command:x_(e),source:e.source,scopes:t,body:r,appId:n})}function x_(e){switch(e.kind){case`runFlow`:return y({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return{kind:e.kind,source:e.source,times:e.times};case`retry`:return y({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function S_(e,t){return t===void 0?e:[...e,t]}function C_(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function w_(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await u_(e,t),a=T_(t.runtimeHints),o=y({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=i_(o);return E_({...o,digest:s})}function T_(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function E_(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))E_(t);return Object.freeze(e)}function D_(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`)return{allowed:!1,reason:`step ${t+1} (runScript) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function O_(e,t={}){let r=D_(e,t);if(!r.allowed)throw new n(`INVALID_ARGS`,r.reason);return r.startIndex}function k_(e,t){if(!Number.isInteger(t)||t<0||t>e.total)throw new n(`INVALID_ARGS`,`Maestro replay startIndex ${t} is out of range for a ${e.total}-step plan.`);return t}async function A_(e,t){J(t.options.signal);try{return await W_(e,t.context,async()=>await j_(e,t))}catch(t){throw G_(t,e)}}async function j_(e,t){if(e.kind===`command`)return await M_(e.command,e.appId,t);await L_(e,t)}async function M_(e,t,n){try{return await F_(e,t,n)}catch(t){if(J(n.options.signal),!P_(e)||!nm(t))throw t;n.warnings.push(N_(e,t)),n.skipped+=1;return}}function N_(e,t){let r=`${e.source.path?`${e.source.path}:`:``}line ${e.source.line}`,i=t instanceof n?t.message:String(t);return`Optional Maestro ${e.kind} skipped at ${r}: ${i}`}function P_(e){return`optional`in e&&e.optional===!0}async function F_(e,t,n){let r=mm(e,n.context);switch(r.kind){case`assertVisible`:await V_({kind:`visible`,selector:r.target,childOf:r.childOf},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await V_({kind:`notVisible`,selector:r.target,childOf:r.childOf},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`extendedWaitUntil`:await V_(U_(r),q(r.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await I_(r,t,n)}}async function I_(e,t,n){let r=y({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return J(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function L_(e,t){let n=mm(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await B_(n.when,t)){t.skipped+=1;return}t.executed+=1,await R_(e.body,t);return;case`repeat`:{let r=hm(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)J(t.options.signal),await R_(e.body,t);return}case`retry`:{let r=Math.min(hm(n.maxRetries,1,t.context,`retry.maxRetries`),B.control.retryMaxRetries);t.executed+=1,await z_(e.body,r,t);return}}}async function R_(e,t){for(let n of e)await A_(n,t)}async function z_(e,t,r){let i;for(let n=0;n<=t;n+=1){J(r.options.signal);try{await R_(e,r);return}catch(t){if(J(r.options.signal),!nm(q_(t)))throw t;i=G_(t,e[0])}}throw i||new n(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function B_(e,t){if(!xm(e,t.context,t.options))return!1;for(let n of Sm(e))if(J(t.options.signal),!(await H_(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function V_(e,t,n){if(!(await H_(e,t,n)).matched)throw tm(`Maestro ${e.kind} condition did not match.`)}async function H_(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return J(n.options.signal),n.context.recordObservation(i),i}function U_(e){if(e.visible)return{kind:`visible`,selector:e.visible};if(e.notVisible)return{kind:`notVisible`,selector:e.notVisible};throw new n(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function W_(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function G_(e,t){if(K_(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:J_(e,t?.command),source:n,...t?{command:t.command}:{}}}function K_(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function q_(e){return K_(e)?e.error:e}function J_(e,t){if(!(e instanceof n)||!t||/\bline \d+\b/.test(e.message))return e;let r=t.source.path?`${t.source.path}:`:``;return new n(e.code,`${e.message} (${r}line ${t.source.line})`,e.details)}async function Y_(e,t,r={}){J(r.signal);let i=r.startIndex??0;if(!Number.isInteger(i)||i<0||i>e.total)throw new n(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${e.total}-step plan.`);let a={plan:e,port:t,options:r,context:a_(r.defaults,r.env?{...r.env}:{}),timing:yi,artifacts:new Set,warnings:[],executed:e.compatibility.staticallyExecutedControls,skipped:e.compatibility.staticallySkippedControls};for(let t=i;t<e.steps.length;t+=1)try{await X_(e.steps[t],t,a)}catch(e){throw q_(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function X_(e,t,n){J(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};Q_(()=>n.options.observer?.commandStarted?.(s));try{let t=await A_(e,n);J(n.options.signal),Q_(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Z_(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=G_(t,e);throw Q_(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Z_(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts],expandedVariables:n.context.expandedVariables})),o}}function Z_(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries}}}function Q_(e){try{e?.()}catch{}}async function $_(e,t,n={}){let r=ev(e,n);return await Y_(e,t,{...n,startIndex:r})}function ev(e,t){return t.from!==void 0||t.planDigest!==void 0?O_(e,{from:t.from,planDigest:t.planDigest}):k_(e,t.startIndex??0)}function tv(e){let t=new Map;return async(n,r,i)=>{if(i?.aborted)throw Wt();let a=nv(n,r,e),o=t.get(a);if(o)return o;let s=pr(V.readFileSync(a,`utf8`),{sourcePath:a});return t.set(a,s),s}}function nv(e,t,n){let r=t?H.dirname(t):n;return H.resolve(r,e)}function rv(e){return pm(e)?{command:e.kind,...e.kind===`runFlow`?Q(e.label??e.includePath):{}}:{command:e.kind,...iv(e)}}function iv(e){return av(e)?Q(fv(e.target)):ov(e)?sv(e):e.kind===`inputText`?Q(`<text>`):cv(e)}function av(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function ov(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function sv(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return Q(pv(e.target));case`extendedWaitUntil`:return Q(pv(e.visible??e.notVisible));case`scrollUntilVisible`:return Q(pv(e.element))}}function cv(e){return lv(e)?uv(e):e.kind===`swipe`?dv(e):e.kind===`runFlow`?Q(e.label??(e.include.kind===`file`?e.include.path:``)):{}}function lv(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function uv(e){switch(e.kind){case`openLink`:return Q(e.link);case`takeScreenshot`:return Q(e.path);case`runScript`:return Q(e.file);case`pressKey`:return Q(e.key)}}function dv(e){return Q(e.gesture.kind===`coordinates`?`${mv(e.gesture.start)} to ${mv(e.gesture.end)}`:e.gesture.direction)}function fv(e){return e.space===`target`?pv(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function pv(e){return e?.id??e?.text??e?.label}function mv(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function Q(e){return e?{value:e}:{}}function hv(e){let{filePath:t,tracePath:n,onFailure:r}=e,i=new Map;return{commandStarted:e=>{i.set(e.stepIndex,e),gv(()=>yv(t,e)),gv(()=>bv(n,t,e))},commandCompleted:e=>{let r=_v(i,e.stepIndex);gv(()=>xv(n,t,vv(r,e),!0))},commandFailed:e=>{let a=_v(i,e.stepIndex);gv(()=>r(e)),gv(()=>xv(n,t,vv(a,e),!1))}}}function gv(e){try{e()}catch{}}function _v(e,t){let n=e.get(t);return e.delete(t),n}function vv(e,t){return y({...e??t,durationMs:t.durationMs,runtimeMetrics:t.runtimeMetrics,data:t.data,error:t.error})}function yv(e,t){let n=zt();if(!n)return;let r=rv(t.command);P({type:`replay-test`,...n,file:n.file||e,status:`progress`,stepIndex:t.stepIndex,stepTotal:t.stepTotal,stepCommand:r.command,...r.value?{stepValue:r.value}:{}})}function bv(e,t,n){let r=rv(n.command);$d(e,{type:`replay_action_start`,ts:new Date().toISOString(),replayPath:t,...n.source.path&&n.source.path!==t?{sourcePath:n.source.path}:{},line:n.source.line,step:n.stepIndex,command:r.command,positionals:r.value?[r.value]:[]})}function xv(e,t,r,i){let a=Sv(r);$d(e,{type:`replay_action_stop`,ts:new Date().toISOString(),replayPath:t,...r.source.path&&r.source.path!==t?{sourcePath:r.source.path}:{},line:r.source.line,step:r.stepIndex,command:rv(r.command).command,ok:i,durationMs:r.durationMs,...Object.keys(a).length>0?{resultTiming:a}:{},...!i&&r.error instanceof n?{errorCode:r.error.code}:{}})}function Sv(e){let t=Cv(e.data?.timing)?e.data.timing:void 0;return y({...e.runtimeMetrics??{},...typeof t?.executionProfile==`string`?{executionProfile:t.executionProfile}:{},...typeof t?.gestureDurationMs==`number`?{gestureDurationMs:t.gestureDurationMs}:{}})}function Cv(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function wv(e,t){let n=rv(e.command);return{authoredCommand:e.command,source:e.source,progress:n,action:{command:Fv(e.command.kind),positionals:Iv(e.command.kind,n.value),flags:t.flags??{}}}}async function Tv(e){let{event:t,plan:n,replayPath:r,req:i,sessionName:a,sessionStore:o,logPath:s}=e,c=wv(t,i),l=Xf(e.error),u=[...Lv(t.expandedVariables),...Rv(c.authoredCommand)].sort((e,t)=>t.value.length-e.value.length),d=le(u),f={...l,message:d(l.message),...l.hint?{hint:d(l.hint)}:{}},p=o.get(a),m=p?await Nf({session:p,sessionName:a,sessionStore:o,logPath:s,action:c.action}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},h=p&&m.state===`available`&&!pm(c.authoredCommand)?Dv({command:c.authoredCommand,platform:n.platform,action:c.action,session:p,nodes:m.nodes,sanitize:d}):[],g=D_(n,{from:t.stepIndex,planDigest:n.digest}),_=[c.authoredCommand.kind,Ev(c.progress.value)].filter(Boolean).join(` `),v=Af({sessionStore:o,sessionName:a,divergence:{version:1,kind:`action-failure`,step:{index:t.stepIndex,source:{path:d(c.source.path??r),line:c.source.line}},action:d(_),cause:{code:f.code,message:f.message,...f.hint?{hint:f.hint}:{}},screen:Lf(m,d),suggestions:h.slice(0,5),suggestionCount:h.length,resume:g.allowed?{allowed:!0,from:t.stepIndex,planDigest:n.digest}:{allowed:!1,from:t.stepIndex,planDigest:n.digest,reason:g.reason},repairHint:Cf({kind:`action-failure`,targetEvidence:void 0,capture:jf(m)})},responseLevel:i.meta?.responseLevel});return Qf({error:f,actionLabel:_,action:c.authoredCommand.kind,positionals:[...c.action.positionals],step:t.stepIndex,replayPath:r,artifactPaths:[...t.artifactPaths],snapshotDiagnostics:e.snapshotDiagnostics,divergence:v,scrubVars:u})}function Ev(e){return!e||e===`<text>`?e??``:Ee(e)}function Dv(e){let t=kv(e.command);return!t||e.platform!==`android`&&e.platform!==`ios`?[]:xf(Ov({createdAt:Date.now(),nodes:e.nodes},t,e.platform).map(e=>({node:e,nodeIndex:e.index,basis:Pv(t.selector,e)}))).map(({node:t,basis:n})=>Jf({node:t,nodes:e.nodes,session:e.session,action:e.action,basis:n,sanitize:e.sanitize}))}function Ov(e,t,n){return Rh(e,t.selector,n,t.childOf).ranked}function kv(e){if(Av(e))return jv(e);if(Mv(e))return Nv(e);if(e.kind===`swipe`&&e.gesture.kind===`target`)return{selector:e.gesture.from}}function Av(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function jv(e){if(e.target.space===`target`)return e.kind===`tapOn`?{selector:e.target.selector,index:e.index,childOf:e.childOf}:{selector:e.target.selector}}function Mv(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Nv(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element}}}function Pv(e,t){return e.id!==void 0||e.text!==void 0&&zm({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text!==void 0||e.label!==void 0?`label`:`other`}function Fv(e){return e===`tapOn`||e===`doubleTapOn`?`click`:e===`longPressOn`?`longpress`:e===`assertVisible`||e===`assertNotVisible`||e===`extendedWaitUntil`||e===`scrollUntilVisible`?`wait`:e}function Iv(e,t){return!t||e===`inputText`?[]:[t]}function Lv(e){return Object.entries(e).filter(([,e])=>e.length>0).map(([e,t])=>({name:e,value:t})).sort((e,t)=>t.value.length-e.value.length)}function Rv(e){return e.kind!==`inputText`||e.text.length===0?[]:[{name:`${e.kind}.text`,value:e.text}]}function zv(e){let{result:t,plan:n,startIndex:r,startedAt:i,sessionName:a,sessionStore:o,snapshotStart:s}=e,c=Vv(o,a,s),l=n.total-r;return{ok:!0,data:{replayed:l,healed:0,session:a,sessionActive:o.get(a)!==void 0,artifactPaths:t.artifactPaths,...t.warnings?{warnings:t.warnings}:{},...c?{snapshotDiagnostics:c}:{},message:Uv(l,Date.now()-i)}}}async function Bv(t){let{failedEvent:n,plan:r}=t.state,i=e(n?.error??t.error);return n&&r?await Tv({error:i,event:n,plan:r,replayPath:k.expandHome(t.requestedPath,t.req.meta?.cwd),req:t.req,sessionName:t.sessionName,sessionStore:t.sessionStore,logPath:t.logPath,snapshotDiagnostics:Vv(t.sessionStore,t.sessionName,t.state.snapshotStart)}):R(i.code,i.message,{...i.details??{},...Hv(n)})}function Vv(e,t,n){return je(e.get(t)?.snapshotDiagnostics?.samples.slice(n)??[])}function Hv(e){return e?{replaySource:e.source,replayStep:e.stepIndex,replayStepTotal:e.stepTotal}:{}}function Uv(e,t){return`Replayed ${e} ${e===1?`step`:`steps`} in ${(t/1e3).toFixed(1)}s`}async function Wv(e){let{req:t}=e,n=t.positionals?.[0];if(!n)return R(`INVALID_ARGS`,`replay requires a path`);if(t.flags?.saveScript!==void 0)return R(`INVALID_ARGS`,`Maestro YAML does not support --save-script; ADR 0012 repair recording applies only to .ad scripts.`);let r=Date.now(),i={snapshotStart:0};try{return await Gv({...e,requestedPath:n,startedAt:r,state:i})}catch(t){return await Bv({...e,requestedPath:n,state:i,error:t})}}async function Gv(e){let{req:t,sessionName:n,sessionStore:r,tracePath:i,invoke:a,state:o}=e,s=await Kv(e),c=await w_(s.program,{defaults:s.defaults,env:s.env,platform:s.platform,target:s.target,runtimeHints:s.runtimeHints,loadProgram:s.loadProgram,signal:s.signal});o.plan=c;let l=O_(c,{from:t.flags?.replayFrom,planDigest:t.flags?.replayPlanDigest}),u=Qv({req:t,invoke:a,logPath:e.logPath,sessionName:n,sessionStore:r,device:s.device,platform:s.platform,runtimeHints:s.runtimeHints,sourcePath:s.filePath});return o.snapshotStart=r.get(n)?.snapshotDiagnostics?.samples.length??0,zv({result:await $_(c,u,{defaults:s.defaults,env:s.env,platform:s.platform,target:s.target,loadProgram:s.loadProgram,signal:s.signal,startIndex:l,observer:hv({filePath:s.filePath,tracePath:i,onFailure:e=>{o.failedEvent=e}})}),plan:c,startIndex:l,startedAt:e.startedAt,sessionName:n,sessionStore:r,snapshotStart:o.snapshotStart})}async function Kv(e){let{req:t,requestedPath:n,sessionName:r,sessionStore:i}=e,a=k.expandHome(n,t.meta?.cwd),o=pr(V.readFileSync(a,`utf8`),{sourcePath:a}),s=i.get(r);s&&In(s,t.flags);let c=await qv({req:t,sessionStore:i,sessionName:r,session:s,program:o});return{filePath:a,program:o,...c,defaults:Xv({req:t,sessionName:r,filePath:a,platform:c.platform,target:c.target}),env:Zv(t),signal:Vt(t.meta?.requestId),loadProgram:tv(H.dirname(a))}}async function qv(e){let{req:t,sessionStore:n,sessionName:r,session:i,program:a}=e,o=t.flags?.platform,s=i?.device??(o===`android`||o===`ios`?void 0:await I(t.flags??{},jr(a,o))),c=iy(t,s),l=Ya({req:t,sessionStore:n,sessionName:r,device:s,platform:c});return await Jv({req:t,sessionStore:n,sessionName:r,device:s,platform:c,target:ay(t,s),runtimeHints:l,program:a})}async function Jv(e){if(e.device||!Yv(e.runtimeHints))return e;let t=await I(e.req.flags??{},jr(e.program,e.platform));return{device:t,platform:e.platform,target:ay(e.req,t),runtimeHints:Ya({req:e.req,sessionStore:e.sessionStore,sessionName:e.sessionName,device:t,platform:e.platform})}}function Yv(e){return e?.metroPort!==void 0&&e.metroHost===void 0&&e.bundleUrl===void 0}function Xv(e){return{...zp({req:e.req,sessionName:e.sessionName,metadata:{},resolvedPath:e.filePath}),AD_PLATFORM:e.platform,AD_TARGET:e.target}}function Zv(e){return{...We(Pe(e.flags?.replayShellEnv)),...Re(Ve(e.flags?.replayEnv))}}function Qv(e){let{req:t,invoke:r,logPath:i,sessionName:a,sessionStore:o,device:s,platform:c,runtimeHints:l,sourcePath:u}=e,{command:d,positionals:f,input:p,flags:m,...h}=t;return Yg({baseReq:y({...h,flags:$v(s,c,t.flags),runtime:l}),invoke:r,platform:c,sourcePath:u,dependencies:{now:Date.now,sleep:async(e,t)=>{await Mi(e,void 0,{signal:t})},resolveGestureViewport:async()=>{let e=o.get(a);if(!e)throw new n(`SESSION_NOT_FOUND`,`No active session. Run open first.`);return await nn(e.device,z(i,t.flags,e.appBundleId,e.trace?.outPath))}}})}function $v(e,t,n){if(!e)return ey(t,n);let r={platform:t,target:e.target,noRecord:!0};return t===`android`?{...r,serial:e.id}:{...r,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}}}function ey(e,t){let n={platform:e,target:t?.target??`mobile`,noRecord:!0};return t?.device&&(n.device=t.device),e===`android`?ty(n,t):ny(n,t)}function ty(e,t){return t?.serial&&(e.serial=t.serial),t?.androidDeviceAllowlist&&(e.androidDeviceAllowlist=t.androidDeviceAllowlist),e}function ny(e,t){return t?.udid&&(e.udid=t.udid),t?.iosSimulatorDeviceSet&&(e.iosSimulatorDeviceSet=t.iosSimulatorDeviceSet),e}function ry(e,t){return e.flags?.replayBackend===`maestro`&&(H.extname(t)===`.yaml`||H.extname(t)===`.yml`)}function iy(e,t){let r=e.flags?.platform;if(r===`android`||r===`ios`)return r;if(t?.platform===`android`)return`android`;if(t?.platform===`apple`&&t.appleOs===`ios`)return`ios`;throw new n(`INVALID_ARGS`,`Maestro replay requires --platform android|ios or an active mobile session.`)}function ay(e,t){return typeof e.flags?.target==`string`?e.flags.target:t?.target??`mobile`}async function oy(e,t,n,r){let i=e.actionSourcePaths?.[n]??e.resolved,a=e.actionLines[n]??1,o=await Dp({action:t,scope:e.scope,sourcePath:i,sourceLine:a,replayPath:e.resolved,step:n+1,sessionName:e.sessionName,sessionStore:e.sessionStore,logPath:e.logPath,artifactPaths:r,responseLevel:e.responseLevel,planActions:e.actions,planDigest:e.planDigest});if(!o.verified)return o.response;let s=o.guard,c=o.deferredLandmark,l=s?{replayTargetGuard:s.expected}:c?{replayLandmarkGuard:c}:void 0;return await sy({ctx:e,action:t,index:n,artifactPaths:r,sourcePath:i,sourceLine:a,response:await ef({req:l?{...e.replayReq,internal:{...e.replayReq.internal,...l}}:e.replayReq,sessionName:e.sessionName,action:t,scope:e.scope,filePath:e.resolved,line:a,sourcePath:e.actionSourcePaths?.[n],step:n+1,tracePath:e.actionTracePath,invoke:e.invoke}),guard:s,deferredLandmark:c})}async function sy(e){let{ctx:t,action:n,index:r,artifactPaths:i,sourcePath:a,sourceLine:o,response:s}=e,c={action:n,scope:t.scope,failedResponse:s,sourcePath:a,sourceLine:o,replayPath:t.resolved,step:r+1,sessionName:t.sessionName,sessionStore:t.sessionStore,logPath:t.logPath,artifactPaths:i,responseLevel:t.responseLevel,planActions:t.actions,planDigest:t.planDigest};return e.guard&&Op(s)?await Ap({...c,guard:e.guard}):e.deferredLandmark&&jp(s)?await Mp(c):s}async function cy(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,tracePath:a,invoke:o}=e,c=t.positionals?.[0];if(!c)return R(`INVALID_ARGS`,`replay requires a path`);let l=Date.now(),u=``,d=new Set;try{u=k.expandHome(c,t.meta?.cwd);let s=await _y({...e,resolved:u});if(s)return s;let f=vy({req:t,sessionName:n,sessionStore:i,tracePath:a,resolved:u});if(!f.ok)return f.response;let{replayReq:p,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_,preEntrySession:v,entryIndex:y,scope:b,actionTracePath:x,snapshotDiagnosticSamples:S}=f.value,C=Sy({req:t,entryIndex:y,preEntrySession:v,sessionStore:i,sessionName:n,sourcePath:u});if(!C.ok)return C.response;let w={scope:b,replayReq:p,sessionName:n,sessionStore:i,logPath:r,resolved:u,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_,actionTracePath:x,responseLevel:t.meta?.responseLevel,invoke:o};return await ly({req:t,sessionName:n,sessionStore:i,logPath:r,resolved:u,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_,entryIndex:y,scope:b,stepContext:w,artifactPaths:d,snapshotDiagnosticSamples:S,armSaveScript:C.armSaveScript})||fy({startedAt:l,sessionName:n,sessionStore:i,actions:m,entryIndex:y,artifactPaths:d,snapshotDiagnosticSamples:S,armSaveScript:C.armSaveScript})}catch(e){let t=s(e);return R(t.code,t.message,d.size>0?{artifactPaths:[...d]}:void 0)}}async function ly(e){let{sessionName:t,sessionStore:n,resolved:r,actions:i,entryIndex:a,stepContext:o,artifactPaths:s,snapshotDiagnosticSamples:c,armSaveScript:l}=e;for(let u=a;u<i.length;u+=1){let a=i[u];if(!uy(a)||(l(),Oy({action:a,index:u,totalActions:i.length,sessionStore:n,sessionName:t})))continue;py(r,u,i.length,a);let d=Ly(n,t),f=await oy(o,a,u,[...s]);if(c.push(...Ry(n,t,d)),sf(f).forEach(e=>s.add(e)),!f.ok)return await dy(e,a,u,f)}}function uy(e){return!!(e&&e.command!==`replay`)}async function dy(e,t,n,r){let i=t=>jy({response:t,sessionStore:e.sessionStore,sessionName:e.sessionName});return Iy(r)?i(r):i(await np({response:r,action:t,index:n,replayPath:e.resolved,sourcePath:e.actionSourcePaths?.[n]??e.resolved,sourceLine:e.actionLines[n]??1,artifactPaths:[...e.artifactPaths],snapshotDiagnosticSamples:e.snapshotDiagnosticSamples,scope:e.scope,req:e.req,sessionName:e.sessionName,sessionStore:e.sessionStore,logPath:e.logPath,planActions:e.actions,planDigest:e.planDigest}))}function fy(e){let{startedAt:t,sessionName:n,sessionStore:r,actions:i,entryIndex:a,artifactPaths:o,snapshotDiagnosticSamples:s,armSaveScript:c}=e;c();let l=r.get(n);l?.saveScriptBoundary!==void 0&&(l.saveScriptComplete=!0,r.set(n,l));let u=i.length-a,d=je(s);return{ok:!0,data:{replayed:u,healed:0,session:n,sessionActive:l!==void 0,artifactPaths:[...o],...d?{snapshotDiagnostics:d}:{},message:Fy(u,Date.now()-t)}}}function py(e,t,n,r){let i=zt();i&&P({type:`replay-test`,...i,file:i.file||e,status:`progress`,stepIndex:t+1,stepTotal:n,...my(r)})}function my(e){return{stepCommand:e.command,...hy(e)}}function hy(e){let t=e.positionals??[],n=gy(t[0]);return n?{stepValue:n}:t.length===0?{}:{stepValue:t.join(` `)}}function gy(e){if(!e)return;let t=b(e);if(!t)return;let n=t.selectors.flatMap(e=>e.terms.flatMap(e=>(e.key===`label`||e.key===`text`||e.key===`id`)&&typeof e.value==`string`?[e.value]:[]));if(n.length===0)return;let r=n[0];return r&&n.every(e=>e===r)?r:void 0}async function _y(e){if(ry(e.req,e.resolved))return e.sessionStore.get(e.sessionName)?.saveScriptBoundary===void 0?await Wv(e):R(`INVALID_ARGS`,`This session has an active .ad --save-script repair run; finish it with replay --from or close before running Maestro YAML.`)}function vy(e){let{req:t,sessionName:n,sessionStore:r,tracePath:i,resolved:a}=e,o=yy(a,t);if(!o.ok)return o;let{metadata:s,actions:c,actionLines:l,actionSourcePaths:u}=o.value,d=by({...t,flags:kr(t.flags,c)},s),f=Xd({actions:c,actionLines:l,actionSourcePaths:u,metadata:op(d.flags)}),p=r.get(n),m=sp(t.flags,c.length,f,p?.pendingRecordAndHeal,p?.actions.length??0);return m.ok?{ok:!0,value:{replayReq:d,actions:c,actionLines:l,actionSourcePaths:u,planDigest:f,preEntrySession:p,entryIndex:m.value,scope:xy({req:t,replayReq:d,sessionName:n,resolved:a,metadata:s}),actionTracePath:i??p?.trace?.outPath,snapshotDiagnosticSamples:[]}}:m}function yy(e,t){let n=V.readFileSync(e,`utf8`),r=n.trimStart()[0];return r!==`{`&&r!==`[`?{ok:!0,value:vr(n,t.flags)}:{ok:!1,response:R(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`)}}function by(e,t){return!t.platform&&!t.target?e:{...e,flags:ap(e.flags,t)}}function xy(e){let{req:t,replayReq:n,sessionName:r,resolved:i,metadata:a}=e;return we({builtins:zp({req:n,sessionName:r,metadata:a,resolvedPath:i}),fileEnv:a.env,shellEnv:We(Pe(t.flags?.replayShellEnv)),cliEnv:Re(Ve(t.flags?.replayEnv))})}function Sy(e){let{req:t,entryIndex:n,preEntrySession:r,sessionStore:i,sessionName:a,sourcePath:o}=e,s=Cy({entryIndex:n,sessionStore:i,sessionName:a});return s?{ok:!1,response:s}:(Ty({req:t,preEntrySession:r,sessionStore:i,sessionName:a}),wy({req:t,sessionStore:i,sessionName:a,sourcePath:o}))}function Cy(e){let t=Ey(e);if(t)return t;if(e.entryIndex>0&&!e.sessionStore.get(e.sessionName))return $t()}function wy(e){let{req:t,sessionStore:n,sessionName:r,sourcePath:i}=e,a=n.get(r),{saveScript:o,force:s}=t.flags??{},{saveScriptForce:c,saveScriptPath:l,saveScriptBoundary:u}=a??{};if(o&&a?.scriptRecordingState!==void 0)return{ok:!1,response:R(`INVALID_ARGS`,`replay --save-script cannot re-arm an ordinary recording in terminal/active state ${a.scriptRecordingState}. Close this session and use a fresh one for repair authoring.`)};let d=Dy({saveScript:o,liveForce:s,persistedForce:c,sourcePath:i,existingSaveScriptPath:l});return d?{ok:!1,response:d}:(a&&u!==void 0&&(a.saveScriptComplete=!1),{ok:!0,armSaveScript:ky({saveScript:o,force:s,sessionStore:n,sessionName:r,sourcePath:i})})}function Ty(e){let{req:t,preEntrySession:n,sessionStore:r,sessionName:i}=e;n&&n.pendingRecordAndHeal?.expectedFrom===t.flags?.replayFrom&&(Kd(n),r.set(i,n)),t.flags?.saveScript&&r.clearRepairTombstone(i)}function Ey(e){let{entryIndex:t,sessionStore:n,sessionName:r}=e;if(!(t>0)&&n.get(r)?.saveScriptBoundary!==void 0)return R(`INVALID_ARGS`,`This session has an active --save-script repair run; continue it with replay --from <n> --plan-digest <sha256>, or finish with close, before starting a fresh full replay.`)}function Dy(e){let{saveScript:t,liveForce:n,persistedForce:r,sourcePath:i,existingSaveScriptPath:a}=e;if(!t)return;let o=typeof t==`string`?He(t):a??Py(i);if(!(n||r&&o===a)&&V.existsSync(o))return R(`COMMAND_FAILED`,`A file already exists at ${o}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`)}function Oy(e){let{action:t,index:n,totalActions:r,sessionStore:i,sessionName:a}=e;return t.command!==`close`||n!==r-1?!1:i.get(a)?.saveScriptBoundary!==void 0}function ky(e){let{saveScript:t,force:n,sessionStore:r,sessionName:i,sourcePath:a}=e;if(!t)return()=>{};let o=!0;return()=>{Ay({sessionStore:r,sessionName:i,saveScript:t,force:n,sourcePath:a,firstArm:o}),o=!1}}function Ay(e){let{sessionStore:t,sessionName:n,saveScript:r,force:i,sourcePath:a,firstArm:o}=e,s=t.get(n);s&&(s.recordSession=!0,typeof r==`string`?(ke(s,He(r),i),s.saveScriptDefaultedHealedPath=!1):s.saveScriptPath===void 0&&(s.saveScriptPath=Py(a),s.saveScriptDefaultedHealedPath=!0),i&&(s.saveScriptForce=!0),s.saveScriptBoundary===void 0&&(s.saveScriptBoundary=o?s.actions.length:0),s.repairSourcePath===void 0&&(s.repairSourcePath=a),t.set(n,s))}function jy(e){let{response:t,sessionStore:n,sessionName:r}=e;if(t.ok)return t;let i=n.get(r);if(i?.saveScriptBoundary===void 0||i.saveScriptCommitted)return t;let a=My(t);return a&&(a.repairSessionHeld=!0),t}function My(e){let t=e.error.details?.divergence;if(!(!x(t)||!Ny(t.resume)))return t.resume}function Ny(e){return!x(e)||typeof e.allowed!=`boolean`||!Number.isInteger(e.from)||typeof e.planDigest!=`string`?!1:e.allowed||typeof e.reason==`string`}function Py(e){let t=H.dirname(e),n=H.basename(e,H.extname(e));return H.join(t,`${n}.healed.ad`)}function Fy(e,t){let n=(t/1e3).toFixed(1);return`Replayed ${e} ${e===1?`step`:`steps`} in ${n}s`}function Iy(e){if(e.ok||e.error.code!==`REPLAY_DIVERGENCE`)return!1;let t=e.error.details?.divergence,n=t&&typeof t==`object`?t.kind:void 0;return typeof n==`string`&&n!==`action-failure`}function Ly(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function Ry(e,t,n){return e.get(t)?.snapshotDiagnostics?.samples.slice(n)??[]}const zy=1e3,By=3e3;function Vy(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await Hy(e)}}async function Hy(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,artifactsDir:a,tracePath:o}=e;if(t.flags?.recordVideo!==!0)return;let s=i.get(n);if(!s||s.recording)return;let c=Ie(s.device.platform),l=a?H.join(a,`recording${c}`):Be(s.device.platform);Wy(o,{type:`video_recording_start`,session:n,videoPath:l}),u({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:l}});let d=await yr({req:{token:t.token,session:n,command:`record`,positionals:[`start`,l],flags:{},meta:t.meta},sessionName:n,sessionStore:i,logPath:r});if(!d.ok)return Wy(o,{type:`video_recording_start_failed`,session:n,videoPath:l,errorCode:d.error.code}),d;let f=Date.now();return await ht(zy),Wy(o,{type:`video_preroll_done`,session:n,durationMs:Date.now()-f,requestedDurationMs:zy}),u({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-f,data:{session:n,requestedDurationMs:zy}}),d}async function Uy(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,tracePath:a,artifactPaths:o}=e;if(t.flags?.recordVideo!==!0||!i.get(n)?.recording)return;Wy(a,{type:`video_tail_start`,session:n,requestedDurationMs:By});let s=Date.now();await ht(By);let c=Date.now(),l=await yr({req:{token:t.token,session:n,command:`record`,positionals:[`stop`],flags:{},meta:t.meta},sessionName:n,sessionStore:i,logPath:r});return sf(l).forEach(e=>o.add(e)),Wy(a,{type:`video_recording_stop`,session:n,ok:l.ok,durationMs:Date.now()-c,tailDurationMs:c-s,errorCode:l.ok?void 0:l.error.code}),u({phase:`replay_test_video_recording_stop`,durationMs:Date.now()-c,data:{session:n,ok:l.ok,tailDurationMs:c-s}}),l}function Wy(e,t){K(e,{...t,ts:new Date().toISOString()})}function Gy(e){let{platform:t,target:n,artifactsDir:r,shard:i}=e,a=Ky(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0?a:md({...a??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r}},i)}function Ky(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}async function qy(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,invoke:o}=e;return t.command===`replay`?await cy({req:t,sessionName:n,logPath:r,sessionStore:i,invoke:o}):t.command===`test`?t.flags?.replayFrom!==void 0||t.flags?.replayPlanDigest!==void 0?R(`INVALID_ARGS`,`test does not support --from/--plan-digest; resume is replay-only. Run the failing script directly with replay --from.`):t.flags?.saveScript===void 0?await Dd({req:t,sessionName:n,runReplay:async({filePath:e,sessionName:n,platform:a,target:s,requestId:c,artifactsDir:l,artifactPaths:u,tracePath:d,shard:f})=>{let p=e=>(u&&sf(e).forEach(e=>u.add(e)),e),m=Gy({parentFlags:t.flags,platform:a,target:s,artifactsDir:l,shard:f}),h={req:t,sessionName:n,logPath:r,sessionStore:i,artifactsDir:l,tracePath:d},g=Vy(h);return await cy({req:{...t,command:`replay`,session:n,positionals:[e],flags:m,meta:{...t.meta??{},...c?{requestId:c}:{}},...t.internal||g?{internal:{...t.internal??{},...g?{openLifecycle:g}:{}}}:{}},sessionName:n,logPath:r,sessionStore:i,tracePath:d,invoke:async e=>{let t=await Hy(h);return t&&!t.ok?t:p(await o(e))}})},finalizeAttempt:async({sessionName:e,artifactPaths:n,artifactsDir:a,tracePath:o})=>await Uy({req:t,sessionName:e,logPath:r,sessionStore:i,artifactsDir:a,tracePath:o,artifactPaths:n}),cleanupSession:async e=>{i.get(e)&&await gs({req:{token:t.token,session:e,command:`close`,positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:r,sessionStore:i,leaseRegistry:a})}}):R(`INVALID_ARGS`,`test does not support --save-script; the agent-supervised repair loop is replay-only. Repair the failing script directly with replay --save-script.`):null}function Jy(e){let{req:t,sessionName:r,sessionStore:i}=e;if(t.command!==ye.sessionSaveScript)return null;if((t.positionals?.length??0)>1)return Xy(new n(`INVALID_ARGS`,`session save-script accepts at most one output path.`));let a=i.get(r);if(!a)return Xy(new n(`SESSION_NOT_FOUND`,`No active session "${r}".`,{hint:`Start a fresh journey with open <app> --save-script[=<path>], then retry.`}));let o=Yy(a);if(o)return Xy(o);let s=t.positionals?.[0]?.trim();if(t.positionals?.[0]!==void 0&&!s)return Xy(new n(`INVALID_ARGS`,`session save-script path cannot be empty.`));s&&ke(a,He(s),t.flags?.force),t.flags?.force&&(a.saveScriptForce=!0);let c=i.writeSessionLog(a,{force:!!(t.flags?.force||a.saveScriptForce),publication:`active`});return c.written?(a.scriptRecordingState=`published`,a.recordSession=!1,a.saveScriptPath=c.path,{ok:!0,data:{session:a.name,savedScript:c.path,actionCount:c.actionCount,...D(`Published script: ${c.path}`)}}):Xy(c.error??new n(`COMMAND_FAILED`,`The active session script was not published.`,{retriable:!0,hint:`The session remains armed; retry session save-script.`}))}function Yy(e){if(e.saveScriptBoundary!==void 0)return new n(`COMMAND_FAILED`,`This session has an active .ad repair transaction and cannot use ordinary active-session publication.`,{hint:`Finish or abort the repair through replay --from and its existing close/teardown protocol.`});if(e.scriptRecordingState===`aborted`)return new n(`COMMAND_FAILED`,`This script recording was aborted by a second successful open and cannot be published.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(e.scriptRecordingState===`published`)return new n(`COMMAND_FAILED`,`This script recording has already been published.`,{hint:`Continue using the live session, or close it and start a fresh authoring session.`});if(e.scriptRecordingState!==`armed`||!e.recordSession)return new n(`COMMAND_FAILED`,`Script recording was not armed before this journey began; session history cannot be published without recording-time target evidence.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`})}function Xy(t){return{ok:!1,error:e(t)}}function Zy(e){return e.some(e=>e.status===`fail`)?`fail`:e.some(e=>e.status===`warn`)?`warn`:`pass`}function Qy(e){return e===`fail`?`Blockers found before the run.`:e===`warn`?`No hard blockers found, but warnings need attention.`:`No blockers found.`}function $y(e){let t={fail:0,warn:1,pass:2,info:3};return[...e].sort((e,n)=>t[e.status]-t[n.status])}function eb(e,...t){for(let n of t)$(e,n)}function $(e,t){e.push(t),P({type:`command`,status:`progress`,message:tb(t)})}function tb(e){return[ue(e),...he(e)].join(`
25
- `)}const nb=2e3;async function rb(e,t){let{device:n,metroPort:r,shouldProbeMetro:i,androidAdbExecutor:a}=t;if(n.platform!==`android`)return;let o=f(n,a);i&&$(e,await lb(o,n.id,r)),$(e,await ib(o,n))}async function ib(e,t){try{let n=await tr(e),r=si(t);return n===await ab()&&!r?await ob(e,t,n):sb(t,n,r)}catch(e){return cb(e)}}async function ab(){try{return(await Nn()).manifest.serviceComponent}catch{return}}async function ob(e,t,n){let r=(await e([`shell`,`settings`,`get`,`secure`,Qn.previousIme],{allowFailure:!0,timeoutMs:nb})).stdout.trim(),i=r&&r!==`null`?r:void 0;return{id:`android-test-ime`,status:`fail`,summary:`Android test IME helper is the active input method on ${t.id}, but no active session owns it -- likely left over from a crashed session.`,hint:`A stuck test IME leaves the real keyboard unavailable on this device until restored.`,command:i?`adb -s ${t.id} shell ime set ${i}`:`adb -s ${t.id} shell ime list -s`,evidence:{currentIme:n,previousIme:i}}}function sb(e,t,n){return{id:`android-test-ime`,status:`pass`,summary:n?`Android test IME helper is active for this session on ${e.id}.`:`Android test IME helper is not active on ${e.id}; the device's normal IME is in use.`,evidence:{currentIme:t}}}function cb(t){let n=e(t);return{id:`android-test-ime`,status:`warn`,summary:`Could not inspect the Android test IME helper state.`,hint:n.message,evidence:{code:n.code}}}async function lb(t,n,r){try{let e=await t([`reverse`,`--list`],{allowFailure:!0,timeoutMs:nb}),i=`tcp:${r} tcp:${r}`,a=e.stdout.includes(i);return{id:`android-reverse`,status:a?`pass`:`warn`,summary:a?`Android adb reverse exists for Metro port ${r}.`:`Android adb reverse is missing for Metro port ${r}.`,command:a?void 0:`adb -s ${n} reverse tcp:${r} tcp:${r}`,evidence:{stdout:e.stdout.trim()}}}catch(t){let n=e(t);return{id:`android-reverse`,status:`warn`,summary:`Could not inspect Android adb reverse mappings.`,hint:n.message,evidence:{code:n.code}}}}async function ub(t,n){let{device:r,targetApp:i,session:a}=n;if(i)try{let e=await db(r,i);if(!e){$(t,{id:`target-app`,status:`info`,summary:`Target app installation checks are not supported for ${j(r)}.`,evidence:{requested:i,platform:j(r)}});return}$(t,{id:`target-app`,status:`pass`,summary:`Target app is launchable: ${e}`,evidence:{requested:i,resolved:e,sessionApp:a?.appBundleId}})}catch(n){let i=e(n);$(t,{id:`target-app`,status:`fail`,summary:`Target app check failed: ${i.message}`,hint:i.hint??`Install the app or pass an exact package/bundle id or app name.`,command:`agent-device apps --platform ${j(r)} --all`,evidence:{code:i.code,message:i.message}})}}async function db(e,t){if(e.platform===`android`){let{listAndroidApps:n}=await import(`./app-lifecycle.js`).then(e=>e.t);return fb(t,(await n(e,`all`)).map(e=>({id:e.package,name:e.name})))?.id}if(N(e)||A(e)){let{listIosApps:n}=await import(`./apps.js`).then(e=>e.t);return fb(t,(await n(e,`all`)).map(e=>({id:e.bundleId,name:e.name})))?.id}}function fb(e,t){let r=e.trim().toLowerCase(),i=t.find(e=>e.id.toLowerCase()===r||e.name.toLowerCase()===r);if(i)return i;let a=t.filter(e=>e.id.toLowerCase().includes(r)||e.name.toLowerCase().includes(r));if(a.length===1)return a[0];throw a.length>1?new n(`AMBIGUOUS_MATCH`,`Multiple launchable apps matched "${e}"`,{matches:a.map(e=>e.id),hint:`Pass an exact package/bundle id from agent-device apps --all.`}):new n(`APP_NOT_INSTALLED`,`No launchable installed app matched "${e}"`)}async function pb(t,n,r){let i=hb(n,r);try{let e=await _b(i),n=gb(e.devices,i);return $(t,{id:`device`,status:n.length===0?`fail`:`pass`,summary:xb(n,i,e.failures),hint:n.length===0?wb(e.failures):void 0,command:n.length===0?kb(i):void 0,evidence:Ab(n,e.failures)}),n.length>0&&vb(t,e.failures),{devices:n,platform:i.platform,target:i.target}}catch(n){let r=e(n);return $(t,{id:`device`,status:`fail`,summary:r.message,hint:r.hint,command:`agent-device devices`,evidence:{code:r.code,details:r.details}}),{devices:[],platform:i.platform,target:i.target}}}function mb(e,t,n){if(!n||!t)return;let r=t.devices.filter(e=>e.booted===!0);if(r.length===1)return r[0];$(e,{id:`target-app-device`,status:`fail`,summary:r.length===0?`Target app check needs one booted device; none matched.`:`Target app check needs one booted device; ${r.length} matched.`,hint:r.length===0?`Boot a device, or adjust --platform/--target/--device/--udid/--serial.`:`Pass --platform/--target/--device/--udid/--serial so doctor checks the intended device.`,command:t.platform?`agent-device devices --platform ${t.platform}`:`agent-device devices`,evidence:{targetApp:n,booted:r.map(e=>({platform:j(e),id:e.id,name:e.name}))}})}function hb(e,t){let n=e.flags??{};return rn({platform:n.platform??t?.device.platform,target:n.target??t?.device.target,device:n.device,udid:n.udid,serial:n.serial,iosSimulatorDeviceSet:n.iosSimulatorDeviceSet,androidDeviceAllowlist:n.androidDeviceAllowlist})}function gb(e,t){return e.filter(e=>Ze(e,t,{includeExplicitSelectors:!0}))}async function _b(e){if(e.platform)return{devices:await tn(e),failures:[]};let t=[],n=[];for(let r of dn)try{t.push(...await tn({...e,platform:r}))}catch(e){n.push(bb(r,e))}return{devices:t,failures:n}}function vb(e,t){for(let n of t)$(e,yb(n))}function yb(e){return{id:`device-${e.platform}`,status:`warn`,summary:`${Db(e.platform)} device inventory could not be read: ${e.message}`,hint:e.hint??`Check the ${Db(e.platform)} toolchain, or scope with --platform to skip it.`,evidence:{platform:e.platform,code:e.code}}}function bb(t,n){let r=e(n);return{platform:t,message:r.message,hint:r.hint,code:r.code}}function xb(e,t,n){if(e.length===0)return n.length>0?`No ${Sb(t)} devices found; ${Cb(n)}.`:`No ${Sb(t)} devices found.`;let r=e.filter(e=>e.booted===!0).length,i=`${e.length} ${Sb(t)} ${Ob(e.length,`device`)} available; ${r} booted`,a=Tb(e,t);return a?`${i} (${a}).`:`${i}.`}function Sb(e){let t=e.platform?Db(e.platform):`local`;return e.target?`${t} ${e.target}`:t}function Cb(e){return e.slice(0,2).map(e=>`${Db(e.platform)} inventory failed: ${e.message}`).join(`; `)}function wb(e){return e.find(e=>e.hint)?.hint??`Start or create a simulator/emulator, connect a device, or adjust --platform/--target/--device selectors.`}function Tb(e,t){if(t.platform||t.target)return;let n=fn(e),r=Eb();return[`android`,`apple`,`vega`,`linux`,`web`].flatMap(e=>{let t=n[e];return t.available>0?[`${r[e]} ${t.available} available, ${t.booted} booted`]:[]}).join(`; `)}function Eb(){return{android:`Android`,apple:`Apple`,vega:`Vega`,linux:`Linux`,web:`web`}}function Db(e){return e===`ios`?`iOS`:e===`macos`?`macOS`:e===`android`?`Android`:e===`vega`?`Vega`:e===`linux`?`Linux`:e===`web`?`web`:`Apple`}function Ob(e,t){return e===1?t:`${t}s`}function kb(e){return e.platform?`agent-device devices --platform ${e.platform}`:`agent-device devices`}function Ab(e,t){let n=new Map;for(let t of e){let e=j(t),r=n.get(e)??{available:0,booted:0};r.available+=1,t.booted===!0&&(r.booted+=1),n.set(e,r)}return{available:e.length,booted:e.filter(e=>e.booted===!0).length,byPlatform:Object.fromEntries([...n.entries()].sort(([e],[t])=>e.localeCompare(t))),...t.length>0?{failures:t}:{}}}const jb=1500;async function Mb(e,t,n,r={}){let i=`http://${e}:${t}/status`;try{let a=await fetch(i,{signal:AbortSignal.timeout(1500)}),o=await a.text(),s=a.ok&&o.toLowerCase().includes(`packager-status:running`),c=s?await Nb(e,t,r):void 0;return{id:`metro`,status:s?`pass`:`warn`,summary:s?Pb(i,c):`React Native dev server responded at ${i}, but did not report packager-status:running.`,hint:s?void 0:`Verify this is the Metro/Re.Pack instance for the target app, or restart the dev server.`,evidence:{url:i,statusCode:a.status,body:o.slice(0,120),kind:n,...c?{process:c}:{}}}}catch(e){return{id:`metro`,status:n===`auto`?`warn`:`fail`,summary:`React Native dev server is not reachable at ${i}.`,hint:`Start Metro or Re.Pack for this project. For non-default endpoints, launch with open --metro-host/--metro-port, or run metro prepare with --public-base-url/--proxy-base-url before retrying doctor.`,command:`curl -fsS ${i}`,evidence:{url:i,error:e instanceof Error?e.message:String(e),kind:n}}}}async function Nb(e,t,n){try{return await(n.resolveProcessInfo??Fb)(e,t)}catch{return}}function Pb(e,t){return t?.cwd?`React Native dev server is reachable at ${e} (cwd: ${t.cwd}).`:`React Native dev server is reachable at ${e}.`}async function Fb(e,t){if(!Ib(e))return;let n=await Lb(t);if(n!==void 0)return{pid:n,cwd:await Rb(n)}}function Ib(e){return e===`127.0.0.1`||e===`localhost`||e===`::1`||e===`0.0.0.0`}async function Lb(e){let t=await p(`lsof`,[`-nP`,`-iTCP:${e}`,`-sTCP:LISTEN`,`-Fp`],{allowFailure:!0,timeoutMs:jb});if(t.exitCode===0)return t.stdout.split(`
26
- `).map(e=>e.startsWith(`p`)?Number.parseInt(e.slice(1),10):NaN).find(e=>Number.isInteger(e)&&e>0)}async function Rb(e){let t=await p(`lsof`,[`-nP`,`-a`,`-p`,String(e),`-d`,`cwd`,`-Fn`],{allowFailure:!0,timeoutMs:jb});if(t.exitCode===0)return t.stdout.split(`
27
- `).find(e=>e.startsWith(`n`)&&e.length>1)?.slice(1)}const zb=[`daemonBaseUrl`,`tenant`,`runId`,`leaseId`,`leaseProvider`],Bb=[`provider`,`providerSessionId`,`providerApp`,`providerOsVersion`,`providerProject`,`providerBuild`,`providerSessionName`,`awsProjectArn`,`awsDeviceArn`,`awsAppArn`,`awsRegion`,`awsInteractionMode`];function Vb(e,t){let n=gt(e.meta?.cwd);return{targetApp:Kb(e.flags?.targetApp)??t?.appBundleId,metroHost:Kb(e.runtime?.metroHost)??`127.0.0.1`,metroPort:qb(e.runtime?.metroPort)??8081,kind:n,remote:e.flags?.remote===!0,shouldProbeMetro:Wb(e,n)}}function Hb(e,t={}){let n=Gb(e);return n?[{id:`remote-connection`,status:t.required?`pass`:`info`,summary:`Remote daemon/session or provider scope is configured.`,evidence:n}]:t.required?[{id:`remote-connection`,status:`fail`,summary:`No remote daemon/session or provider scope is configured.`,hint:`Use connect, --remote-config <path>, or direct remote/provider flags for the command.`}]:[]}function Ub(e,t,n,r={}){let i=n?e.toArray().filter(e=>e.name!==n.name&&e.device.platform===n.device.platform&&e.device.id===n.device.id).map(e=>e.name):[];return n?[{id:`session`,status:i.length>0?`warn`:`pass`,summary:i.length>0?`Other active sessions target the same device: ${i.join(`, `)}`:`Active session ${n.name} targets ${n.device.name}`,hint:i.length>0?`Close stale sessions before a QA run if they belong to old attempts.`:void 0,command:i.length>0?`agent-device close --session ${i[0]} --platform ${j(n.device)}`:void 0,evidence:{session:n.name,sameDeviceSessions:i,sessionStateDir:e.resolveSessionDir(n.name)}}]:[{id:`session`,status:`info`,summary:r.remote?`No active session named ${t}. Remote doctor will use configured remote scope.`:`No active session named ${t}. Doctor will use device inventory only.`,hint:`This is expected before a run. Use open when app foreground state matters.`}]}function Wb(e,t){return t!==`auto`||typeof e.runtime?.metroPort==`number`||typeof e.runtime?.metroHost==`string`}function Gb(e){let t={...Object.fromEntries([...zb,...Bb].flatMap(t=>typeof e.flags?.[t]==`string`?[[t,`<configured>`]]:[])),...e.flags?.sessionIsolation===`tenant`?{sessionIsolation:`tenant`}:{}};return Object.keys(t).length>0?t:void 0}function Kb(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function qb(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}const Jb=3e3;async function Yb(e,t){if(t===`android`){$(e,await Zb());return}if(t===`vega`){$(e,await Xb());return}(t===`ios`||t===`macos`||t===`apple`)&&$(e,await nx())}async function Xb(){let{parseVegaDeviceList:e}=await import(`./devices4.js`),{resolveVegaToolProvider:t}=await import(`./tool-provider3.js`).then(e=>e.n),n=t();if(!await n.isAvailable())return{id:`toolchain`,status:`info`,summary:`Vega toolchain: Vega CLI not found.`,hint:`Install Vega Developer Tools or ensure ~/vega/bin/vega is executable.`,command:`vega --version`};let r=await n.version({allowFailure:!0,timeoutMs:Jb}),i=await n.listDevices({allowFailure:!0,timeoutMs:Jb}),a=lx(r.stdout),o=i.exitCode===0&&e(i.stdout).length>0;return{id:`toolchain`,status:r.exitCode===0?`pass`:`info`,summary:a?`Vega toolchain: ${a}; ${o?`VVD running`:`no running VVD`}.`:`Vega toolchain: CLI found but version check failed.`,hint:o?void 0:`Start the Vega Virtual Device and retry doctor.`,evidence:{vegaVersion:a??null,deviceList:i.stdout.trim()||null}}}async function Zb(){let e=process.env.ANDROID_HOME||process.env.ANDROID_SDK_ROOT,t=await sx(e),n=await cx(`adb`,[`version`]);return n?Qb({license:t,sdkRoot:e,versionLine:n}):tx(e,t)}function Qb(e){return{id:`toolchain`,status:$b(e),summary:e.versionLine?`Android toolchain: ${e.versionLine}; ${ex(e.sdkRoot)}.`:`Android toolchain: adb is present but version check failed.`,hint:e.license===`missing`?`Accept Android SDK licenses before installing/building apps.`:void 0,command:e.license===`missing`?`sdkmanager --licenses`:void 0,evidence:{adbVersion:e.versionLine??null,androidHome:e.sdkRoot??null,license:e.license}}}function $b(e){return e.versionLine&&e.sdkRoot&&e.license!==`missing`?`pass`:`info`}function ex(e){return e?`ANDROID_HOME/ANDROID_SDK_ROOT set`:`ANDROID_HOME unset`}function tx(e,t){return{id:`toolchain`,status:`info`,summary:`Android toolchain: adb not found on PATH.`,hint:`Install Android platform-tools or add adb to PATH.`,evidence:{androidHome:e??null,license:t}}}async function nx(){let e=await cx(`xcodebuild`,[`-version`]);return e?rx({selectedPath:await cx(`xcode-select`,[`-p`]),versionLine:e}):ox()}function rx(e){return{id:`toolchain`,status:ix(e),summary:ax(e),evidence:{selectedPath:e.selectedPath??null,xcodeVersion:e.versionLine??null}}}function ix(e){return e.versionLine?`pass`:`info`}function ax(e){return e.versionLine?e.selectedPath?`Apple toolchain: ${e.versionLine}; xcode-select ${e.selectedPath}.`:`Apple toolchain: ${e.versionLine}; xcode-select path unavailable.`:`Apple toolchain: xcodebuild version check failed.`}function ox(){return{id:`toolchain`,status:`info`,summary:`Apple toolchain: xcodebuild version check failed.`,hint:`Install/select Xcode and complete first launch/license setup if xcodebuild reports it.`,command:`xcodebuild -version`}}async function sx(e){if(!e)return`unknown`;try{return await ji(H.join(e,`licenses`,`android-sdk-license`)),`accepted`}catch{return`missing`}}async function cx(e,t){try{let n=await p(e,t,{allowFailure:!0,timeoutMs:Jb});return n.exitCode===0?lx(n.stdout):void 0}catch{return}}function lx(e){return e.split(`
28
- `).map(e=>e.trim()).find(Boolean)}async function ux(e,t){$(e,await dx(t))}async function dx(e){let t=wn({stateDir:e});if(!t.installed)return{id:`web-agent-browser-processes`,status:`info`,summary:`Managed web backend is not installed; no agent-device-owned browser processes counted.`,evidence:{stateDir:e,installed:!1}};try{let n=await Tn(t);return{id:`web-agent-browser-processes`,status:n.count>0?`info`:`pass`,summary:n.count>0?`${n.count} live agent-device-owned Chrome process${n.count===1?``:`es`} detected.`:`No live agent-device-owned Chrome processes detected.`,evidence:{stateDir:e,installed:!0,count:n.count,pids:n.pids,matchReasons:n.processes.map(e=>e.reason)}}}catch(t){return{id:`web-agent-browser-processes`,status:`info`,summary:`Could not inspect live agent-device-owned Chrome processes.`,hint:`Run doctor again from a shell with permission to inspect local processes.`,evidence:{stateDir:e,error:t instanceof Error?t.message:String(t)}}}}async function fx(e){let{req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i}=e;if(t.command!==O.doctor)return null;let a=r.get(n),o=Vb(t,a),s=hx(r,n),c=[];if(eb(c,{id:`agent-device`,status:`pass`,summary:`agent-device ${Ke()} using ${s}`,evidence:{version:Ke(),stateDir:s}},...Hb(t,{required:o.remote}),...Ub(r,n,a,{remote:o.remote})),o.remote)return vx(c,o);let l=await pb(c,t,a);await Yb(c,a?.device.platform??l?.platform);let u=await gx({androidAdbExecutor:i,checks:c,inventory:l,options:o,session:a,stateDir:s});return await mx(c,u??px(l)),vx(c,o,{device:u,includeMetro:!0,inventory:l})}function px(e){let t=(e?.devices??[]).filter(e=>N(e)&&e.kind===`simulator`);return t.find(e=>e.booted===!0)??t[0]}async function mx(e,t){if(!(!t||!N(t)||t.kind!==`simulator`)&&!(process.platform!==`darwin`||F(t))){if(P({type:`command`,status:`progress`,message:`Checking iOS runner build cache (${t.name})...`}),await Yt(t)){$(e,{id:`ios-runner-cache`,status:`pass`,summary:`iOS runner artifact cached; first open skips the runner build`});return}xn(t,{}),P({type:`command`,status:`progress`,message:`Warming iOS runner build cache in the background (${t.name})...`}),$(e,{id:`ios-runner-cache`,status:`pass`,summary:`iOS runner build started in the background; the first open gets faster once it completes`,hint:"Run `agent-device prepare ios-runner` to wait for a fully warmed runner instead."})}}function hx(e,t){let n=H.dirname(e.resolveSessionDir(t));return H.basename(n)===`sessions`?H.dirname(n):n}async function gx(e){let{checks:t,inventory:n,options:r,session:i,androidAdbExecutor:a,stateDir:o}=e,s=i?.device??mb(t,n,r.targetApp);return s&&await _x(t,{androidAdbExecutor:a,device:s,options:r,session:i}),r.shouldProbeMetro&&$(t,await Mb(r.metroHost,r.metroPort,r.kind)),await ux(t,o),s}async function _x(e,t){let{androidAdbExecutor:n,device:r,options:i,session:a}=t;await ub(e,{device:r,session:a,targetApp:i.targetApp}),await rb(e,{androidAdbExecutor:n,device:r,metroPort:i.metroPort,shouldProbeMetro:i.shouldProbeMetro})}function vx(e,t,n={}){let r=Zy(e);return{ok:!0,data:{status:r,summary:Qy(r),kind:t.kind,platform:n.device?j(n.device):n.inventory?.platform,target:n.device?.target??n.inventory?.target,targetApp:t.targetApp,metro:n.includeMetro&&t.shouldProbeMetro?{host:t.metroHost,port:t.metroPort}:void 0,checks:$y(e)}}}async function yx(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=t.positionals?.[0]??``;if(a!==`ios-runner`)return R(`INVALID_ARGS`,`prepare requires a subcommand: ios-runner`);let o=i.get(n),s=t.flags??{},c=W(O.prepare,o,s);if(c)return c;let l=await G({session:o,flags:s,ensureReady:!0});if(!M(l.platform))return R(`UNSUPPORTED_OPERATION`,`prepare ios-runner is only supported on Apple runner platforms`);let u=Date.now(),d=await bn(l,bx(t,o,r,u));return{ok:!0,data:Sx(a,l,Math.max(0,Date.now()-u),d)}}function bx(e,t,n,r){let i=xx(e);return{...ti({req:e,logPath:n,traceLogPath:t?.trace?.outPath}),cleanStaleBundles:!0,buildTimeoutMs:i,healthTimeoutMs:i,prepareDeadline:Lt.fromTimeoutMs(i,r),startupTimeoutMs:i}}function xx(e){let t=e.flags?.timeoutMs;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:_}function Sx(e,t,n,r){return{action:e,platform:j(t),deviceId:t.id,deviceName:t.name,kind:t.kind,durationMs:n,...r,timing:Cx(n,r),message:`Prepared Apple runner: ${t.name}`}}function Cx(e,t){let n=wx(t.buildMs),r=Tx(t.connectMs),i=Tx(t.healthCheckMs);return{totalMs:e,additiveParts:{...n===void 0?{}:{buildMs:n},connectAfterBuildMs:Math.max(0,r-(n??0)),healthCheckMs:i},containment:n===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},note:`Top-level prepare timing fields are diagnostic and may overlap; use timing.additiveParts for additive wall-clock phases.`}}function wx(e){return e===void 0?void 0:Tx(e)}function Tx(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):0}async function Ex(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,command:a,positionals:o,recordPositionals:s,deriveNextSession:c}=e,l=i.get(n),u=t.flags??{},d=W(a,l,u);if(d)return d;let f=await G({session:l,flags:u,ensureReady:!0}),p=L(a,f);if(p)return p;l&&$n(t)===`may-invalidate`&&Yr(l);let m=await an(f,a,o,t.flags?.out,{...z(r,t.flags,l?.appBundleId,l?.trace?.outPath)});if(l){let e=c?await c(l,m,f):l;Ar(i,e,t,a,m??{},{positionals:s??o}),e!==l&&i.set(n,e)}return{ok:!0,data:m??{}}}async function Dx(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=i.get(n),o=t.flags??{},s=W(O.clipboard,a,o);if(s)return s;let c=(t.positionals?.[0]??``).toLowerCase();if(c!==`read`&&c!==`write`)return R(`INVALID_ARGS`,`clipboard requires a subcommand: read or write`);let l=await G({session:a,flags:o,ensureReady:!0}),u=L(O.clipboard,l);if(u)return u;let d=await an(l,O.clipboard,t.positionals??[],t.flags?.out,{...z(r,t.flags,a?.appBundleId,a?.trace?.outPath)});return Ar(i,a,t,t.command,d??{}),{ok:!0,data:{platform:j(l),...d??{}}}}async function Ox(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a=new Fn,leaseLifecycleProvider:o,invoke:s,invokeReplayAction:c,androidAdbExecutor:l}=e;if(t.command===O.doctor)return await fx({req:t,sessionName:n,sessionStore:i,androidAdbExecutor:l});if(di(t.command)===`inventory`)return await ks({req:t,sessionName:n,sessionStore:i});if(t.command===`runtime`)return await Qa({req:t,sessionName:n,sessionStore:i});if(di(t.command)===`state`)return await Is({req:t,sessionName:n,logPath:r,sessionStore:i});if(di(t.command)===`publication`)return Jy({req:t,sessionName:n,sessionStore:i});if(t.command===O.clipboard)return await Dx({req:t,sessionName:n,logPath:r,sessionStore:i});if(t.command===O.keyboard){let e=i.get(n),a=t.positionals?.[0]?.trim().toLowerCase();return!e&&(a===`dismiss`||a===`enter`||a===`return`)&&(t.flags??{}).platform===`ios`?R(`SESSION_NOT_FOUND`,`iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.`):await Ex({req:t,sessionName:n,logPath:r,sessionStore:i,command:O.keyboard,positionals:t.positionals??[]})}if(di(t.command)===`observability`)return await Ol({req:t,sessionName:n,sessionStore:i,androidAdbExecutor:l});if(t.command===O.prepare)return await yx({req:t,sessionName:n,logPath:r,sessionStore:i});if(t.command===O.install||t.command===O.reinstall)return await Cs({req:t,command:t.command,sessionName:n,sessionStore:i,deployOps:t.command===O.install?Ss:xs});if(t.command===ye.installSource)return await Ui({req:t,sessionName:n,sessionStore:i});if(t.command===ye.releaseMaterializedPaths)return await Qi({req:t});if(t.command===O.push){let e=t.positionals?.[0]?.trim(),a=t.positionals?.[1]?.trim();return!e||!a?R(`INVALID_ARGS`,`push requires <bundle|package> <payload.json|inline-json>`):await Ex({req:t,sessionName:n,logPath:r,sessionStore:i,command:O.push,positionals:[e,kx(a,t.meta?.cwd)],recordPositionals:[e,a]})}return t.command===O.triggerAppEvent?await Ex({req:t,sessionName:n,logPath:r,sessionStore:i,command:O.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let n=typeof t?.eventUrl==`string`?t.eventUrl:void 0,r=n?await wo(e.device,n,e.appBundleId,xo)??e.appBundleId:e.appBundleId;return{...e,appBundleId:r}}}):t.command===O.open?await Jo({req:t,sessionName:n,logPath:r,sessionStore:i}):di(t.command)===`replay`?await qy({req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,invoke:c??s}):t.command===O.batch?await Os(t,n,s):t.command===O.close?await gs({req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o}):null}function kx(e,t){let n=Qt(e,{subject:`Push payload`,cwd:t,expandPath:(e,t)=>k.expandHome(e,t)});return n.kind===`file`?n.path:n.text}export{Ox as handleSessionCommands};
24
+ `],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??``}),timeoutMs:sm,allowFailure:!0});if(i.exitCode!==0)throw new n(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${gm(i.stderr)}`,{exitCode:i.exitCode,stderr:i.stderr});try{return JSON.parse(i.stdout)}catch(r){throw new n(`COMMAND_FAILED`,`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:i.stdout.slice(0,cm),stderr:i.stderr.slice(0,cm)},r instanceof Error?r:void 0)}}function mm(e,t){for(let r of Object.keys(e))if(r.includes(`.`))throw new n(`INVALID_ARGS`,`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}function hm(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function gm(e){let t=e.trim();return t.length>0?t.slice(0,cm):`request process exited without stderr`}const _m=`maestro-test-failure`;function vm(e,t={}){return new n(`COMMAND_FAILED`,e,{...t,reason:_m})}function ym(e){return e instanceof n&&e.code===`COMMAND_FAILED`&&e.details?.reason===_m}function bm(e,t,n){return new km(Sm(xm(t.resolve(e))),n).parse()}function xm(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Sm(e){let t=[],r=0;for(;r<e.length;){let i=e.slice(r),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){r+=a;continue}let o=Cm(i);if(!o)throw new n(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);t.push(o.value),r+=o.length}return t}function Cm(e){return wm(e)??Tm(e)??Em(e)??Dm(e)??Om(e)}function wm(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function Tm(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Em(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Dm(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function Om(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var km=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let e=this.parseOr();if(this.peek())throw new n(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new n(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(e.type===`boolean`)return this.index+=1,e.value;if(e.type===`paren`&&e.value===`(`){this.index+=1;let e=this.parseOr();if(!this.consumeParen(`)`))throw new n(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new n(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let e=this.peek();if(e?.type!==`operator`||e.value!==`==`&&e.value!==`!=`)throw new n(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,e}consumeStringLiteral(){let e=this.peek();if(e?.type!==`string`)throw new n(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,e.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function Am(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function jm(e,t){return{...Bm(e,t),source:e.source}}function q(e,t,r){if(e===void 0)return;let i=r??ci[t]??{},a=Tr(i),o;if(typeof e==`number`)o=e;else{let r=e.trim();if(r===``)throw new n(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);o=Number(r)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new n(`INVALID_ARGS`,`Maestro ${t} must be ${a}.`);return o}function Mm(e,t,n,r){return q(e===void 0?t:n.resolve(String(e)),r)}function J(e){if(e?.aborted)throw en()}async function Nm(e,t){if(e.include.kind===`commands`)return{kind:`program`,source:e.source,config:{},commands:e.include.commands};if(!t.loadProgram)throw new n(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return J(t.signal),t.signal?await t.loadProgram(e.include.path,e.source.path,t.signal):await t.loadProgram(e.include.path,e.source.path)}function Pm(e,t){if(e.include.kind===`file`)return H.resolve(t?H.dirname(t):process.cwd(),e.include.path)}function Fm(e){return e===void 0?void 0:H.resolve(e)}function Im(e,t){let r=Pm(e,e.source.path);if(r&&t.has(r))throw new n(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function Lm(e,t,r,i){let a=e.include.kind===`file`?Fm(t.source.path):void 0,o=new Set([r,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new n(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function Rm(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:bm(e.true,t,n.platform)}function zm(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function Bm(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>Bm(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Bm(n,t)])):e}function Vm(e,t){return b({appId:e.appId,env:e.env,generation:e.generation,invalidateObservation:e.invalidateObservation,source:t?.source,cachedObservation:e.cachedObservation,signal:e.signal})}function Hm(e){return b({env:e.env,generation:e.generation,cachedObservation:e.cachedObservation,signal:e.signal})}async function Um(e,t){let n=Jm(await t.observe({condition:e.condition,timeoutMs:e.timeoutMs},Hm(e)),e.generation),r={kind:`selector`,selector:e.condition.selector,visible:n.visible,candidateCount:n.candidateCount,...n.ref?{ref:n.ref}:{},...e.condition.childOf?{childOf:e.condition.childOf}:{}};return{generation:e.generation,matched:Wm(e.condition,n),candidateCount:n.candidateCount,evidence:r}}function Wm(e,t){return e.kind===`visible`?t.matched&&t.visible:!t.matched||!t.visible}async function Gm(e,t,n,r){let i=Jm(await r.resolveTarget({selector:e,...t},Vm(n,n.command)),n.generation);if(!i.matched||!i.visible||!i.rect)throw vm(`Maestro target did not resolve to a visible element.`,{selector:e,candidateCount:i.candidateCount});return{kind:`selector`,selector:e,query:{selector:e,...t},...i,rect:i.rect}}function Km(e){let t={kind:`selector`,selector:e.selector,visible:e.visible,candidateCount:e.candidateCount,...e.ref?{ref:e.ref}:{},...e.query.childOf?{childOf:e.query.childOf}:{}};return{generation:e.generation,matched:e.matched&&e.visible,candidateCount:e.candidateCount,evidence:t}}function qm(e){if(!e||typeof e!=`object`)return!1;let t=e;return[`x`,`y`,`width`,`height`].every(e=>typeof t[e]==`number`&&Number.isFinite(t[e]))}function Jm(e,t){return Ym(e,t),Xm(e),Zm(e),Qm(e),e}function Ym(e,t){if(e.generation!==t)throw new n(`COMMAND_FAILED`,`Maestro target evidence generation ${e.generation} does not match ${t}.`)}function Xm(e){if(!Number.isInteger(e.candidateCount)||e.candidateCount<0)throw new n(`COMMAND_FAILED`,`Maestro target evidence has an invalid candidate count.`)}function Zm(e){if(e.rect!==void 0&&!qm(e.rect)||e.viewport!==void 0&&!qm(e.viewport))throw new n(`COMMAND_FAILED`,`Maestro target evidence has invalid geometry.`)}function Qm(e){if(e.surfaceSignature!==void 0&&typeof e.surfaceSignature!=`string`)throw new n(`COMMAND_FAILED`,`Maestro target evidence has an invalid surface signature.`)}const $m=new Set(`^$\\.*+?()[]{}|`);function eh(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function th(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if($m.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!$m.has(i))return;t+=i,n+=1}return t}function nh(e,t){let n=[t.id===void 0?void 0:ih(e.identifier,t.id),t.text===void 0?void 0:ah(e,t.text),t.label===void 0?void 0:ih(e.label,t.label)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function rh(e){return e.matches.filter(t=>et({predicate:`visible`,node:t,nodes:e.nodes,platform:e.platform}).pass)}function ih(e,t){let n=e??``;return g(n)===g(t)?!0:eh(n,t)}function ah(e,t){return[e.label,it(e),e.identifier].filter(e=>!!e).some(e=>ih(e,t))}function oh(e,t,n,r,i){let a=sh(e,t,n,i);if(!a)return;let{start:o,end:s}=dh(a,n);return{gesture:{from:o,to:s,durationMs:r},viewport:a}}function sh(e,t,n,r){let i=n===`up`||n===`down`,a=rh({nodes:e.nodes,matches:e.nodes.filter(e=>ur(e.type)),platform:r}),o=Wn(e.nodes)??ch(a);if(!o||!$e(o))return;let s=a.flatMap(e=>{if(!$e(e.rect))return[];let t=lh(e.rect,o);return!t||(i?t.height<=t.width:t.width<t.height)?[]:[{node:e,viewport:t}]}),c=new Map(e.nodes.map(e=>[e.index,e])),l=new Map(s.map(e=>[e.node.index,e]));for(let n of e.nodes.filter(e=>nh(e,t))){let e=or(n,c,{includeSelf:!0}),t=e?l.get(e.index):void 0;if(t)return t.viewport}return s.sort(uh)[0]?.viewport}function ch(e){let t;for(let n of e)$e(n.rect)&&(!t||n.rect.width*n.rect.height>t.width*t.height)&&(t=n.rect);return t}function lh(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width)-n,a=Math.min(e.y+e.height,t.y+t.height)-r;return i>0&&a>0?{x:n,y:r,width:i,height:a}:void 0}function uh(e,t){return t.viewport.width*t.viewport.height-e.viewport.width*e.viewport.height}function dh(e,t){let n=Y(e,.5,.5),r=B.scrollUntilVisibleSwipe.nearEdgeFraction,i=B.scrollUntilVisibleSwipe.farEdgeFraction;switch(t){case`up`:return{start:n,end:Y(e,.5,i)};case`down`:return{start:n,end:Y(e,.5,r)};case`left`:return{start:n,end:Y(e,i,.5)};case`right`:return{start:n,end:Y(e,r,.5)}}}async function fh(e,t,r){let i=q(e.duration,`swipe.duration`);if(e.kind===`coordinates`){if(e.start.space!==e.end.space)throw new n(`INVALID_ARGS`,`Maestro swipe endpoints must use the same coordinate space.`);let a=e.start.space===`percent`?await r.resolveGestureViewport(Vm(t,t.command)):void 0;return{authored:e,gesture:mh(await ph(e.start,t,r,a),await ph(e.end,t,r,a),i),...a?{viewport:a}:{}}}if(e.kind===`screen`){let n=await r.resolveGestureViewport(Vm(t,t.command)),{start:a,end:o}=hh(n,e.direction,r.platform);return{authored:e,gesture:mh(a,o,i),viewport:n}}let a=await Gm(e.from,{purpose:`swipe`,timeoutMs:`optional`in t.command&&t.command.optional===!0?B.command.optionalTargetLookupTimeoutMs:B.command.targetLookupTimeoutMs},t,r),o=a.viewport??await r.resolveGestureViewport(Vm(t,t.command)),{start:s,end:c}=gh(a,e.direction,o);return{authored:e,gesture:mh(s,c,i),target:a,viewport:o}}async function ph(e,t,n,r){if(e.space===`absolute`)return{x:e.x,y:e.y};let i=r??await n.resolveGestureViewport(Vm(t,t.command));return{x:i.x+Math.trunc(i.width*e.x/100),y:i.y+Math.trunc(i.height*e.y/100)}}function mh(e,t,n){return{from:e,to:t,durationMs:n??B.command.swipeDurationMs}}function hh(e,t,n){if(t===`left`||t===`right`){let n=ht(t,{referenceWidth:e.width,referenceHeight:e.height});return{start:{x:e.x+n.x1,y:e.y+n.y1},end:{x:e.x+n.x2,y:e.y+n.y2}}}let r=B.screenSwipe,i=Y(e,r.centerFraction,r.nearEdgeFraction),a=Y(e,r.centerFraction,r.farEdgeFraction),o=Y(e,r.centerFraction,r.downStartFraction),s=Y(e,r.centerFraction,r.upStartFraction[n]);return t===`up`?{start:s,end:i}:{start:o,end:a}}function Y(e,t,n){return{x:e.x+Math.trunc(e.width*t),y:e.y+Math.trunc(e.height*n)}}function gh(e,t,n){let r=wt(e.rect),i=n.x+Math.trunc(n.width*B.targetSwipe.nearEdgeFraction),a=n.y+Math.trunc(n.height*B.targetSwipe.nearEdgeFraction),o=n.x+Math.trunc(n.width*B.targetSwipe.farEdgeFraction),s=n.y+Math.trunc(n.height*B.targetSwipe.farEdgeFraction);switch(t){case`up`:return{start:r,end:{x:r.x,y:a}};case`down`:return{start:r,end:{x:r.x,y:s}};case`left`:return{start:r,end:{x:i,y:r.y}};case`right`:return{start:r,end:{x:o,y:r.y}}}}const _h={launchApp:Sh,stopApp:Sh,openLink:Sh,tapOn:wh,doubleTapOn:wh,longPressOn:wh,swipe:kh,inputText:Ah,eraseText:Ah,scroll:jh,scrollUntilVisible:jh,hideKeyboard:jh,pressKey:jh,back:jh,waitForAnimationToEnd:jh,takeScreenshot:Ph,runScript:Ph,assertVisible:Fh,assertNotVisible:Fh,extendedWaitUntil:Fh},vh={launchApp:!0,stopApp:!0,openLink:!0,tapOn:!0,doubleTapOn:!0,longPressOn:!0,swipe:!0,inputText:!0,eraseText:!0,scroll:!0,scrollUntilVisible:!0,hideKeyboard:!0,pressKey:!0,back:!0,waitForAnimationToEnd:!0,takeScreenshot:!1,runScript:!1,assertVisible:!1,assertNotVisible:!1,extendedWaitUntil:!1};function yh(e){return vh[e.kind]}async function bh(e,t){let n=e.command;return await xh(n,e,t,Vm(e,n))}function xh(e,t,n,r){let i=_h[e.kind];return i(e,t,n,r)}async function Sh(e,t,n,r){switch(e.kind){case`launchApp`:return await X(n.launchApp,Ch(e,t),r,`invalidate`);case`stopApp`:return await X(n.stopApp,{appId:e.appId??t.appId},r,`invalidate`);case`openLink`:return await X(n.openLink,{link:e.link},r,`invalidate`)}}function Ch(e,t){return b({appId:e.appId??t.appId,stopApp:e.stopApp,clearState:e.clearState,arguments:e.arguments,launchArguments:e.launchArguments})}async function wh(e,t,n,r){switch(e.kind){case`tapOn`:return await Th(e,t,n,r);case`doubleTapOn`:{let i=await Uh(e.target,{purpose:`doubleTap`,timeoutMs:Dh(e)},t,n),a=q(e.delay,`doubleTapOn.delay`)??B.command.repeatDelayMs;return await X(n.doubleTapOn,{target:i,delay:a},r,`invalidate`,i.resolution?Km(i.resolution):void 0)}case`longPressOn`:{let i=await Uh(e.target,{purpose:`longPress`,timeoutMs:Dh(e)},t,n);return await X(n.longPressOn,{target:i},r,`invalidate`,i.resolution?Km(i.resolution):void 0)}}}async function Th(e,t,n,r){let i=await Eh(e,t,n);return await X(n.tapOn,Oh(e,i),r,`invalidate`,i.resolution?Km(i.resolution):void 0)}async function Eh(e,t,n){let r={purpose:`tap`,timeoutMs:Dh(e),index:q(e.index,`tapOn.index`),childOf:e.childOf,allowAtomicSelectorDispatch:e.repeat===void 0&&e.delay===void 0,...e.retryTapIfNoChange===!0?{includeSurfaceSignature:!0}:{}};return await Uh(e.target,r,t,n)}function Dh(e){return e.optional===!0?B.command.optionalTargetLookupTimeoutMs:B.command.targetLookupTimeoutMs}function Oh(e,t){let n=q(e.repeat,`tapOn.repeat`),r=q(e.delay,`tapOn.delay`),i=n===void 0?r:r??B.command.repeatDelayMs;return b({target:t,retryTapIfNoChange:e.retryTapIfNoChange,repeat:n,delay:i})}async function kh(e,t,n,r){let i=await fh(e.gesture,t,n);return await X(n.gesture,i.gesture,{...r,...i.viewport?{gestureViewport:i.viewport}:{}},`invalidate`,i.target?Km(i.target):void 0)}async function Ah(e,t,n,r){switch(e.kind){case`inputText`:return await X(n.inputText,b({text:e.text,label:e.label}),r,`invalidate`);case`eraseText`:return await X(n.eraseText,b({charactersToErase:q(e.charactersToErase,`eraseText.charactersToErase`)}),r,`invalidate`)}}async function jh(e,t,n,r){switch(e.kind){case`scroll`:return await X(n.scroll,{direction:`down`},r,`invalidate`);case`scrollUntilVisible`:return await X(n.scrollUntilVisible,Mh(e),r,`invalidate`);case`hideKeyboard`:return await X(n.hideKeyboard,{},r,`invalidate`);case`pressKey`:return await X(n.pressKey,{key:e.key},r,`invalidate`);case`back`:return await X(n.back,{},r,`invalidate`);case`waitForAnimationToEnd`:return await X(n.waitForAnimationToEnd,Nh(e),r,`preserve`)}}function Mh(e){return{selector:e.element,direction:e.direction??`down`,timeoutMs:q(e.timeout,`scrollUntilVisible.timeout`)??B.command.scrollUntilVisibleTimeoutMs,durationMs:vi(B.command.scrollUntilVisibleSpeed)}}function Nh(e){return b({timeoutMs:q(e.timeout,`waitForAnimationToEnd.timeout`)})}async function Ph(e,t,n,r){switch(e.kind){case`takeScreenshot`:return Lh(await n.takeScreenshot({path:e.path},r),[],void 0,r.generation);case`runScript`:return await X(n.runScript,b({file:e.file,env:e.env}),r,`preserve`)}}async function Fh(e){throw new n(`COMMAND_FAILED`,`Maestro ${e.kind} must be executed by the observation engine.`)}async function X(e,t,n,r,i){let a=Ih(n,r);return Lh(await e(t,a),[],r===`preserve`?i:void 0,a.generation)}function Ih(e,t){return t===`preserve`?e:(e.invalidateObservation(),{...e,generation:e.generation+1})}function Lh(e,t,n,r){let i=e?.observation;return Rh(i,r),{...zh(n??i),...Bh(e?.outputEnv),...Vh(t,e?.artifactPaths),...Hh(e?.data),...e?.visualStabilityReached===void 0?{}:{visualStabilityReached:e.visualStabilityReached}}}function Rh(e,t){if(!(!e||t===void 0||e.generation===t))throw new n(`COMMAND_FAILED`,`Maestro operation evidence generation ${e.generation} does not match ${t}.`)}function zh(e){return e?{observation:e}:{}}function Bh(e){return e?{outputEnv:{...e}}:{}}function Vh(e,t){let n=[...new Set([...e,...t??[]])];return n.length>0?{artifactPaths:n}:{}}function Hh(e){return e&&Object.keys(e).length>0?{data:{...e}}:{}}async function Uh(e,t,n,r){if(e.space===`target`){let i=await Gm(e.selector,t,n,r);return{authored:e,point:wt(i.rect),resolution:i}}return{authored:e,point:await ph(e,n,r)}}async function Wh(e){return await Gh(`tap`,async t=>{let n=H.join(t,`before.png`),r=H.join(t,`after.png`),i=await qh(e,n);return await e.run({matchesCurrent:async()=>{if(!(!i||!await qh(e,r)))return await Kh(n,r,e.signal,`tap`)}})})}async function Gh(e,t){let n=await Ai.mkdtemp(H.join(ji.tmpdir(),`agent-device-maestro-${e}-`));try{return await t(n)}finally{try{await Ai.rm(n,{recursive:!0,force:!0})}catch{}}}async function Kh(e,t,n,r){try{let[i,a]=await Promise.all([Ai.readFile(e),Ai.readFile(t)]);Zh(n);let o=await Dt(i,a,`Maestro screenshot`);return Zh(n),Jh(o,r)}catch(e){Xh(e,n),d({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:r,result:`error`,error:e instanceof Error?e.message:String(e)}});return}}async function qh(e,t){try{return await Ai.rm(t,{force:!0}),Zh(e.signal),await e.capture(t),Zh(e.signal),!0}catch(t){return Xh(t,e.signal),!1}}function Jh(e,t){if(e.status!==`compared`)return Yh(t,e.status,e),!1;let n=e.differencePercent<=B.command.waitForAnimationToEndDifferencePercent;return Yh(t,n?`stable`:`changed`,e),n}function Yh(e,t,n){d({level:`debug`,phase:`maestro_screenshot_compare`,data:{purpose:e,result:t,first:n.first,second:n.second,...`differencePercent`in n?{differencePercent:n.differencePercent}:{}}})}function Xh(e,t){if(t?.aborted||$t(e))throw en()}function Zh(e){if(e?.aborted)throw en()}async function Qh(e){eg(e.timeoutMs),Zh(e.signal);let t=e.now()+e.timeoutMs;return await Gh(`animation`,async n=>{let r=H.join(n,`first.png`),i=H.join(n,`second.png`);for(;;){if(Zh(e.signal),await $h(e,r,i))return!0;if(e.now()>=t)return!1}})}async function $h(e,t,n){let r=[await qh(e,t),await qh(e,n)];return!r[0]||!r[1]?!1:await Kh(t,n,e.signal,`animation`)===!0}function eg(e){if(!Number.isFinite(e)||e<0)throw new n(`INVALID_ARGS`,`waitForAnimationToEnd timeout must be a non-negative number.`)}function tg(e,t,n,r){let i=ug(e,e.nodes.filter(e=>nh(e,t)),r),a=rh({nodes:e.nodes,matches:i.matches,platform:n});return{matches:i.matches,visible:a,ranked:ng(e.nodes,a,t,n),parentMatched:i.parentMatched}}function ng(e,t,n,r){if(r!==`ios`||!ag(n))return t;let i=Qe(e);return t.filter(r=>{if(lg(r))return!0;let a=t.filter(e=>e!==r&&og(r,e,n));return a.some(t=>lg(t)&&rt(e,r,t,i))?!1:!a.some(t=>rt(e,t,r,i))})}function rg(e,t){let n=t===void 0?e.find(ig):e[t];return!n||!ig(n)?null:{node:n,rect:n.rect}}function ig(e){return $e(e.rect)}function ag(e){return e.id!==void 0||e.label!==void 0||e.text!==void 0}function og(e,t,n){if(n.id!==void 0&&cg(e.identifier)!==cg(t.identifier)||n.label!==void 0&&cg(e.label)!==cg(t.label))return!1;if(n.text!==void 0){let n=sg(e),r=new Set(sg(t));if(!n.some(e=>r.has(e)))return!1}return!0}function sg(e){return[e.label,e.value,e.identifier].map(cg).filter(e=>e!==void 0)}function cg(e){if(e)return g(e)||void 0}function lg(e){let t=ft(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}function ug(e,t,n){if(!n)return{matches:t,parentMatched:!0};let r=e.nodes.filter(e=>nh(e,n));if(r.length===0)return{matches:[],parentMatched:!1};let i=Qe(e.nodes);return{matches:t.filter(t=>r.some(n=>rt(e.nodes,t,n,i))),parentMatched:!0}}function dg(e,t,n,r={}){let i=tg(e,t.selector,n,t.childOf);if(!i.parentMatched)return{ok:!1,message:`Maestro childOf parent did not match.`,evidence:hg(t,i.matches,[],void 0)};let{matches:a,ranked:o}=i,s=rg(o,t.index),c=hg(t,a,o,s?.node);if(!s)return fg(t,a,o,c);let l=n===`ios`&&(r.interactiveBounds||t.allowAtomicSelectorDispatch)?cr(e.nodes):void 0,u=r.interactiveBounds===!0?l?.sourceNodes.get(s.node.index)?.rect??s.rect:s.rect;return{ok:!0,node:s.node,rect:u,matches:o.length,dispatchCandidates:n===`ios`&&t.allowAtomicSelectorDispatch&&!t.childOf?pg(e,t,{...s,rect:u},l):0,evidence:c}}function fg(e,t,n,r){return t.length>0&&n.length===0?{ok:!1,message:`Maestro selector matched ${t.length} element(s), but none were visible.`,evidence:r}:{ok:!1,message:`Maestro selector did not match${e.index===void 0?``:` index ${e.index}`}.`,evidence:r}}function pg(e,t,n,i){let a=tg({...e,nodes:r((i??cr(e.nodes)).nodes)},t.selector,`ios`).ranked;if(a.length!==1)return a.length;let o=rg(a,void 0);return o&&o.node.hittable!==!1&&mg(o.rect,n.rect)?1:0}function mg(e,t){let n=wt(e),r=wt(t);return n.x===r.x&&n.y===r.y}function hg(e,t,n,r){return b({selector:e.selector,childOf:e.childOf,matched:t.length>0,visible:n.length>0,candidateCount:t.length,ref:r?.ref})}const gg=B.observation.pollIntervalMs;async function _g(e,t){for(;;){Z(e.context.signal);try{return await e.snapshot(e.context)}catch(n){if(!Ng(n)||(Z(e.context.signal),!await jg(e.dependencies,t,gg,e.context.signal)))throw n}}}function vg(e){return yg({...e,mode:e.query.purpose===`swipe`?`swipe`:`tap`})}function yg(e){let t=fi(e.snapshot);return wg(dg(e.snapshot,e.query,e.platform,{interactiveBounds:e.mode===`tap`}),e.snapshot,e.context.generation,t,e.query,e.platform,e.mode)}async function bg(e){Mg(e.timeoutMs,`observation`);let t,n=e.dependencies.now()+e.timeoutMs;for(;;){Z(e.context.signal);let r=await _g(e,n),i=yg({query:{selector:e.condition.selector,childOf:e.condition.childOf},context:e.context,snapshot:r,platform:e.platform,mode:`observe`});if(t=i,Wm(e.condition,i))return i;if(e.dependencies.now()>=n)break;await jg(e.dependencies,n,gg,e.context.signal)}return Z(e.context.signal),Ig(t)}async function xg(e){Mg(e.timeoutMs,`scrollUntilVisible`);let t=e.dependencies.now()+e.timeoutMs,n,r;for(;;){Z(e.context.signal);let i=r??await _g(e,t);if(r=void 0,n=yg({query:{selector:e.selector},context:e.context,snapshot:i,platform:e.platform,mode:`observe`}),n.visiblePercentage===B.command.scrollUntilVisiblePercentage)return n;if(e.dependencies.now()>=t)break;let a=t-e.dependencies.now();a>0&&(r=await e.scroll(a,i))}return Z(e.context.signal),Ig(n)}async function Sg(e){Mg(e.timeoutMs,`waitForAnimationToEnd`);let t=e.dependencies.now()+e.timeoutMs,n=e.initialSnapshot??await _g(e,t),r=Pg(n);for(;;){Z(e.context.signal),await jg(e.dependencies,t,gg,e.context.signal);let i=await _g(e,t),a=Pg(i);if(a===r)return{snapshot:i,signature:a};if(n=i,r=a,e.dependencies.now()>=t)return{snapshot:n,signature:r}}}function Cg(e){return e?{x:0,y:0,width:e.referenceWidth,height:e.referenceHeight}:void 0}function wg(e,t,n,r,i,a,o){if(!e.ok){let t=Cg(r);return{generation:n,matched:e.evidence.matched,visible:e.evidence.visible,candidateCount:e.evidence.candidateCount,...e.evidence.ref?{ref:e.evidence.ref}:{},...t?{viewport:t}:{}}}let s=Eg({query:i,platform:a,mode:o,dispatchCandidates:e.dispatchCandidates}),c=Cg(r);return{generation:n,matched:!0,visible:!0,...c?{visiblePercentage:Tg(e.rect,c)}:{},candidateCount:e.evidence.candidateCount,rect:e.rect,...e.evidence.ref?{ref:e.evidence.ref}:{},...c?{viewport:c}:{},...s?{dispatchSelector:s}:{},...i.includeSurfaceSignature?{surfaceSignature:Pg(t)}:{}}}function Tg(e,t){return!$e(e)||!$e(t)?0:nt(t,e)?100:Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))*100/(e.width*e.height)}function Eg(e){let{query:t,platform:n,mode:r,dispatchCandidates:i}=e;if(!(!Dg(t,n,r)||i!==1))return Og(t.selector)}function Dg(e,t,n){return t===`ios`&&n===`tap`&&e.allowAtomicSelectorDispatch===!0&&e.index===void 0&&e.childOf===void 0}function Og(e){let t=Object.entries(e).filter(([,e])=>e!==void 0);if(t.length!==1)return;let[n,r]=t[0];if(!kg(n)||typeof r!=`string`)return;let i=th(r)?.trim();return i?{key:n,value:i}:void 0}function kg(e){return e===`id`||e===`label`||e===`text`}async function Ag(e,t,n){try{await e.sleep(t,n)}catch(e){throw n?.aborted?en():e}Z(n)}async function jg(e,t,n,r){let i=t-e.now();return i<=0?!1:(await Ag(e,Math.min(n,i),r),!0)}function Z(e){if(e?.aborted)throw en()}function Mg(e,t){if(!Number.isFinite(e)||e<0)throw new n(`INVALID_ARGS`,`${t} timeout must be a non-negative number.`)}function Ng(e){return e instanceof n&&e.details?.retriable===!0}function Pg(e){return ki(`sha256`).update(JSON.stringify([...e.nodes].sort((e,t)=>e.index-t.index).map(e=>({index:e.index,parentIndex:e.parentIndex,identifier:e.identifier??``,label:e.label??``,value:e.value??``,enabled:e.enabled??!1,selected:e.selected??!1,focused:e.focused??!1,bounds:Fg(e.rect)})))).digest(`hex`)}function Fg(e){if(e)return{left:Math.trunc(e.x),top:Math.trunc(e.y),right:Math.trunc(e.x+e.width),bottom:Math.trunc(e.y+e.height)}}function Ig(e){if(e)return e;throw new n(`COMMAND_FAILED`,`Maestro observation completed without a snapshot result.`)}function Lg(e){return Rg(e)?zg(e):Yg(e)?Xg(e):Ug(e)}function Rg(e){return e.kind===`launchApp`||e.kind===`stopApp`||e.kind===`openLink`}function zg(e){switch(e.kind){case`launchApp`:return Bg(e);case`stopApp`:return Vg(e);case`openLink`:return Hg(e)}}function Bg(e){return{command:`open`,positionals:e.appId?[e.appId]:[],flags:{...e.relaunch?{relaunch:!0}:{},...e.clearState?{clearAppState:!0}:{},...e.launchArgs.length>0?{launchArgs:e.launchArgs}:{}}}}function Vg(e){return{command:`close`,positionals:e.appId?[e.appId]:[],internal:{closeAppOnly:!0}}}function Hg(e){return{command:`open`,positionals:e.appId?[e.appId,e.link]:[e.link],...e.prewarmRunner?{flags:{maestro:{prewarmRunnerBeforeOpen:!0}}}:{}}}function Ug(e){switch(e.kind){case`typeText`:return{command:`type`,positionals:[e.text]};case`clickSelector`:return Wg(e);case`clickPoint`:return Gg(e);case`swipe`:return Kg(e);case`scroll`:return qg(e);case`pressKey`:return Jg(e)}}function Wg(e){return{command:`click`,positionals:[`${e.selector.key}=${JSON.stringify(e.selector.value)}`],flags:{...e.options,maestro:{allowNonHittableCoordinateFallback:!0,expectedTapPoint:e.expectedPoint}}}}function Gg(e){return{command:`click`,positionals:[String(e.point.x),String(e.point.y)],flags:{...e.options}}}function Kg(e){let{from:t,to:n,durationMs:r}=e.gesture;return{command:`gesture`,positionals:[],input:{kind:`pan`,origin:t,delta:{x:n.x-t.x,y:n.y-t.y},durationMs:r},flags:{postGestureStabilization:!1},internal:{gestureExecutionProfile:`endpoint-hold`,...e.viewport?{gestureViewport:e.viewport}:{}}}}function qg(e){return{command:`scroll`,positionals:[e.direction],...e.durationMs===void 0?{}:{input:{direction:e.direction,durationMs:e.durationMs}},flags:{postGestureStabilization:!1}}}function Jg(e){return e.key===`back`||e.key===`home`?{command:e.key,positionals:[]}:{command:`keyboard`,positionals:[e.key]}}function Yg(e){return e.kind===`screenshot`||e.kind===`snapshot`}function Xg(e){switch(e.kind){case`screenshot`:return{command:`screenshot`,positionals:[e.path],...e.stabilize===!1||e.captureBackend===`runner`?{flags:{...e.stabilize===!1?{screenshotNoStabilize:!0}:{},...e.captureBackend===`runner`?{maestro:{screenshotCaptureBackend:`runner`}}:{}}}:{}};case`snapshot`:return{command:`snapshot`,positionals:[],flags:{noRecord:!0}}}}async function Zg(e,t){let n=Lg(t),{input:r,flags:i,internal:a,...o}=e.baseReq,s=Qg(i,n.flags??{}),c=b({...a,...n.internal,...t.kind===`snapshot`?{observationOnly:!0}:{}}),l=await e.invoke(b({...o,command:n.command,positionals:n.positionals,input:n.input,flags:s,internal:Object.keys(c).length>0?c:void 0}));if(!l.ok)throw i_(l);return l.data}function Qg(e,t){let n=e?.maestro===void 0&&t.maestro===void 0?void 0:{...e?.maestro,...t.maestro},r=b({...e,...t,maestro:n});return Object.keys(r).length>0?r:void 0}function $g(e){return e?e.kind===`scalar`?[String(e.value)]:e.kind===`list`?e.values.map(String):Object.entries(e.values).flatMap(([e,t])=>[e,String(t)]):[]}function e_(e,t){return{generation:t.generation,matched:t.matched&&t.visible,candidateCount:t.candidateCount,evidence:{kind:`selector`,selector:e,visible:t.visible,candidateCount:t.candidateCount,...t.ref?{ref:t.ref}:{}}}}function t_(e){if(!e)return[];let t=[];if(typeof e.path==`string`&&t.push(e.path),Array.isArray(e.artifactPaths)&&t.push(...e.artifactPaths.filter(e=>typeof e==`string`)),Array.isArray(e.artifacts))for(let n of e.artifacts)typeof n.localPath==`string`?t.push(n.localPath):typeof n.path==`string`&&t.push(n.path);return[...new Set(t)]}function n_(e,t,r){if(H.isAbsolute(e))return e;let i=t.source?.path??r;if(!i)throw new n(`INVALID_ARGS`,`Maestro runScript file paths require a source path.`);return H.resolve(H.dirname(i),e)}function r_(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function i_(e){let t=e.error,r=b({...t.details??{},hint:t.hint??a_(t.details,`hint`),diagnosticId:t.diagnosticId??a_(t.details,`diagnosticId`),logPath:t.logPath??a_(t.details,`logPath`),retriable:t.retriable??o_(t.details,`retriable`),supportedOn:t.supportedOn??a_(t.details,`supportedOn`)});return new n(t.code,t.message,Object.keys(r).length?r:void 0)}function a_(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function o_(e,t){let n=e?.[t];return typeof n==`boolean`?n:void 0}function s_(e){let t,r,i,a,o,s=0,c=0,l=async r=>{c+=1;let i=await Zg(e,{kind:`snapshot`});if(!i||!Array.isArray(i.nodes))throw new n(`COMMAND_FAILED`,`Maestro snapshot did not return node data.`);let a=i;return t={generation:r.generation,snapshot:a},a};return{capture:async e=>{if(r?.generation===e.generation){let n=r.snapshot;return r=void 0,t={generation:e.generation,snapshot:n},n}return r=void 0,await l(e)},bindObservation:e=>{if(t?.generation!==e.generation)return e;let n=`maestro-observation-${++s}`;return t.observationIdentity=n,{...e,identity:n}},reuseObservation:e=>{if(e.cachedObservation?.generation===e.generation&&e.cachedObservation.identity!==void 0&&t?.generation===e.generation&&e.cachedObservation.identity===t.observationIdentity)return t.snapshot},readMetrics:()=>({hierarchyCaptures:c}),invalidate:e=>{i=t?.generation===e-1?{generation:e,snapshot:t.snapshot}:void 0,t=void 0,r=void 0},requireStability:e=>{o=e,a=i?.generation===e?i:void 0,i=void 0,r=void 0},consumeStabilityFromVisualWait:e=>{if(o!==void 0){if(o!==e.generation)throw new n(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${e.generation}.`);o=void 0,a=void 0,i=void 0,r=void 0}},prime:(e,t)=>{r={generation:e,snapshot:t}},settlePending:async i=>{if(o===void 0)return;if(o!==i.generation)throw new n(`COMMAND_FAILED`,`Maestro stability generation ${o} does not match ${i.generation}.`);let s=t?.generation===i.generation?t.snapshot:a?.snapshot,c=await Sg({timeoutMs:yi,context:i,snapshot:l,dependencies:e.dependencies,...s?{initialSnapshot:s}:{}});o=void 0,a=void 0,r={generation:i.generation,snapshot:c.snapshot}}}}function c_(e){let t=s_(e),r={screenshotCaptures:0,tapRetries:0},i=e.platform,a=t=>(t.kind===`screenshot`&&(r.screenshotCaptures+=1),Zg(e,t)),o=async(e,n,r=`none`)=>{t.invalidate(n.generation);try{return await e()}finally{r===`deferred`&&t.requireStability(n.generation)}},s=async(e,t,n=`none`)=>await o(()=>a(e),t,n),c=async(n,r)=>{u(n),await s({kind:`typeText`,text:n},r);let i=await Sg({timeoutMs:yi,context:r,snapshot:t.capture,dependencies:e.dependencies});t.prime(r.generation,i.snapshot)};return{operations:{platform:i,resolveTarget:async(n,r)=>await l_({input:n,context:r,snapshots:t,options:e}),observe:async(n,r)=>await bg({condition:n.condition,timeoutMs:n.timeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies,platform:i}),resolveGestureViewport:async t=>{let r=await e.dependencies.resolveGestureViewport(t);if(!r)throw new n(`COMMAND_FAILED`,`Unable to resolve Maestro gesture viewport.`);return r},launchApp:async(e,t)=>{let n=e.appId??t.appId,r=[...$g(e.arguments),...$g(e.launchArguments)],i=e.clearState===!0,a=!i&&e.stopApp!==!1;await s({kind:`launchApp`,...n?{appId:n}:{},relaunch:a,clearState:i,launchArgs:r},t,`deferred`)},stopApp:async(e,t)=>{let n=e.appId??t.appId;await s({kind:`stopApp`,...n?{appId:n}:{}},t)},openLink:async(e,t)=>{await s({kind:`openLink`,...t.appId?{appId:t.appId}:{},link:e.link,prewarmRunner:i===`ios`},t,`deferred`)},tapOn:async(n,i)=>await p_(e,t,r,n.target,i,{click:{count:n.repeat,intervalMs:n.delay},retryIfNoChange:n.retryTapIfNoChange===!0}),doubleTapOn:async(t,n)=>{await o(()=>b_(e,t.target.point,b({doubleTap:!0,intervalMs:t.delay})),n,`deferred`)},longPressOn:async(t,n)=>{await o(()=>b_(e,t.target.point,{holdMs:B.command.longPressDurationMs}),n,`deferred`)},gesture:async(e,t)=>{let n=await s({kind:`swipe`,gesture:e,...t.gestureViewport?{viewport:t.gestureViewport}:{}},t,`deferred`);return n?{data:n}:void 0},inputText:async(e,t)=>await c(e.text,t),eraseText:async(e,t)=>await c(`\b`.repeat(e.charactersToErase??B.command.eraseTextMaxCharacters),t),scroll:async(e,t)=>{await s({kind:`scroll`,direction:e.direction},t,`deferred`)},scrollUntilVisible:async(n,r)=>{let a=await xg({selector:n.selector,direction:n.direction,timeoutMs:n.timeoutMs,context:r,snapshot:t.capture,dependencies:e.dependencies,platform:i,scroll:async(a,o)=>{let c=oh(o,n.selector,n.direction,n.durationMs,i);return await s(c?{kind:`swipe`,...c}:{kind:`scroll`,direction:n.direction,durationMs:n.durationMs},r),(await Sg({timeoutMs:Math.min(yi,a),context:r,snapshot:t.capture,dependencies:e.dependencies})).snapshot}});if(a.visiblePercentage!==B.command.scrollUntilVisiblePercentage)throw vm(`Maestro scrollUntilVisible target did not become visible.`,{selector:n.selector,timeoutMs:n.timeoutMs});return{observation:t.bindObservation(e_(n.selector,a))}},pressKey:async(e,t)=>{await s({kind:`pressKey`,key:e.key},t,`deferred`)},back:async(e,t)=>{await s({kind:`pressKey`,key:`back`},t,`deferred`)},hideKeyboard:async(e,t)=>{await s({kind:`pressKey`,key:`dismiss`},t,`deferred`)},waitForAnimationToEnd:async(t,n)=>({visualStabilityReached:await Qh({timeoutMs:t.timeoutMs??B.command.waitForAnimationToEndTimeoutMs,now:e.dependencies.now,signal:n.signal,capture:async t=>{await a({kind:`screenshot`,path:t,stabilize:!1,...e.platform===`ios`?{captureBackend:`runner`}:{}})}})}),takeScreenshot:async e=>({artifactPaths:t_(await a({kind:`screenshot`,path:e.path}))}),runScript:async(t,n)=>({outputEnv:lm({scriptPath:n_(t.file,n,e.sourcePath),env:{...n.env,...t.env?r_(t.env):{}}})})},snapshots:t,readMetrics:()=>({...t.readMetrics(),...r})}}async function l_(e){let{input:t,context:n,snapshots:r,options:i}=e,a=i.dependencies.now()+t.timeoutMs,o=e.allowObservationReuse===!1?void 0:r.reuseObservation(n);for(;;){let e=i.dependencies.now(),s=o!==void 0;o??=await _g({context:n,snapshot:r.capture,dependencies:i.dependencies},a);let c=vg({query:t,context:n,snapshot:o,platform:i.platform});if(d_(c,s))return c;if(o=void 0,!s){if(e>=a)return c;await jg(i.dependencies,a,gg,n.signal)}}}function u_(e){return e.matched&&e.visible&&e.rect!==void 0}function d_(e,t){return u_(e)?!t||e.dispatchSelector!==void 0:!1}function f_(e){let{operations:t,snapshots:n,readMetrics:r}=c_(e);return{execute:async e=>{let r=Vm(e,e.command),i=e.command.kind===`waitForAnimationToEnd`;yh(e.command)&&!i&&await n.settlePending(r);let a=await bh(e,t);return i&&a.visualStabilityReached===!0&&n.consumeStabilityFromVisualWait(r),delete a.visualStabilityReached,a},observe:async e=>{let r=await Um(e,t);return n.bindObservation(r)},readMetrics:r}}async function p_(e,t,n,r,i,a){let o=async()=>await __(e,t,r,i,a.click);if(!a.retryIfNoChange){try{await o()}finally{t.requireStability(i.generation)}return}if(e.platform===`ios`){await Wh({signal:i.signal,capture:async t=>{n.screenshotCaptures+=1,await Zg(e,{kind:`screenshot`,path:t,stabilize:!1,captureBackend:`runner`})},run:async o=>await m_(e,t,n,r,i,a.click,o)});return}await m_(e,t,n,r,i,a.click)}async function m_(e,t,n,r,i,a,o){let s=async()=>await __(e,t,r,i,a),c=await h_(r,t,i,o),l=async()=>await Sg({timeoutMs:yi,context:i,snapshot:t.capture,dependencies:e.dependencies});try{let e=await g_({baselineSignature:c,screenshotBaseline:o,dispatch:s,settle:l,onRetry:()=>{n.tapRetries+=1}});t.prime(i.generation,e.snapshot)}catch(e){throw t.requireStability(i.generation),e}}async function h_(e,t,n,r){if(e.resolution?.surfaceSignature)return e.resolution.surfaceSignature;if(!r)return Pg(await t.capture(n))}async function g_(e){await e.dispatch();let t=await e.settle(),n=1;for(;(e.baselineSignature===void 0||t.signature===e.baselineSignature)&&n<B.command.retryTapMaxAttempts&&!(e.screenshotBaseline&&await e.screenshotBaseline.matchesCurrent()!==!0);)e.onRetry(),await e.dispatch(),n+=1,t=await e.settle();return t}async function __(e,t,n,r,i){let a=n.resolution,o=a?.dispatchSelector;if(o&&n.point){t.invalidate(r.generation);try{await v_(e,o,n.point,i);return}catch(n){if(!y_(n))throw n;let o=await l_({input:a.query,context:r,snapshots:t,options:e,allowObservationReuse:!1});if(!u_(o))throw n;t.invalidate(r.generation),await b_(e,wt(o.rect),i);return}}t.invalidate(r.generation),await b_(e,n.point,i)}async function v_(e,t,n,r){d({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`selector`,selectorKey:t.key,expectedPoint:n}}),await Zg(e,{kind:`clickSelector`,selector:t,expectedPoint:n,options:r})}function y_(e){let t=s(e).code;return t===`AMBIGUOUS_MATCH`||t===`ELEMENT_NOT_FOUND`||t===`ELEMENT_OFFSCREEN`}async function b_(e,t,r){if(!t)throw new n(`COMMAND_FAILED`,`Maestro target did not resolve to a point.`);d({level:`debug`,phase:`maestro_tap_dispatch`,data:{kind:`point`,point:t}}),await Zg(e,{kind:`clickPoint`,point:t,options:r})}function x_(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return ki(`sha256`).update($d(t),`utf8`).digest(`hex`)}function S_(e={},t={}){let r={...t},i=C_(e),a=[],o,s=0,c;return{get values(){return l()},get generation(){return s},get observation(){return c?.generation===s?c:void 0},enter(e={}){let t=u(e);return a.push(t),o=void 0,()=>{if(a.pop()!==t)throw new n(`COMMAND_FAILED`,`Maestro environment scopes were left out of order.`);o=void 0}},merge(e){i={...i,...e},o=void 0},recordObservation(e){if(e.generation!==s)throw new n(`COMMAND_FAILED`,`Maestro observation generation ${e.generation} does not match ${s}.`);c=e},invalidateObservation(){s+=1,c=void 0},resolve(e){return w_(e,l())},resolveDeferred(e){return w_(e,l(),new Set,!1)}};function l(){return o||(o={...a.reduce((e,t)=>({...e,...t}),{...i}),...r},o)}function u(e){let t=C_(e),n={};for(let[e,i]of Object.entries(t))n[e]=w_(i,{...l(),...t,...n,...r},new Set,!1);return n}}function C_(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function w_(e,t,r=new Set,i=!0){let a=e.replace(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,a)=>{if(!Object.hasOwn(t,a)){if(!i)return e;throw new n(`INVALID_ARGS`,`Maestro variable "${a}" is not defined.`)}if(r.has(a)){if(!i)return e;throw new n(`INVALID_ARGS`,`Maestro variable "${a}" has a cyclic reference.`)}return w_(t[a],t,new Set([...r,a]),i)});return i&&T_(a),a}function T_(e){for(let t of e.matchAll(/\$\{[^{}]*\}/g))if(!E_(t[0]))throw new n(`INVALID_ARGS`,`Maestro interpolation "${t[0]}" is unresolved or unsupported.`)}function E_(e){return/^\$\{\s*maestro\.platform\s*(?:==|!=)\s*(['"]).*\1(?:\s*(?:&&|\|\|).*)?\s*\}$/.test(e)}async function D_(e,t){J(t.signal);let n=Fm(e.source.path),r={options:t,context:S_(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await O_(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function O_(e,t,n,r,i){J(i.options.signal);let a=z_(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await A_(s,a,o,e.source.path??r,i));return n}finally{s()}}async function k_(e,t,n,r,i){let a=[];for(let o of e)a.push(...await A_(o,t,n,r,i));return a}async function A_(e,t,n,r,i){J(i.options.signal);let a=B_(e,r);switch(a.kind){case`runFlow`:{let e=M_(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await j_(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[L_(a,t,n,o)]}case`repeat`:return[L_(a,t,n,await k_(a.commands,t,n,r,i))];case`retry`:return[L_(a,t,n,await k_(a.commands,t,n,r,i))];default:return[I_(a,t,n)]}}async function j_(e,t,n,r,i){let a=P_(e,i.context),o=Im(a,i.activeIncludePaths),s=await Nm(a,i.options);J(i.options.signal);let c=Lm(a,s,o,i.activeIncludePaths),l=z_(t,e.env),u=i.context.enter(e.env);try{return await O_(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function M_(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:N_(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function N_(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return F_(t.context.resolveDeferred(e))?`opaque`:bm(e,t.context,t.options.platform)?void 0:`omit`}function P_(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function F_(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function I_(e,t,n){return b({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function L_(e,t,n,r){return b({kind:`opaque`,command:R_(e),source:e.source,scopes:t,body:r,appId:n})}function R_(e){switch(e.kind){case`runFlow`:return b({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return{kind:e.kind,source:e.source,times:e.times};case`retry`:return b({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function z_(e,t){return t===void 0?e:[...e,t]}function B_(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function V_(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await D_(e,t),a=H_(t.runtimeHints),o=b({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=x_(o);return U_({...o,digest:s})}function H_(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function U_(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))U_(t);return Object.freeze(e)}function W_(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`)return{allowed:!1,reason:`step ${t+1} (runScript) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function G_(e,t={}){let r=W_(e,t);if(!r.allowed)throw new n(`INVALID_ARGS`,r.reason);return r.startIndex}function K_(e,t){if(!Number.isInteger(t)||t<0||t>e.total)throw new n(`INVALID_ARGS`,`Maestro replay startIndex ${t} is out of range for a ${e.total}-step plan.`);return t}async function q_(e,t){J(t.options.signal);try{return await sv(e,t.context,async()=>await J_(e,t))}catch(t){throw cv(t,e)}}async function J_(e,t){if(e.kind===`command`)return await Y_(e.command,e.appId,t);await ev(e,t)}async function Y_(e,t,n){let r=jm(e,n.context);try{return await Q_(r,t,n)}catch(e){if(J(n.options.signal),Z_(r)&&ym(e)){n.warnings.push(X_(r,e)),n.skipped+=1;return}throw lv(e,r)}}function X_(e,t){let r=`${e.source.path?`${e.source.path}:`:``}line ${e.source.line}`,i=t instanceof n?t.message:String(t);return`Optional Maestro ${e.kind} skipped at ${r}: ${i}`}function Z_(e){return`optional`in e&&e.optional===!0}async function Q_(e,t,n){switch(e.kind){case`assertVisible`:await iv({kind:`visible`,selector:e.target,childOf:e.childOf},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await iv({kind:`notVisible`,selector:e.target,childOf:e.childOf},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`extendedWaitUntil`:await iv(ov(e),q(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await $_(e,t,n)}}async function $_(e,t,n){let r=b({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return J(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function ev(e,t){let n=jm(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await rv(n.when,t)){t.skipped+=1;return}t.executed+=1,await tv(e.body,t);return;case`repeat`:{let r=Mm(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)J(t.options.signal),await tv(e.body,t);return}case`retry`:{let r=Math.min(Mm(n.maxRetries,1,t.context,`retry.maxRetries`),B.control.retryMaxRetries);t.executed+=1,await nv(e.body,r,t);return}}}async function tv(e,t){for(let n of e)await q_(n,t)}async function nv(e,t,r){let i;for(let n=0;n<=t;n+=1){J(r.options.signal);try{await tv(e,r);return}catch(t){if(J(r.options.signal),!ym(dv(t)))throw t;i=cv(t,e[0])}}throw i||new n(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function rv(e,t){if(!Rm(e,t.context,t.options))return!1;for(let n of zm(e))if(J(t.options.signal),!(await av(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function iv(e,t,n){if(!(await av(e,t,n)).matched)throw vm(`Maestro ${e.kind} condition did not match.`)}async function av(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return J(n.options.signal),n.context.recordObservation(i),i}function ov(e){if(e.visible)return{kind:`visible`,selector:e.visible};if(e.notVisible)return{kind:`notVisible`,selector:e.notVisible};throw new n(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function sv(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function cv(e,t){if(uv(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:fv(e,t?.command),source:n,...t?{command:t.command}:{}}}function lv(e,t){return{kind:`maestroPlanStepFailure`,error:fv(e,t),source:t.source,command:t}}function uv(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function dv(e){return uv(e)?e.error:e}function fv(e,t){if(!(e instanceof n)||!t||/\bline \d+\b/.test(e.message))return e;let r=t.source.path?`${t.source.path}:`:``;return new n(e.code,`${e.message} (${r}line ${t.source.line})`,e.details)}async function pv(e,t,r={}){J(r.signal);let i=r.startIndex??0;if(!Number.isInteger(i)||i<0||i>e.total)throw new n(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${e.total}-step plan.`);let a={plan:e,port:t,options:r,context:S_(r.defaults,r.env?{...r.env}:{}),timing:bi,artifacts:new Set,warnings:[],executed:e.compatibility.staticallyExecutedControls,skipped:e.compatibility.staticallySkippedControls};for(let t=i;t<e.steps.length;t+=1)try{await mv(e.steps[t],t,a)}catch(e){throw dv(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function mv(e,t,n){J(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};gv(()=>n.options.observer?.commandStarted?.(s));try{let t=await q_(e,n);J(n.options.signal),gv(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...hv(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=cv(t,e);throw gv(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...hv(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts]})),o}}function hv(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries}}}function gv(e){try{e?.()}catch{}}async function _v(e,t,n={}){let r=vv(e,n);return await pv(e,t,{...n,startIndex:r})}function vv(e,t){return t.from!==void 0||t.planDigest!==void 0?G_(e,{from:t.from,planDigest:t.planDigest}):K_(e,t.startIndex??0)}function yv(e){let t=new Map;return async(n,r,i)=>{if(i?.aborted)throw en();let a=bv(n,r,e),o=t.get(a);if(o)return o;let s=Vr(V.readFileSync(a,`utf8`),{sourcePath:a});return t.set(a,s),s}}function bv(e,t,n){let r=t?H.dirname(t):n;return H.resolve(r,e)}function xv(e){return Am(e)?{command:e.kind,...e.kind===`runFlow`?Q(e.label??e.includePath):{}}:{command:e.kind,...Sv(e)}}function Sv(e){return Cv(e)?Q(Av(e.target)):wv(e)?Tv(e):e.kind===`inputText`?Q(`<text>`):Ev(e)}function Cv(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function wv(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Tv(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return Q(jv(e.target));case`extendedWaitUntil`:return Q(jv(e.visible??e.notVisible));case`scrollUntilVisible`:return Q(jv(e.element))}}function Ev(e){return Dv(e)?Ov(e):e.kind===`swipe`?kv(e):e.kind===`runFlow`?Q(e.label??(e.include.kind===`file`?e.include.path:``)):{}}function Dv(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function Ov(e){switch(e.kind){case`openLink`:return Q(e.link);case`takeScreenshot`:return Q(e.path);case`runScript`:return Q(e.file);case`pressKey`:return Q(e.key)}}function kv(e){return Q(e.gesture.kind===`coordinates`?`${Mv(e.gesture.start)} to ${Mv(e.gesture.end)}`:e.gesture.direction)}function Av(e){return e.space===`target`?jv(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function jv(e){return e?.id??e?.text??e?.label}function Mv(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function Q(e){return e?{value:e}:{}}function Nv(e){let{filePath:t,tracePath:n,onFailure:r}=e,i=new Map;return{commandStarted:e=>{i.set(e.stepIndex,e),Pv(()=>Lv(t,e)),Pv(()=>Rv(n,t,e))},commandCompleted:e=>{let r=Fv(i,e.stepIndex);Pv(()=>zv(n,t,Iv(r,e),!0))},commandFailed:e=>{let a=Fv(i,e.stepIndex);Pv(()=>r(e)),Pv(()=>zv(n,t,Iv(a,e),!1))}}}function Pv(e){try{e()}catch{}}function Fv(e,t){let n=e.get(t);return e.delete(t),n}function Iv(e,t){return b({...e??t,durationMs:t.durationMs,runtimeMetrics:t.runtimeMetrics,data:t.data,error:t.error})}function Lv(e,t){let n=qt();if(!n)return;let r=xv(t.command);P({type:`replay-test`,...n,file:n.file||e,status:`progress`,stepIndex:t.stepIndex,stepTotal:t.stepTotal,stepCommand:r.command,...r.value?{stepValue:r.value}:{}})}function Rv(e,t,n){let r=xv(n.command);af(e,{type:`replay_action_start`,ts:new Date().toISOString(),replayPath:t,...n.source.path&&n.source.path!==t?{sourcePath:n.source.path}:{},line:n.source.line,step:n.stepIndex,command:r.command,positionals:r.value?[r.value]:[]})}function zv(e,t,r,i){let a=Bv(r);af(e,{type:`replay_action_stop`,ts:new Date().toISOString(),replayPath:t,...r.source.path&&r.source.path!==t?{sourcePath:r.source.path}:{},line:r.source.line,step:r.stepIndex,command:xv(r.command).command,ok:i,durationMs:r.durationMs,...Object.keys(a).length>0?{resultTiming:a}:{},...!i&&r.error instanceof n?{errorCode:r.error.code}:{}})}function Bv(e){let t=Vv(e.data?.timing)?e.data.timing:void 0;return b({...e.runtimeMetrics??{},...typeof t?.executionProfile==`string`?{executionProfile:t.executionProfile}:{},...typeof t?.gestureDurationMs==`number`?{gestureDurationMs:t.gestureDurationMs}:{}})}function Vv(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Hv(e,t){let n=xv(e.command);return{command:e.command,source:e.source,progress:n,action:{command:$v(e.command.kind),positionals:ey(e.command.kind,n.value),flags:t.flags??{}}}}async function Uv(e){let{event:t,plan:n,replayPath:r,req:i,sessionName:a,sessionStore:o,logPath:s}=e,c=Zt(i.meta?.requestId),l=Hv(t,i),u=fp(e.error),d=ty(l.command),f=O(d),p={...u,message:f(u.message),...u.hint?{hint:f(u.hint)}:{}},m=o.get(a),h=m?await Xf({session:m,sessionName:a,sessionStore:o,logPath:s,action:l.action}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},g=m&&h.state===`available`&&!Am(l.command)?Gv({command:l.command,platform:n.platform,action:l.action,session:m,nodes:h.nodes,sanitize:f}):[],_=W_(n,{from:t.stepIndex,planDigest:n.digest}),v=[l.command.kind,Wv(l.progress.value)].filter(Boolean).join(` `),y=Uf({sessionStore:o,sessionName:a,divergence:{version:1,kind:`action-failure`,step:{index:t.stepIndex,source:{path:f(l.source.path??r),line:l.source.line}},action:f(v),cause:{code:p.code,message:p.message,...p.hint?{hint:p.hint}:{}},screen:ep(h,f),suggestions:g.slice(0,5),suggestionCount:g.length,resume:_.allowed?{allowed:!0,from:t.stepIndex,planDigest:n.digest}:{allowed:!1,from:t.stepIndex,planDigest:n.digest,reason:_.reason},repairHint:Of({kind:`action-failure`,targetEvidence:void 0,capture:Jf(h)})},responseLevel:i.meta?.responseLevel,evidence:h.state===`available`?h.evidence:void 0,...c?{signal:c}:{}});return mp({error:p,actionLabel:v,action:l.command.kind,positionals:[...l.action.positionals],step:t.stepIndex,replayPath:r,artifactPaths:[...t.artifactPaths],snapshotDiagnostics:e.snapshotDiagnostics,divergence:y,scrubVars:d})}function Wv(e){return!e||e===`<text>`?e??``:Ee(e)}function Gv(e){let t=qv(e.command);return!t||e.platform!==`android`&&e.platform!==`ios`?[]:Ef(Kv({createdAt:Date.now(),nodes:e.nodes},t,e.platform).map(e=>({node:e,nodeIndex:e.index,basis:Qv(t.selector,e)}))).map(({node:t,basis:n})=>dp({node:t,nodes:e.nodes,session:e.session,action:e.action,basis:n,sanitize:e.sanitize}))}function Kv(e,t,n){return tg(e,t.selector,n,t.childOf).ranked}function qv(e){if(Jv(e))return Yv(e);if(Xv(e))return Zv(e);if(e.kind===`swipe`&&e.gesture.kind===`target`)return{selector:e.gesture.from}}function Jv(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function Yv(e){if(e.target.space===`target`)return e.kind===`tapOn`?{selector:e.target.selector,index:e.index,childOf:e.childOf}:{selector:e.target.selector}}function Xv(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Zv(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element}}}function Qv(e,t){return e.id!==void 0||e.text!==void 0&&nh({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text!==void 0||e.label!==void 0?`label`:`other`}function $v(e){return e===`tapOn`||e===`doubleTapOn`?`click`:e===`longPressOn`?`longpress`:e===`assertVisible`||e===`assertNotVisible`||e===`extendedWaitUntil`||e===`scrollUntilVisible`?`wait`:e}function ey(e,t){return!t||e===`inputText`?[]:[t]}function ty(e){return e.kind!==`inputText`||e.text.length===0?[]:[{name:`${e.kind}.text`,value:e.text}]}function ny(e){let{result:t,plan:n,startIndex:r,startedAt:i,sessionName:a,sessionStore:o,snapshotStart:s}=e,c=iy(o,a,s),l=n.total-r;return{ok:!0,data:{replayed:l,healed:0,session:a,sessionActive:o.get(a)!==void 0,artifactPaths:t.artifactPaths,...t.warnings?{warnings:t.warnings}:{},...c?{snapshotDiagnostics:c}:{},message:oy(l,Date.now()-i)}}}async function ry(t){let{failedEvent:n,plan:r}=t.state,i=e(n?.error??t.error);return n&&r?await Uv({error:i,event:n,plan:r,replayPath:k.expandHome(t.requestedPath,t.req.meta?.cwd),req:t.req,sessionName:t.sessionName,sessionStore:t.sessionStore,logPath:t.logPath,snapshotDiagnostics:iy(t.sessionStore,t.sessionName,t.state.snapshotStart)}):L(i.code,i.message,{...i.details??{},...ay(n)})}function iy(e,t,n){return je(e.get(t)?.snapshotDiagnostics?.samples.slice(n)??[])}function ay(e){return e?{replaySource:e.source,replayStep:e.stepIndex,replayStepTotal:e.stepTotal}:{}}function oy(e,t){return`Replayed ${e} ${e===1?`step`:`steps`} in ${(t/1e3).toFixed(1)}s`}async function sy(e){let{req:t}=e,n=t.positionals?.[0];if(!n)return L(`INVALID_ARGS`,`replay requires a path`);if(t.flags?.saveScript!==void 0)return L(`INVALID_ARGS`,`Maestro YAML does not support --save-script; ADR 0012 repair recording applies only to .ad scripts.`);let r=Date.now(),i={snapshotStart:0};try{return await cy({...e,requestedPath:n,startedAt:r,state:i})}catch(t){return await ry({...e,requestedPath:n,state:i,error:t})}}async function cy(e){let{req:t,sessionName:n,sessionStore:r,tracePath:i,invoke:a,state:o}=e,s=await ly(e),c=await V_(s.program,{defaults:s.defaults,env:s.env,platform:s.platform,target:s.target,runtimeHints:s.runtimeHints,loadProgram:s.loadProgram,signal:s.signal});o.plan=c;let l=G_(c,{from:t.flags?.replayFrom,planDigest:t.flags?.replayPlanDigest}),u=hy({req:t,invoke:a,logPath:e.logPath,sessionName:n,sessionStore:r,device:s.device,platform:s.platform,runtimeHints:s.runtimeHints,sourcePath:s.filePath});return o.snapshotStart=r.get(n)?.snapshotDiagnostics?.samples.length??0,ny({result:await _v(c,u,{defaults:s.defaults,env:s.env,platform:s.platform,target:s.target,loadProgram:s.loadProgram,signal:s.signal,startIndex:l,observer:Nv({filePath:s.filePath,tracePath:i,onFailure:e=>{o.failedEvent=e}})}),plan:c,startIndex:l,startedAt:e.startedAt,sessionName:n,sessionStore:r,snapshotStart:o.snapshotStart})}async function ly(e){let{req:t,requestedPath:n,sessionName:r,sessionStore:i}=e,a=k.expandHome(n,t.meta?.cwd),o=Vr(V.readFileSync(a,`utf8`),{sourcePath:a}),s=i.get(r);s&&ui(s,t.flags);let c=await uy({req:t,sessionStore:i,sessionName:r,session:s,program:o});return{filePath:a,program:o,...c,defaults:py({req:t,sessionName:r,filePath:a,platform:c.platform,target:c.target}),env:my(t),signal:Zt(t.meta?.requestId),loadProgram:yv(H.dirname(a))}}async function uy(e){let{req:t,sessionStore:n,sessionName:r,session:i,program:a}=e,o=t.flags?.platform,s=i?.device??(o===`android`||o===`ios`?void 0:await cn(t.flags??{},ri(a,o))),c=xy(t,s),l=Xa({req:t,sessionStore:n,sessionName:r,device:s,platform:c});return await dy({req:t,sessionStore:n,sessionName:r,device:s,platform:c,target:Sy(t,s),runtimeHints:l,program:a})}async function dy(e){if(e.device||!fy(e.runtimeHints))return e;let t=await cn(e.req.flags??{},ri(e.program,e.platform));return{device:t,platform:e.platform,target:Sy(e.req,t),runtimeHints:Xa({req:e.req,sessionStore:e.sessionStore,sessionName:e.sessionName,device:t,platform:e.platform})}}function fy(e){return e?.metroPort!==void 0&&e.metroHost===void 0&&e.bundleUrl===void 0}function py(e){return{...nm({req:e.req,sessionName:e.sessionName,metadata:{},resolvedPath:e.filePath}),AD_PLATFORM:e.platform,AD_TARGET:e.target}}function my(e){return{...We(Pe(e.flags?.replayShellEnv)),...Re(Ve(e.flags?.replayEnv))}}function hy(e){let{req:t,invoke:r,logPath:i,sessionName:a,sessionStore:o,device:s,platform:c,runtimeHints:l,sourcePath:u}=e,{command:d,positionals:f,input:p,flags:m,...h}=t;return f_({baseReq:b({...h,flags:gy(s,c,t.flags),runtime:l}),invoke:r,platform:c,sourcePath:u,dependencies:{now:Date.now,sleep:async(e,t)=>{await Ni(e,void 0,{signal:t})},resolveGestureViewport:async()=>{let e=o.get(a);if(!e)throw new n(`SESSION_NOT_FOUND`,`No active session. Run open first.`);return await un(e.device,R(i,t.flags,e.appBundleId,e.trace?.outPath))}}})}function gy(e,t,n){if(!e)return _y(t,n);let r={platform:t,target:e.target,noRecord:!0};return t===`android`?{...r,serial:e.id}:{...r,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}}}function _y(e,t){let n={platform:e,target:t?.target??`mobile`,noRecord:!0};return t?.device&&(n.device=t.device),e===`android`?vy(n,t):yy(n,t)}function vy(e,t){return t?.serial&&(e.serial=t.serial),t?.androidDeviceAllowlist&&(e.androidDeviceAllowlist=t.androidDeviceAllowlist),e}function yy(e,t){return t?.udid&&(e.udid=t.udid),t?.iosSimulatorDeviceSet&&(e.iosSimulatorDeviceSet=t.iosSimulatorDeviceSet),e}function by(e,t){return e.flags?.replayBackend===`maestro`&&(H.extname(t)===`.yaml`||H.extname(t)===`.yml`)}function xy(e,t){let r=e.flags?.platform;if(r===`android`||r===`ios`)return r;if(t?.platform===`android`)return`android`;if(t?.platform===`apple`&&t.appleOs===`ios`)return`ios`;throw new n(`INVALID_ARGS`,`Maestro replay requires --platform android|ios or an active mobile session.`)}function Sy(e,t){return typeof e.flags?.target==`string`?e.flags.target:t?.target??`mobile`}async function Cy(e,t,n,r){let i=e.actionSourcePaths?.[n]??e.resolved,a=e.actionLines[n]??1,o=await Up({action:t,scope:e.scope,sourcePath:i,sourceLine:a,replayPath:e.resolved,step:n+1,sessionName:e.sessionName,sessionStore:e.sessionStore,logPath:e.logPath,artifactPaths:r,responseLevel:e.responseLevel,planActions:e.actions,planDigest:e.planDigest,signal:e.signal});if(!o.verified)return o.response;let s=o.guard,c=o.deferredLandmark,l=s?{replayTargetGuard:s.expected}:c?{replayLandmarkGuard:c}:void 0;return await wy({ctx:e,action:t,index:n,artifactPaths:r,sourcePath:i,sourceLine:a,response:await of({req:l?{...e.replayReq,internal:{...e.replayReq.internal,...l}}:e.replayReq,sessionName:e.sessionName,action:t,scope:e.scope,filePath:e.resolved,line:a,sourcePath:e.actionSourcePaths?.[n],step:n+1,tracePath:e.actionTracePath,invoke:e.invoke}),guard:s,deferredLandmark:c})}async function wy(e){let{ctx:t,action:n,index:r,artifactPaths:i,sourcePath:a,sourceLine:o,response:s}=e,c={action:n,scope:t.scope,failedResponse:s,sourcePath:a,sourceLine:o,replayPath:t.resolved,step:r+1,sessionName:t.sessionName,sessionStore:t.sessionStore,logPath:t.logPath,artifactPaths:i,responseLevel:t.responseLevel,planActions:t.actions,planDigest:t.planDigest,signal:t.signal};return e.guard&&Wp(s)?await qp({...c,guard:e.guard}):e.deferredLandmark&&Jp(s)?await Yp(c):s}async function Ty(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,tracePath:a,invoke:o}=e,c=t.positionals?.[0];if(!c)return L(`INVALID_ARGS`,`replay requires a path`);let l=Date.now(),u=``,d=new Set;try{u=k.expandHome(c,t.meta?.cwd);let s=await Py({...e,resolved:u});if(s)return s;let f=Fy({req:t,sessionName:n,sessionStore:i,tracePath:a,resolved:u});if(!f.ok)return f.response;let{replayReq:p,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_,preEntrySession:v,entryIndex:y,scope:b,actionTracePath:x,snapshotDiagnosticSamples:S}=f.value,C=zy({req:t,entryIndex:y,preEntrySession:v,sessionStore:i,sessionName:n,sourcePath:u});if(!C.ok)return C.response;let ee={scope:b,replayReq:p,sessionName:n,sessionStore:i,logPath:r,resolved:u,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_,actionTracePath:x,responseLevel:t.meta?.responseLevel,invoke:o,signal:Zt(t.meta?.requestId)};return await Ey({req:t,sessionName:n,sessionStore:i,logPath:r,resolved:u,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_,entryIndex:y,scope:b,stepContext:ee,artifactPaths:d,snapshotDiagnosticSamples:S,armSaveScript:C.armSaveScript})||ky({startedAt:l,sessionName:n,sessionStore:i,actions:m,entryIndex:y,artifactPaths:d,snapshotDiagnosticSamples:S,armSaveScript:C.armSaveScript})}catch(e){let t=s(e);return L(t.code,t.message,d.size>0?{artifactPaths:[...d]}:void 0)}}async function Ey(e){let{sessionName:t,sessionStore:n,resolved:r,actions:i,entryIndex:a,stepContext:o,artifactPaths:s,snapshotDiagnosticSamples:c,armSaveScript:l}=e;for(let u=a;u<i.length;u+=1){let a=i[u];if(!Dy(a)||(l(),Gy({action:a,index:u,totalActions:i.length,sessionStore:n,sessionName:t})))continue;Ay(r,u,i.length,a);let d=eb(n,t),f=await Cy(o,a,u,[...s]);if(c.push(...tb(n,t,d)),ff(f).forEach(e=>s.add(e)),!f.ok)return await Oy(e,a,u,f)}}function Dy(e){return!!(e&&e.command!==`replay`)}async function Oy(e,t,n,r){let i=t=>Jy({response:t,sessionStore:e.sessionStore,sessionName:e.sessionName});return $y(r)?i(r):i(await vp({response:r,action:t,index:n,replayPath:e.resolved,sourcePath:e.actionSourcePaths?.[n]??e.resolved,sourceLine:e.actionLines[n]??1,artifactPaths:[...e.artifactPaths],snapshotDiagnosticSamples:e.snapshotDiagnosticSamples,scope:e.scope,req:e.req,sessionName:e.sessionName,sessionStore:e.sessionStore,logPath:e.logPath,planActions:e.actions,planDigest:e.planDigest}))}function ky(e){let{startedAt:t,sessionName:n,sessionStore:r,actions:i,entryIndex:a,artifactPaths:o,snapshotDiagnosticSamples:s,armSaveScript:c}=e;c();let l=r.get(n);l?.saveScriptBoundary!==void 0&&(l.saveScriptComplete=!0,r.set(n,l));let u=i.length-a,d=je(s);return{ok:!0,data:{replayed:u,healed:0,session:n,sessionActive:l!==void 0,artifactPaths:[...o],...d?{snapshotDiagnostics:d}:{},message:Qy(u,Date.now()-t)}}}function Ay(e,t,n,r){let i=qt();i&&P({type:`replay-test`,...i,file:i.file||e,status:`progress`,stepIndex:t+1,stepTotal:n,...jy(r)})}function jy(e){return{stepCommand:e.command,...My(e)}}function My(e){let t=e.positionals??[],n=Ny(t[0]);return n?{stepValue:n}:t.length===0?{}:{stepValue:t.join(` `)}}function Ny(e){if(!e)return;let t=x(e);if(!t)return;let n=t.selectors.flatMap(e=>e.terms.flatMap(e=>(e.key===`label`||e.key===`text`||e.key===`id`)&&typeof e.value==`string`?[e.value]:[]));if(n.length===0)return;let r=n[0];return r&&n.every(e=>e===r)?r:void 0}async function Py(e){if(by(e.req,e.resolved))return e.sessionStore.get(e.sessionName)?.saveScriptBoundary===void 0?await sy(e):L(`INVALID_ARGS`,`This session has an active .ad --save-script repair run; finish it with replay --from or close before running Maestro YAML.`)}function Fy(e){let{req:t,sessionName:n,sessionStore:r,tracePath:i,resolved:a}=e,o=Iy(a,t);if(!o.ok)return o;let{metadata:s,actions:c,actionLines:l,actionSourcePaths:u}=o.value,d=Ly({...t,flags:Cr(t.flags,c)},s),f=tf({actions:c,actionLines:l,actionSourcePaths:u,metadata:Sp(d.flags)}),p=r.get(n),m=Cp(t.flags,c.length,f,p?.pendingRecordAndHeal,p?.actions.length??0);return m.ok?{ok:!0,value:{replayReq:d,actions:c,actionLines:l,actionSourcePaths:u,planDigest:f,preEntrySession:p,entryIndex:m.value,scope:Ry({req:t,replayReq:d,sessionName:n,resolved:a,metadata:s}),actionTracePath:i??p?.trace?.outPath,snapshotDiagnosticSamples:[]}}:m}function Iy(e,t){let n=V.readFileSync(e,`utf8`),r=n.trimStart()[0];return r!==`{`&&r!==`[`?{ok:!0,value:kr(n,t.flags)}:{ok:!1,response:L(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`)}}function Ly(e,t){return!t.platform&&!t.target?e:{...e,flags:xp(e.flags,t)}}function Ry(e){let{req:t,replayReq:n,sessionName:r,resolved:i,metadata:a}=e;return we({builtins:nm({req:n,sessionName:r,metadata:a,resolvedPath:i}),fileEnv:a.env,shellEnv:We(Pe(t.flags?.replayShellEnv)),cliEnv:Re(Ve(t.flags?.replayEnv))})}function zy(e){let{req:t,entryIndex:n,preEntrySession:r,sessionStore:i,sessionName:a,sourcePath:o}=e,s=By({entryIndex:n,sessionStore:i,sessionName:a});return s?{ok:!1,response:s}:(Hy({req:t,preEntrySession:r,sessionStore:i,sessionName:a}),Vy({req:t,sessionStore:i,sessionName:a,sourcePath:o}))}function By(e){let t=Uy(e);if(t)return t;if(e.entryIndex>0&&!e.sessionStore.get(e.sessionName))return on()}function Vy(e){let{req:t,sessionStore:n,sessionName:r,sourcePath:i}=e,a=n.get(r),{saveScript:o,force:s}=t.flags??{},{saveScriptForce:c,saveScriptPath:l,saveScriptBoundary:u}=a??{};if(o&&a?.scriptRecordingState!==void 0)return{ok:!1,response:L(`INVALID_ARGS`,`replay --save-script cannot re-arm an ordinary recording in terminal/active state ${a.scriptRecordingState}. Close this session and use a fresh one for repair authoring.`)};let d=Wy({saveScript:o,liveForce:s,persistedForce:c,sourcePath:i,existingSaveScriptPath:l});return d?{ok:!1,response:d}:(a&&u!==void 0&&(a.saveScriptComplete=!1),{ok:!0,armSaveScript:Ky({saveScript:o,force:s,sessionStore:n,sessionName:r,sourcePath:i})})}function Hy(e){let{req:t,preEntrySession:n,sessionStore:r,sessionName:i}=e;n&&n.pendingRecordAndHeal?.expectedFrom===t.flags?.replayFrom&&(Zd(n),r.set(i,n)),t.flags?.saveScript&&r.clearRepairTombstone(i)}function Uy(e){let{entryIndex:t,sessionStore:n,sessionName:r}=e;if(!(t>0)&&n.get(r)?.saveScriptBoundary!==void 0)return L(`INVALID_ARGS`,`This session has an active --save-script repair run; continue it with replay --from <n> --plan-digest <sha256>, or finish with close, before starting a fresh full replay.`)}function Wy(e){let{saveScript:t,liveForce:n,persistedForce:r,sourcePath:i,existingSaveScriptPath:a}=e;if(!t)return;let o=typeof t==`string`?He(t):a??Zy(i);if(!(n||r&&o===a)&&V.existsSync(o))return L(`COMMAND_FAILED`,`A file already exists at ${o}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`)}function Gy(e){let{action:t,index:n,totalActions:r,sessionStore:i,sessionName:a}=e;return t.command!==`close`||n!==r-1?!1:i.get(a)?.saveScriptBoundary!==void 0}function Ky(e){let{saveScript:t,force:n,sessionStore:r,sessionName:i,sourcePath:a}=e;if(!t)return()=>{};let o=!0;return()=>{qy({sessionStore:r,sessionName:i,saveScript:t,force:n,sourcePath:a,firstArm:o}),o=!1}}function qy(e){let{sessionStore:t,sessionName:n,saveScript:r,force:i,sourcePath:a,firstArm:o}=e,s=t.get(n);s&&(s.recordSession=!0,typeof r==`string`?(ke(s,He(r),i),s.saveScriptDefaultedHealedPath=!1):s.saveScriptPath===void 0&&(s.saveScriptPath=Zy(a),s.saveScriptDefaultedHealedPath=!0),i&&(s.saveScriptForce=!0),s.saveScriptBoundary===void 0&&(s.saveScriptBoundary=o?s.actions.length:0),s.repairSourcePath===void 0&&(s.repairSourcePath=a),t.set(n,s))}function Jy(e){let{response:t,sessionStore:n,sessionName:r}=e;if(t.ok)return t;let i=n.get(r);if(i?.saveScriptBoundary===void 0||i.saveScriptCommitted)return t;let a=Yy(t);return a&&(a.repairSessionHeld=!0),t}function Yy(e){let t=e.error.details?.divergence;if(!(!S(t)||!Xy(t.resume)))return t.resume}function Xy(e){return!S(e)||typeof e.allowed!=`boolean`||!Number.isInteger(e.from)||typeof e.planDigest!=`string`?!1:e.allowed||typeof e.reason==`string`}function Zy(e){let t=H.dirname(e),n=H.basename(e,H.extname(e));return H.join(t,`${n}.healed.ad`)}function Qy(e,t){let n=(t/1e3).toFixed(1);return`Replayed ${e} ${e===1?`step`:`steps`} in ${n}s`}function $y(e){if(e.ok||e.error.code!==`REPLAY_DIVERGENCE`)return!1;let t=e.error.details?.divergence,n=t&&typeof t==`object`?t.kind:void 0;return typeof n==`string`&&n!==`action-failure`}function eb(e,t){return e.get(t)?.snapshotDiagnostics?.samples.length??0}function tb(e,t,n){return e.get(t)?.snapshotDiagnostics?.samples.slice(n)??[]}const nb=1e3,rb=3e3;function ib(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await ab(e)}}async function ab(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,artifactsDir:a,tracePath:o}=e;if(t.flags?.recordVideo!==!0)return;let s=i.get(n);if(!s||s.recording)return;let c=Ie(s.device.platform),l=a?H.join(a,`recording${c}`):Be(s.device.platform);sb(o,{type:`video_recording_start`,session:n,videoPath:l}),d({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:l}});let u=await Sr({req:{token:t.token,session:n,command:`record`,positionals:[`start`,l],flags:{},meta:t.meta},sessionName:n,sessionStore:i,logPath:r});if(!u.ok)return sb(o,{type:`video_recording_start_failed`,session:n,videoPath:l,errorCode:u.error.code}),u;let f=Date.now();return await vt(nb),sb(o,{type:`video_preroll_done`,session:n,durationMs:Date.now()-f,requestedDurationMs:nb}),d({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-f,data:{session:n,requestedDurationMs:nb}}),u}async function ob(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,tracePath:a,artifactPaths:o}=e;if(t.flags?.recordVideo!==!0||!i.get(n)?.recording)return;sb(a,{type:`video_tail_start`,session:n,requestedDurationMs:rb});let s=Date.now();await vt(rb);let c=Date.now(),l=await Sr({req:{token:t.token,session:n,command:`record`,positionals:[`stop`],flags:{},meta:t.meta},sessionName:n,sessionStore:i,logPath:r});return ff(l).forEach(e=>o.add(e)),sb(a,{type:`video_recording_stop`,session:n,ok:l.ok,durationMs:Date.now()-c,tailDurationMs:c-s,errorCode:l.ok?void 0:l.error.code}),d({phase:`replay_test_video_recording_stop`,durationMs:Date.now()-c,data:{session:n,ok:l.ok,tailDurationMs:c-s}}),l}function sb(e,t){K(e,{...t,ts:new Date().toISOString()})}function cb(e){let{platform:t,target:n,artifactsDir:r,shard:i}=e,a=lb(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0?a:yd({...a??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r}},i)}function lb(e){if(e?.recordVideo!==!0)return e;let t={...e};return delete t.recordVideo,Object.keys(t).length>0?t:void 0}async function ub(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,invoke:o}=e;return t.command===`replay`?await Ty({req:t,sessionName:n,logPath:r,sessionStore:i,invoke:o}):t.command===`test`?t.flags?.replayFrom!==void 0||t.flags?.replayPlanDigest!==void 0?L(`INVALID_ARGS`,`test does not support --from/--plan-digest; resume is replay-only. Run the failing script directly with replay --from.`):t.flags?.saveScript===void 0?await Md({req:t,sessionName:n,runReplay:async({filePath:e,sessionName:n,platform:a,target:s,requestId:c,artifactsDir:l,artifactPaths:u,tracePath:d,shard:f})=>{let p=e=>(u&&ff(e).forEach(e=>u.add(e)),e),m=cb({parentFlags:t.flags,platform:a,target:s,artifactsDir:l,shard:f}),h={req:t,sessionName:n,logPath:r,sessionStore:i,artifactsDir:l,tracePath:d},g=ib(h);return await Ty({req:{...t,command:`replay`,session:n,positionals:[e],flags:m,meta:{...t.meta??{},...c?{requestId:c}:{}},...t.internal||g?{internal:{...t.internal??{},...g?{openLifecycle:g}:{}}}:{}},sessionName:n,logPath:r,sessionStore:i,tracePath:d,invoke:async e=>{let t=await ab(h);return t&&!t.ok?t:p(await o(e))}})},finalizeAttempt:async({sessionName:e,artifactPaths:n,artifactsDir:a,tracePath:o})=>await ob({req:t,sessionName:e,logPath:r,sessionStore:i,artifactsDir:a,tracePath:o,artifactPaths:n}),cleanupSession:async e=>{i.get(e)&&await ys({req:{token:t.token,session:e,command:`close`,positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:r,sessionStore:i,leaseRegistry:a})}}):L(`INVALID_ARGS`,`test does not support --save-script; the agent-supervised repair loop is replay-only. Repair the failing script directly with replay --save-script.`):null}function db(e){let{req:t,sessionName:r,sessionStore:i}=e;if(t.command!==te.sessionSaveScript)return null;if((t.positionals?.length??0)>1)return pb(new n(`INVALID_ARGS`,`session save-script accepts at most one output path.`));let a=i.get(r);if(!a)return pb(new n(`SESSION_NOT_FOUND`,`No active session "${r}".`,{hint:`Start a fresh journey with open <app> --save-script[=<path>], then retry.`}));let o=fb(a);if(o)return pb(o);let s=t.positionals?.[0]?.trim();if(t.positionals?.[0]!==void 0&&!s)return pb(new n(`INVALID_ARGS`,`session save-script path cannot be empty.`));s&&ke(a,He(s),t.flags?.force),t.flags?.force&&(a.saveScriptForce=!0);let c=i.writeSessionLog(a,{force:!!(t.flags?.force||a.saveScriptForce),publication:`active`});return c.written?(a.scriptRecordingState=`published`,a.recordSession=!1,a.saveScriptPath=c.path,{ok:!0,data:{session:a.name,savedScript:c.path,actionCount:c.actionCount,...ve(`Published script: ${c.path}`)}}):pb(c.error??new n(`COMMAND_FAILED`,`The active session script was not published.`,{retriable:!0,hint:`The session remains armed; retry session save-script.`}))}function fb(e){if(e.saveScriptBoundary!==void 0)return new n(`COMMAND_FAILED`,`This session has an active .ad repair transaction and cannot use ordinary active-session publication.`,{hint:`Finish or abort the repair through replay --from and its existing close/teardown protocol.`});if(e.scriptRecordingState===`aborted`)return new n(`COMMAND_FAILED`,`This script recording was aborted by a second successful open and cannot be published.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(e.scriptRecordingState===`published`)return new n(`COMMAND_FAILED`,`This script recording has already been published.`,{hint:`Continue using the live session, or close it and start a fresh authoring session.`});if(e.scriptRecordingState!==`armed`||!e.recordSession)return new n(`COMMAND_FAILED`,`Script recording was not armed before this journey began; session history cannot be published without recording-time target evidence.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`})}function pb(t){return{ok:!1,error:e(t)}}function mb(e){return e.some(e=>e.status===`fail`)?`fail`:e.some(e=>e.status===`warn`)?`warn`:`pass`}function hb(e){return e===`fail`?`Blockers found before the run.`:e===`warn`?`No hard blockers found, but warnings need attention.`:`No blockers found.`}function gb(e){let t={fail:0,warn:1,pass:2,info:3};return[...e].sort((e,n)=>t[e.status]-t[n.status])}function _b(e,...t){for(let n of t)$(e,n)}function $(e,t){e.push(t),P({type:`command`,status:`progress`,message:vb(t)})}function vb(e){return[re(e),...ae(e)].join(`
25
+ `)}const yb=2e3;async function bb(e,t){let{device:n,metroPort:r,shouldProbeMetro:i,androidAdbExecutor:a}=t;if(n.platform!==`android`)return;let o=p(n,a);i&&$(e,await Eb(o,n.id,r)),$(e,await xb(o,n))}async function xb(e,t){try{let n=await Bt(e),r=Ut(t);return n===await Sb()&&!r?await Cb(e,t,n):wb(t,n,r)}catch(e){return Tb(e)}}async function Sb(){try{return(await Ht()).manifest.serviceComponent}catch{return}}async function Cb(e,t,n){let r=(await e([`shell`,`settings`,`get`,`secure`,zt.previousIme],{allowFailure:!0,timeoutMs:yb})).stdout.trim(),i=r&&r!==`null`?r:void 0;return{id:`android-test-ime`,status:`fail`,summary:`Android test IME helper is the active input method on ${t.id}, but no active session owns it -- likely left over from a crashed session.`,hint:`A stuck test IME leaves the real keyboard unavailable on this device until restored.`,command:i?`adb -s ${t.id} shell ime set ${i}`:`adb -s ${t.id} shell ime list -s`,evidence:{currentIme:n,previousIme:i}}}function wb(e,t,n){return{id:`android-test-ime`,status:`pass`,summary:n?`Android test IME helper is active for this session on ${e.id}.`:`Android test IME helper is not active on ${e.id}; the device's normal IME is in use.`,evidence:{currentIme:t}}}function Tb(t){let n=e(t);return{id:`android-test-ime`,status:`warn`,summary:`Could not inspect the Android test IME helper state.`,hint:n.message,evidence:{code:n.code}}}async function Eb(t,n,r){try{let e=await t([`reverse`,`--list`],{allowFailure:!0,timeoutMs:yb}),i=`tcp:${r} tcp:${r}`,a=e.stdout.includes(i);return{id:`android-reverse`,status:a?`pass`:`warn`,summary:a?`Android adb reverse exists for Metro port ${r}.`:`Android adb reverse is missing for Metro port ${r}.`,command:a?void 0:`adb -s ${n} reverse tcp:${r} tcp:${r}`,evidence:{stdout:e.stdout.trim()}}}catch(t){let n=e(t);return{id:`android-reverse`,status:`warn`,summary:`Could not inspect Android adb reverse mappings.`,hint:n.message,evidence:{code:n.code}}}}async function Db(t,n){let{device:r,targetApp:i,session:a}=n;if(i)try{let e=await Ob(r,i);if(!e){$(t,{id:`target-app`,status:`info`,summary:`Target app installation checks are not supported for ${j(r)}.`,evidence:{requested:i,platform:j(r)}});return}$(t,{id:`target-app`,status:`pass`,summary:`Target app is launchable: ${e}`,evidence:{requested:i,resolved:e,sessionApp:a?.appBundleId}})}catch(n){let i=e(n);$(t,{id:`target-app`,status:`fail`,summary:`Target app check failed: ${i.message}`,hint:i.hint??`Install the app or pass an exact package/bundle id or app name.`,command:`agent-device apps --platform ${j(r)} --all`,evidence:{code:i.code,message:i.message}})}}async function Ob(e,t){if(e.platform===`android`){let{listAndroidApps:n}=await import(`./app-lifecycle.js`).then(e=>e.t);return kb(t,(await n(e,`all`)).map(e=>({id:e.package,name:e.name})))?.id}if(N(e)||A(e)){let{listIosApps:n}=await import(`./apps.js`).then(e=>e.t);return kb(t,(await n(e,`all`)).map(e=>({id:e.bundleId,name:e.name})))?.id}}function kb(e,t){let r=e.trim().toLowerCase(),i=t.find(e=>e.id.toLowerCase()===r||e.name.toLowerCase()===r);if(i)return i;let a=t.filter(e=>e.id.toLowerCase().includes(r)||e.name.toLowerCase().includes(r));if(a.length===1)return a[0];throw a.length>1?new n(`AMBIGUOUS_MATCH`,`Multiple launchable apps matched "${e}"`,{matches:a.map(e=>e.id),hint:`Pass an exact package/bundle id from agent-device apps --all.`}):new n(`APP_NOT_INSTALLED`,`No launchable installed app matched "${e}"`)}async function Ab(t,n,r){let i=Mb(n,r);try{let e=await Pb(i),n=Nb(e.devices,i);return $(t,{id:`device`,status:n.length===0?`fail`:`pass`,summary:Rb(n,i,e.failures),hint:n.length===0?Vb(e.failures):void 0,command:n.length===0?Kb(i):void 0,evidence:qb(n,e.failures)}),n.length>0&&Fb(t,e.failures),{devices:n,platform:i.platform,target:i.target}}catch(n){let r=e(n);return $(t,{id:`device`,status:`fail`,summary:r.message,hint:r.hint,command:`agent-device devices`,evidence:{code:r.code,details:r.details}}),{devices:[],platform:i.platform,target:i.target}}}function jb(e,t,n){if(!n||!t)return;let r=t.devices.filter(e=>e.booted===!0);if(r.length===1)return r[0];$(e,{id:`target-app-device`,status:`fail`,summary:r.length===0?`Target app check needs one booted device; none matched.`:`Target app check needs one booted device; ${r.length} matched.`,hint:r.length===0?`Boot a device, or adjust --platform/--target/--device/--udid/--serial.`:`Pass --platform/--target/--device/--udid/--serial so doctor checks the intended device.`,command:t.platform?`agent-device devices --platform ${t.platform}`:`agent-device devices`,evidence:{targetApp:n,booted:r.map(e=>({platform:j(e),id:e.id,name:e.name}))}})}function Mb(e,t){let n=e.flags??{};return dn({platform:n.platform??t?.device.platform,target:n.target??t?.device.target,device:n.device,udid:n.udid,serial:n.serial,iosSimulatorDeviceSet:n.iosSimulatorDeviceSet,androidDeviceAllowlist:n.androidDeviceAllowlist})}function Nb(e,t){return e.filter(e=>Ze(e,t,{includeExplicitSelectors:!0}))}async function Pb(e){if(e.platform)return{devices:await ln(e),failures:[]};let t=[],n=[];for(let r of vn)try{t.push(...await ln({...e,platform:r}))}catch(e){n.push(Lb(r,e))}return{devices:t,failures:n}}function Fb(e,t){for(let n of t)$(e,Ib(n))}function Ib(e){return{id:`device-${e.platform}`,status:`warn`,summary:`${Wb(e.platform)} device inventory could not be read: ${e.message}`,hint:e.hint??`Check the ${Wb(e.platform)} toolchain, or scope with --platform to skip it.`,evidence:{platform:e.platform,code:e.code}}}function Lb(t,n){let r=e(n);return{platform:t,message:r.message,hint:r.hint,code:r.code}}function Rb(e,t,n){if(e.length===0)return n.length>0?`No ${zb(t)} devices found; ${Bb(n)}.`:`No ${zb(t)} devices found.`;let r=e.filter(e=>e.booted===!0).length,i=`${e.length} ${zb(t)} ${Gb(e.length,`device`)} available; ${r} booted`,a=Hb(e,t);return a?`${i} (${a}).`:`${i}.`}function zb(e){let t=e.platform?Wb(e.platform):`local`;return e.target?`${t} ${e.target}`:t}function Bb(e){return e.slice(0,2).map(e=>`${Wb(e.platform)} inventory failed: ${e.message}`).join(`; `)}function Vb(e){return e.find(e=>e.hint)?.hint??`Start or create a simulator/emulator, connect a device, or adjust --platform/--target/--device selectors.`}function Hb(e,t){if(t.platform||t.target)return;let n=yn(e),r=Ub();return[`android`,`apple`,`vega`,`linux`,`web`].flatMap(e=>{let t=n[e];return t.available>0?[`${r[e]} ${t.available} available, ${t.booted} booted`]:[]}).join(`; `)}function Ub(){return{android:`Android`,apple:`Apple`,vega:`Vega`,linux:`Linux`,web:`web`}}function Wb(e){return e===`ios`?`iOS`:e===`macos`?`macOS`:e===`android`?`Android`:e===`vega`?`Vega`:e===`linux`?`Linux`:e===`web`?`web`:`Apple`}function Gb(e,t){return e===1?t:`${t}s`}function Kb(e){return e.platform?`agent-device devices --platform ${e.platform}`:`agent-device devices`}function qb(e,t){let n=new Map;for(let t of e){let e=j(t),r=n.get(e)??{available:0,booted:0};r.available+=1,t.booted===!0&&(r.booted+=1),n.set(e,r)}return{available:e.length,booted:e.filter(e=>e.booted===!0).length,byPlatform:Object.fromEntries([...n.entries()].sort(([e],[t])=>e.localeCompare(t))),...t.length>0?{failures:t}:{}}}const Jb=1500;async function Yb(e,t,n,r={}){let i=`http://${e}:${t}/status`;try{let a=await fetch(i,{signal:AbortSignal.timeout(1500)}),o=await a.text(),s=a.ok&&o.toLowerCase().includes(`packager-status:running`),c=s?await Xb(e,t,r):void 0;return{id:`metro`,status:s?`pass`:`warn`,summary:s?Zb(i,c):`React Native dev server responded at ${i}, but did not report packager-status:running.`,hint:s?void 0:`Verify this is the Metro/Re.Pack instance for the target app, or restart the dev server.`,evidence:{url:i,statusCode:a.status,body:o.slice(0,120),kind:n,...c?{process:c}:{}}}}catch(e){return{id:`metro`,status:n===`auto`?`warn`:`fail`,summary:`React Native dev server is not reachable at ${i}.`,hint:`Start Metro or Re.Pack for this project. For non-default endpoints, launch with open --metro-host/--metro-port, or run metro prepare with --public-base-url/--proxy-base-url before retrying doctor.`,command:`curl -fsS ${i}`,evidence:{url:i,error:e instanceof Error?e.message:String(e),kind:n}}}}async function Xb(e,t,n){try{return await(n.resolveProcessInfo??Qb)(e,t)}catch{return}}function Zb(e,t){return t?.cwd?`React Native dev server is reachable at ${e} (cwd: ${t.cwd}).`:`React Native dev server is reachable at ${e}.`}async function Qb(e,t){if(!$b(e))return;let n=await ex(t);if(n!==void 0)return{pid:n,cwd:await tx(n)}}function $b(e){return e===`127.0.0.1`||e===`localhost`||e===`::1`||e===`0.0.0.0`}async function ex(e){let t=await m(`lsof`,[`-nP`,`-iTCP:${e}`,`-sTCP:LISTEN`,`-Fp`],{allowFailure:!0,timeoutMs:Jb});if(t.exitCode===0)return t.stdout.split(`
26
+ `).map(e=>e.startsWith(`p`)?Number.parseInt(e.slice(1),10):NaN).find(e=>Number.isInteger(e)&&e>0)}async function tx(e){let t=await m(`lsof`,[`-nP`,`-a`,`-p`,String(e),`-d`,`cwd`,`-Fn`],{allowFailure:!0,timeoutMs:Jb});if(t.exitCode===0)return t.stdout.split(`
27
+ `).find(e=>e.startsWith(`n`)&&e.length>1)?.slice(1)}const nx=[`daemonBaseUrl`,`tenant`,`runId`,`leaseId`,`leaseProvider`],rx=[`provider`,`providerSessionId`,`providerApp`,`providerOsVersion`,`providerProject`,`providerBuild`,`providerSessionName`,`awsProjectArn`,`awsDeviceArn`,`awsAppArn`,`awsRegion`,`awsInteractionMode`];function ix(e,t){let n=bt(e.meta?.cwd);return{targetApp:lx(e.flags?.targetApp)??t?.appBundleId,metroHost:lx(e.runtime?.metroHost)??`127.0.0.1`,metroPort:ux(e.runtime?.metroPort)??8081,kind:n,remote:e.flags?.remote===!0,shouldProbeMetro:sx(e,n)}}function ax(e,t={}){let n=cx(e);return n?[{id:`remote-connection`,status:t.required?`pass`:`info`,summary:`Remote daemon/session or provider scope is configured.`,evidence:n}]:t.required?[{id:`remote-connection`,status:`fail`,summary:`No remote daemon/session or provider scope is configured.`,hint:`Use connect, --remote-config <path>, or direct remote/provider flags for the command.`}]:[]}function ox(e,t,n,r={}){let i=n?e.toArray().filter(e=>e.name!==n.name&&e.device.platform===n.device.platform&&e.device.id===n.device.id).map(e=>e.name):[];return n?[{id:`session`,status:i.length>0?`warn`:`pass`,summary:i.length>0?`Other active sessions target the same device: ${i.join(`, `)}`:`Active session ${n.name} targets ${n.device.name}`,hint:i.length>0?`Close stale sessions before a QA run if they belong to old attempts.`:void 0,command:i.length>0?`agent-device close --session ${i[0]} --platform ${j(n.device)}`:void 0,evidence:{session:n.name,sameDeviceSessions:i,sessionStateDir:e.resolveSessionDir(n.name)}}]:[{id:`session`,status:`info`,summary:r.remote?`No active session named ${t}. Remote doctor will use configured remote scope.`:`No active session named ${t}. Doctor will use device inventory only.`,hint:`This is expected before a run. Use open when app foreground state matters.`}]}function sx(e,t){return t!==`auto`||typeof e.runtime?.metroPort==`number`||typeof e.runtime?.metroHost==`string`}function cx(e){let t={...Object.fromEntries([...nx,...rx].flatMap(t=>typeof e.flags?.[t]==`string`?[[t,`<configured>`]]:[])),...e.flags?.sessionIsolation===`tenant`?{sessionIsolation:`tenant`}:{}};return Object.keys(t).length>0?t:void 0}function lx(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function ux(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}const dx=3e3;async function fx(e,t){if(t===`android`){$(e,await mx());return}if(t===`vega`){$(e,await px());return}(t===`ios`||t===`macos`||t===`apple`)&&$(e,await yx())}async function px(){let{parseVegaDeviceList:e}=await import(`./devices4.js`),{resolveVegaToolProvider:t}=await import(`./tool-provider3.js`).then(e=>e.n),n=t();if(!await n.isAvailable())return{id:`toolchain`,status:`info`,summary:`Vega toolchain: Vega CLI not found.`,hint:`Install Vega Developer Tools or ensure ~/vega/bin/vega is executable.`,command:`vega --version`};let r=await n.version({allowFailure:!0,timeoutMs:dx}),i=await n.listDevices({allowFailure:!0,timeoutMs:dx}),a=Ex(r.stdout),o=i.exitCode===0&&e(i.stdout).length>0;return{id:`toolchain`,status:r.exitCode===0?`pass`:`info`,summary:a?`Vega toolchain: ${a}; ${o?`VVD running`:`no running VVD`}.`:`Vega toolchain: CLI found but version check failed.`,hint:o?void 0:`Start the Vega Virtual Device and retry doctor.`,evidence:{vegaVersion:a??null,deviceList:i.stdout.trim()||null}}}async function mx(){let e=process.env.ANDROID_HOME||process.env.ANDROID_SDK_ROOT,t=await wx(e),n=await Tx(`adb`,[`version`]);return n?hx({license:t,sdkRoot:e,versionLine:n}):vx(e,t)}function hx(e){return{id:`toolchain`,status:gx(e),summary:e.versionLine?`Android toolchain: ${e.versionLine}; ${_x(e.sdkRoot)}.`:`Android toolchain: adb is present but version check failed.`,hint:e.license===`missing`?`Accept Android SDK licenses before installing/building apps.`:void 0,command:e.license===`missing`?`sdkmanager --licenses`:void 0,evidence:{adbVersion:e.versionLine??null,androidHome:e.sdkRoot??null,license:e.license}}}function gx(e){return e.versionLine&&e.sdkRoot&&e.license!==`missing`?`pass`:`info`}function _x(e){return e?`ANDROID_HOME/ANDROID_SDK_ROOT set`:`ANDROID_HOME unset`}function vx(e,t){return{id:`toolchain`,status:`info`,summary:`Android toolchain: adb not found on PATH.`,hint:`Install Android platform-tools or add adb to PATH.`,evidence:{androidHome:e??null,license:t}}}async function yx(){let e=await Tx(`xcodebuild`,[`-version`]);return e?bx({selectedPath:await Tx(`xcode-select`,[`-p`]),versionLine:e}):Cx()}function bx(e){return{id:`toolchain`,status:xx(e),summary:Sx(e),evidence:{selectedPath:e.selectedPath??null,xcodeVersion:e.versionLine??null}}}function xx(e){return e.versionLine?`pass`:`info`}function Sx(e){return e.versionLine?e.selectedPath?`Apple toolchain: ${e.versionLine}; xcode-select ${e.selectedPath}.`:`Apple toolchain: ${e.versionLine}; xcode-select path unavailable.`:`Apple toolchain: xcodebuild version check failed.`}function Cx(){return{id:`toolchain`,status:`info`,summary:`Apple toolchain: xcodebuild version check failed.`,hint:`Install/select Xcode and complete first launch/license setup if xcodebuild reports it.`,command:`xcodebuild -version`}}async function wx(e){if(!e)return`unknown`;try{return await Mi(H.join(e,`licenses`,`android-sdk-license`)),`accepted`}catch{return`missing`}}async function Tx(e,t){try{let n=await m(e,t,{allowFailure:!0,timeoutMs:dx});return n.exitCode===0?Ex(n.stdout):void 0}catch{return}}function Ex(e){return e.split(`
28
+ `).map(e=>e.trim()).find(Boolean)}async function Dx(e,t){$(e,await Ox(t))}async function Ox(e){let t=jn({stateDir:e});if(!t.installed)return{id:`web-agent-browser-processes`,status:`info`,summary:`Managed web backend is not installed; no agent-device-owned browser processes counted.`,evidence:{stateDir:e,installed:!1}};try{let n=await Mn(t);return{id:`web-agent-browser-processes`,status:n.count>0?`info`:`pass`,summary:n.count>0?`${n.count} live agent-device-owned Chrome process${n.count===1?``:`es`} detected.`:`No live agent-device-owned Chrome processes detected.`,evidence:{stateDir:e,installed:!0,count:n.count,pids:n.pids,matchReasons:n.processes.map(e=>e.reason)}}}catch(t){return{id:`web-agent-browser-processes`,status:`info`,summary:`Could not inspect live agent-device-owned Chrome processes.`,hint:`Run doctor again from a shell with permission to inspect local processes.`,evidence:{stateDir:e,error:t instanceof Error?t.message:String(t)}}}}async function kx(e){let{req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i}=e;if(t.command!==D.doctor)return null;let a=r.get(n),o=ix(t,a),s=Mx(r,n),c=[];if(_b(c,{id:`agent-device`,status:`pass`,summary:`agent-device ${Ke()} using ${s}`,evidence:{version:Ke(),stateDir:s}},...ax(t,{required:o.remote}),...ox(r,n,a,{remote:o.remote})),o.remote)return Fx(c,o);let l=await Ab(c,t,a);await fx(c,a?.device.platform??l?.platform);let u=await Nx({androidAdbExecutor:i,checks:c,inventory:l,options:o,session:a,stateDir:s});return await jx(c,u??Ax(l)),Fx(c,o,{device:u,includeMetro:!0,inventory:l})}function Ax(e){let t=(e?.devices??[]).filter(e=>N(e)&&e.kind===`simulator`);return t.find(e=>e.booted===!0)??t[0]}async function jx(e,t){if(!(!t||!N(t)||t.kind!==`simulator`)&&!(process.platform!==`darwin`||F(t))){if(P({type:`command`,status:`progress`,message:`Checking iOS runner build cache (${t.name})...`}),await tn(t)){$(e,{id:`ios-runner-cache`,status:`pass`,summary:`iOS runner artifact cached; first open skips the runner build`});return}On(t,{}),P({type:`command`,status:`progress`,message:`Warming iOS runner build cache in the background (${t.name})...`}),$(e,{id:`ios-runner-cache`,status:`pass`,summary:`iOS runner build started in the background; the first open gets faster once it completes`,hint:"Run `agent-device prepare ios-runner` to wait for a fully warmed runner instead."})}}function Mx(e,t){let n=H.dirname(e.resolveSessionDir(t));return H.basename(n)===`sessions`?H.dirname(n):n}async function Nx(e){let{checks:t,inventory:n,options:r,session:i,androidAdbExecutor:a,stateDir:o}=e,s=i?.device??jb(t,n,r.targetApp);return s&&await Px(t,{androidAdbExecutor:a,device:s,options:r,session:i}),r.shouldProbeMetro&&$(t,await Yb(r.metroHost,r.metroPort,r.kind)),await Dx(t,o),s}async function Px(e,t){let{androidAdbExecutor:n,device:r,options:i,session:a}=t;await Db(e,{device:r,session:a,targetApp:i.targetApp}),await bb(e,{androidAdbExecutor:n,device:r,metroPort:i.metroPort,shouldProbeMetro:i.shouldProbeMetro})}function Fx(e,t,n={}){let r=mb(e);return{ok:!0,data:{status:r,summary:hb(r),kind:t.kind,platform:n.device?j(n.device):n.inventory?.platform,target:n.device?.target??n.inventory?.target,targetApp:t.targetApp,metro:n.includeMetro&&t.shouldProbeMetro?{host:t.metroHost,port:t.metroPort}:void 0,checks:gb(e)}}}async function Ix(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=t.positionals?.[0]??``;if(a!==`ios-runner`)return L(`INVALID_ARGS`,`prepare requires a subcommand: ios-runner`);let o=i.get(n),s=t.flags??{},c=W(D.prepare,o,s);if(c)return c;let l=await G({session:o,flags:s,ensureReady:!0}),u=I(D.prepare,l);if(u)return u;let d=Date.now(),f=await Dn(l,Lx(t,o,r,d));return{ok:!0,data:zx(a,l,Math.max(0,Date.now()-d),f)}}function Lx(e,t,n,r){let i=Rx(e);return{...si({req:e,logPath:n,traceLogPath:t?.trace?.outPath}),cleanStaleBundles:!0,buildTimeoutMs:i,healthTimeoutMs:i,prepareDeadline:Rt.fromTimeoutMs(i,r),startupTimeoutMs:i}}function Rx(e){let t=e.flags?.timeoutMs;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:v}function zx(e,t,n,r){return{action:e,platform:j(t),deviceId:t.id,deviceName:t.name,kind:t.kind,durationMs:n,...r,timing:Bx(n,r),message:`Prepared Apple runner: ${t.name}`}}function Bx(e,t){let n=Vx(t.buildMs),r=Hx(t.connectMs),i=Hx(t.healthCheckMs);return{totalMs:e,additiveParts:{...n===void 0?{}:{buildMs:n},connectAfterBuildMs:Math.max(0,r-(n??0)),healthCheckMs:i},containment:n===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},note:`Top-level prepare timing fields are diagnostic and may overlap; use timing.additiveParts for additive wall-clock phases.`}}function Vx(e){return e===void 0?void 0:Hx(e)}function Hx(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):0}async function Ux(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,command:a,positionals:o,recordPositionals:s,deriveNextSession:c}=e,l=i.get(n),u=t.flags??{},d=W(a,l,u);if(d)return d;let f=await G({session:l,flags:u,ensureReady:!0}),p=I(a,f);if(p)return p;l&&Er(t)===`may-invalidate`&&Vn(l);let m=await fn(f,a,o,t.flags?.out,{...R(r,t.flags,l?.appBundleId,l?.trace?.outPath)});if(l){let e=c?await c(l,m,f):l;jr(i,e,t,a,m??{},{positionals:s??o}),e!==l&&i.set(n,e)}return{ok:!0,data:m??{}}}async function Wx(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=i.get(n),o=t.flags??{},s=W(D.clipboard,a,o);if(s)return s;let c=(t.positionals?.[0]??``).toLowerCase();if(c!==`read`&&c!==`write`)return L(`INVALID_ARGS`,`clipboard requires a subcommand: read or write`);let l=await G({session:a,flags:o,ensureReady:!0}),u=I(D.clipboard,l);if(u)return u;let d=await fn(l,D.clipboard,t.positionals??[],t.flags?.out,{...R(r,t.flags,a?.appBundleId,a?.trace?.outPath)});return jr(i,a,t,t.command,d??{}),{ok:!0,data:{platform:j(l),...d??{}}}}const Gx=async({req:e,sessionName:t,sessionStore:n})=>await Ps({req:e,sessionName:t,sessionStore:n}),Kx=async({req:e,sessionName:t,logPath:n,sessionStore:r})=>await Vs({req:e,sessionName:t,logPath:n,sessionStore:r}),qx=async({req:e,sessionName:t,sessionStore:n,androidAdbExecutor:r})=>await Nl({req:e,sessionName:t,sessionStore:n,androidAdbExecutor:r}),Jx=async({req:e,sessionName:t,logPath:n,sessionStore:r,leaseRegistry:i,invoke:a,invokeReplayAction:o})=>await ub({req:e,sessionName:t,logPath:n,sessionStore:r,leaseRegistry:i,invoke:o??a});async function Yx(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=i.get(n),o=t.positionals?.[0]?.trim().toLowerCase();return!a&&(o===`dismiss`||o===`enter`||o===`return`)&&(t.flags??{}).platform===`ios`?L(`SESSION_NOT_FOUND`,`iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.`):await Ux({req:t,sessionName:n,logPath:r,sessionStore:i,command:D.keyboard,positionals:t.positionals??[]})}async function Xx(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return!a||!o?L(`INVALID_ARGS`,`push requires <bundle|package> <payload.json|inline-json>`):await Ux({req:t,sessionName:n,logPath:r,sessionStore:i,command:D.push,positionals:[a,eS(o,t.meta?.cwd)],recordPositionals:[a,o]})}async function Zx(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e;return await Ux({req:t,sessionName:n,logPath:r,sessionStore:i,command:D.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let n=typeof t?.eventUrl==`string`?t.eventUrl:void 0,r=n?await To(e.device,n,e.appBundleId,So)??e.appBundleId:e.appBundleId;return{...e,appBundleId:r}}})}const Qx={session_list:Gx,devices:Gx,capabilities:Gx,apps:Gx,doctor:async({req:e,sessionName:t,sessionStore:n,androidAdbExecutor:r})=>await kx({req:e,sessionName:t,sessionStore:n,androidAdbExecutor:r}),boot:Kx,shutdown:Kx,appstate:Kx,session_save_script:async({req:e,sessionName:t,sessionStore:n})=>db({req:e,sessionName:t,sessionStore:n}),runtime:async({req:e,sessionName:t,sessionStore:n})=>await $a({req:e,sessionName:t,sessionStore:n}),clipboard:async({req:e,sessionName:t,logPath:n,sessionStore:r})=>await Wx({req:e,sessionName:t,logPath:n,sessionStore:r}),keyboard:Yx,perf:qx,logs:qx,events:qx,network:qx,audio:qx,prepare:async({req:e,sessionName:t,logPath:n,sessionStore:r})=>await Ix({req:e,sessionName:t,logPath:n,sessionStore:r}),install:async({req:e,sessionName:t,sessionStore:n})=>await Os({req:e,command:`install`,sessionName:t,sessionStore:n,deployOps:Ds}),reinstall:async({req:e,sessionName:t,sessionStore:n})=>await Os({req:e,command:`reinstall`,sessionName:t,sessionStore:n,deployOps:Es}),install_source:async({req:e,sessionName:t,sessionStore:n})=>await Wi({req:e,sessionName:t,sessionStore:n}),release_materialized_paths:async({req:e})=>await $i({req:e}),push:Xx,"trigger-app-event":Zx,open:async({req:e,sessionName:t,logPath:n,sessionStore:r})=>await Yo({req:e,sessionName:t,logPath:n,sessionStore:r}),replay:Jx,test:Jx,batch:async({req:e,sessionName:t,invoke:n})=>await Ns(e,t,n),close:async({req:e,sessionName:t,logPath:n,sessionStore:r,leaseRegistry:i,leaseLifecycleProvider:a})=>await ys({req:e,sessionName:t,logPath:n,sessionStore:r,leaseRegistry:i,leaseLifecycleProvider:a})};async function $x(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a=new Pr,leaseLifecycleProvider:o,invoke:s,invokeReplayAction:c,androidAdbExecutor:l}=e,u=Qx[t.command];return u?await u({req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o,invoke:s,invokeReplayAction:c,androidAdbExecutor:l}):null}function eS(e,t){let n=an(e,{subject:`Push payload`,cwd:t,expandPath:(e,t)=>k.expandHome(e,t)});return n.kind===`file`?n.path:n.text}export{$x as handleSessionCommands};