agent-device 0.16.5 → 0.16.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.16.5.apk → agent-device-android-multitouch-helper-0.16.7.apk} +0 -0
  2. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.16.7.apk.sha256 +1 -0
  3. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.16.5.manifest.json → agent-device-android-multitouch-helper-0.16.7.manifest.json} +4 -4
  4. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.7.apk +0 -0
  5. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.7.apk.sha256 +1 -0
  6. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.16.5.manifest.json → agent-device-android-snapshot-helper-0.16.7.manifest.json} +6 -6
  7. package/dist/src/1010.js +1 -0
  8. package/dist/src/1231.js +1 -1
  9. package/dist/src/1352.js +1 -0
  10. package/dist/src/1998.js +1 -0
  11. package/dist/src/208.js +1 -1
  12. package/dist/src/221.js +6 -6
  13. package/dist/src/2415.js +31 -0
  14. package/dist/src/2805.js +1 -0
  15. package/dist/src/5186.js +1 -0
  16. package/dist/src/5310.js +1 -0
  17. package/dist/src/5792.js +1 -0
  18. package/dist/src/6085.js +1 -0
  19. package/dist/src/6629.js +1 -0
  20. package/dist/src/8114.js +4 -0
  21. package/dist/src/8133.js +1 -0
  22. package/dist/src/8502.js +1 -0
  23. package/dist/src/8699.js +1 -0
  24. package/dist/src/8806.js +7 -0
  25. package/dist/src/940.js +1 -1
  26. package/dist/src/9404.js +1 -0
  27. package/dist/src/9471.js +1 -0
  28. package/dist/src/9533.js +1 -0
  29. package/dist/src/9542.js +3 -3
  30. package/dist/src/9671.js +1 -0
  31. package/dist/src/android-adb.js +1 -1
  32. package/dist/src/android-snapshot-helper.d.ts +2 -1
  33. package/dist/src/android-snapshot-helper.js +1 -1
  34. package/dist/src/android.js +5 -0
  35. package/dist/src/apple.js +1 -0
  36. package/dist/src/apps.js +13 -0
  37. package/dist/src/args.js +449 -0
  38. package/dist/src/batch.js +1 -1
  39. package/dist/src/cli.js +36 -492
  40. package/dist/src/command-metadata.js +1 -0
  41. package/dist/src/command-surface.js +1 -0
  42. package/dist/src/contracts.d.ts +1 -0
  43. package/dist/src/devices.js +1 -0
  44. package/dist/src/devices~1.js +1 -0
  45. package/dist/src/devices~2.js +1 -0
  46. package/dist/src/find.js +1 -0
  47. package/dist/src/finders.d.ts +1 -0
  48. package/dist/src/generic.js +9 -0
  49. package/dist/src/index.d.ts +12 -0
  50. package/dist/src/input-actions.js +1 -0
  51. package/dist/src/input-actions~1.js +1 -0
  52. package/dist/src/interaction.js +1 -0
  53. package/dist/src/internal/bin.js +5 -2
  54. package/dist/src/internal/daemon.js +1 -100
  55. package/dist/src/lease.js +1 -0
  56. package/dist/src/linux.js +1 -0
  57. package/dist/src/notifications.js +1 -0
  58. package/dist/src/react-native.js +1 -0
  59. package/dist/src/record-trace.js +26 -0
  60. package/dist/src/recording-provider.js +1 -0
  61. package/dist/src/selector-runtime.js +1 -0
  62. package/dist/src/selectors.d.ts +1 -0
  63. package/dist/src/server.js +1 -1
  64. package/dist/src/session.js +29 -0
  65. package/dist/src/snapshot.js +2 -0
  66. package/package.json +4 -1
  67. package/server.json +2 -2
  68. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.16.5.apk.sha256 +0 -1
  69. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.5.apk +0 -0
  70. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.5.apk.sha256 +0 -1
  71. package/dist/src/1769.js +0 -7
  72. package/dist/src/6277.js +0 -4
  73. package/dist/src/7519.js +0 -1
  74. package/dist/src/89.js +0 -1
@@ -1,100 +1 @@
1
- let e,t,r,n,i;import{__webpack_require__ as a}from"../rslib-runtime.js";import o,{createHash as s}from"node:crypto";import l,{existsSync as u,promises as d}from"node:fs";import c,{hostname as p}from"node:os";import f from"node:path";import m from"node:net";import{AsyncLocalStorage as h}from"node:async_hooks";import w from"node:http";import{fileURLToPath as g,pathToFileURL as y}from"node:url";import"node:https";import{once as v}from"node:events";import{Transform as I}from"node:stream";import{pipeline as b}from"node:stream/promises";import A from"node:fs/promises";import{setTimeout as S}from"node:timers/promises";import{parseAllDocuments as x}from"yaml";import _ from"node:vm";import{toAppErrorCode as N,asAppError as M,normalizeError as k,AppError as D}from"../9152.js";import{runCmdBackground as O,runCmdStreaming as P,runCmd as R,runCmdSync as C,whichCmd as E,resolveExecutableOverridePath as L}from"../9818.js";import{getAndroidBlockingDialogFocus as T,withRetry as $,listAndroidDevices as F,classifyBootFailure as U,isEnvTruthy as V,streamAndroidLogcatWithAdb as G,writeAndroidClipboardText as q,openAndroidApp as B,closeAndroidApp as j,listAndroidApps as H,openAndroidDevice as W,androidDeviceForSerial as z,captureAndroidLogcatWithAdb as K,readAndroidClipboardText as J,formatAndroidInstalledPackageRequiredMessage as X,runAndroidAdb as Z,resolveIosSimulatorDeviceSetPath as Y,dismissAndroidKeyboard as Q,resolveIosDeviceDeepLinkBundleId as ee,Deadline as et,ensureAdb as er,isWebUrl as en,bootFailureHint as ei,getAndroidKeyboardState as ea,parseSerialAllowlist as eo,isInfrastructureBootFailureReason as es,retryWithPolicy as el,getAndroidAppState as eu,isAndroidInputMethodOwnedNode as ed,classifyAndroidAppTarget as ec,resolveAndroidSerialAllowlist as ep,createAppResolutionCache as ef,isDeepLinkTarget as em}from"../1769.js";import{readProcessStartTime as eh,trimRuntimeValue as ew,readProcessCommand as eg,resolveRuntimeTransportHints as ey,isProcessGroupAlive as ev,isAgentDeviceDaemonProcess as eI,isProcessAlive as eb}from"../8656.js";import{withDiagnosticsScope as eA,getDiagnosticsMeta as eS,flushDiagnosticsToSessionFile as ex,withDiagnosticTimer as e_,emitDiagnostic as eN}from"../7599.js";import{resolveDaemonCodeSignature as eM,DAEMON_COMMAND_GROUPS as ek,PUBLIC_COMMANDS as eD,readInteractionTargetFromPositionals as eO,normalizeTenantId as eP,consumeTextLines as eR,parseTimeout as eC,appendScreenshotScriptFlags as eE,resolveDeployResultTarget as eL,serializeDaemonRpcResponseEnvelope as eT,GESTURE_SUBCOMMAND_ERROR as e$,serializeDaemonResponseEnvelope as eF,shouldStreamRequestProgress as eU,withSuccessText as eV,splitNonEmptyTrimmedLines as eG,INTERNAL_COMMANDS as eq,readLocationCoordinate as eB,resolveSessionIsolationMode as ej,readVersion as eH,findProjectRoot as eW,requireLocationCoordinates as ez,readScreenshotScriptFlag as eK,successText as eJ,screenshotOptionsFromFlags as eX,parseWaitPositionals as eZ,screenshotFlagsFromOptions as eY,resolveDaemonPaths as eQ,resolveDaemonServerMode as e0,parseDeviceRotation as e1,readFillTargetFromPositionals as e2,resolveInstallFromSourceResultTarget as e3,serializeDaemonProgressEnvelope as e5,SCREENSHOT_ACTION_FLAG_KEYS as e4}from"../6277.js";import{sleep as e8}from"../4829.js";import{resolveUserPath as e6}from"../3267.js";import{withAndroidAdbProvider as e9,pullAndroidAdbFile as e7,resolveAndroidTextInjector as te,resolveAndroidAdbProvider as tt,resolveAndroidTouchInjector as tr,resolveAndroidAdbExecutor as tn,installAndroidAdbPackage as ti}from"../9639.js";import{isScrollableType as ta}from"../2842.js";import{parseUiHierarchy as to,ensureAndroidSnapshotHelper as ts,parseUiHierarchyTree as tl,captureAndroidSnapshotWithHelper as tu,captureAndroidSnapshotWithHelperSession as td,parseAndroidSnapshotHelperManifest as tc,androidUiNodes as tp,forgetAndroidSnapshotHelperInstall as tf,buildUiHierarchySnapshot as tm,stopAndroidSnapshotHelperSession as th}from"../221.js";import{isKeyboardAction as tw,isMacOsSettingSupported as tg,isReactNativeCollapsedWarningLabel as ty,resolveRectCenter as tv,deriveMobileSnapshotHiddenContentHints as tI,SETTINGS_INVALID_ARGS_MESSAGE as tb,pointInsideRect as tA,resolveReactNativeOverlayDismissTarget as tS,inferVerticalScrollIndicatorDirections as tx,resolveActionableTouchResolution as t_,PNG as tN,evaluateIsPredicate as tM,runScrollEdgePasses as tk,getUnsupportedMacOsSettingMessage as tD,localCommandPolicy as tO,isSupportedPredicate as tP,applyCommandDefaults as tR,findMistargetedTypeRefToken as tC,resolveActionableTouchNode as tE,isSystemScrollIndicatorLabel as tL,formatScrollEdgeMessage as tT,MAESTRO_COMPAT_TRACKER_URL as t$,captureScrollEdgeState as tF,normalizeSnapshotTree as tU,interiorCoordinate as tV,createAgentDevice as tG,parseSessionSurface as tq,requireIntInRange as tB,detectReactNativeOverlay as tj,decodePng as tH,MAESTRO_NEW_ISSUE_URL as tW}from"../7519.js";import{snapshotPresentationOptionsFromFlags as tz,normalizeRef as tK,findNodeByRef as tJ,buildSnapshotPresentationKey as tX,centerOfRect as tZ,attachRefs as tY}from"../4057.js";import{materializeInstallablePath as tQ,isTrustedInstallSourceUrl as t0}from"../989.js";import{splitSelectorFromArgs as t1,extractNodeText as t2,tryParseSelectorChain as t3,extractNodeReadText as t5,splitIsSelectorArgs as t4,findNodeByLabel as t8,resolveRefLabel as t6,parseSelectorChain as t9,findNearestAncestor as t7,resolveSelectorChain as re,matchesSelector as rt,normalizeType as rr,buildSelectorChainForNode as rn,pruneGroupNodes as ri}from"../940.js";import{findBestMatchesByLocator as ra,normalizeText as ro,parseFindArgs as rs}from"../7556.js";import{runBatch as rl,mergeParentFlags as ru}from"../1231.js";import{assertResolvedAppsFilter as rd}from"../1393.js";var rc={};a.r(rc),a.d(rc,{dH:()=>da,TM:()=>di,installIosApp:()=>dl,installIosInstallablePath:()=>dd,YO:()=>dh,L5:()=>dr,IJ:()=>dn,TJ:()=>df,J7:()=>dc,reinstallIosApp:()=>du,resolveIosApp:()=>de,resolveIosSimulatorDeepLinkBundleId:()=>dt,kc:()=>uK,Cm:()=>dm,ap:()=>dp});var rp={};a.r(rp),a.d(rp,{prepareIosInstallArtifact:()=>l4});var rf={};a.r(rf),a.d(rf,{ensureBootedSimulator:()=>l1,SA:()=>l3,EB:()=>lQ,N3:()=>l2});let rm=new Set,rh=new Map,rw="request_canceled",rg="request canceled";function ry(e,t){if("string"==typeof e&&e.length>0)return e;let r=("string"==typeof t?t:"number"==typeof t&&Number.isFinite(t)?String(t):"generated").trim().replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,32)||"generated",n=Math.random().toString(36).slice(2,10);return`req:${r}:${process.pid}:${Date.now()}:${n}`}function rv(e){if(!e)return;!function(e){if(e.size<=5e4)return;let t=0;for(let r of e.keys()){if(t>=1e4)break;e.delete(r),t++}}(rh);let t=new AbortController;rh.set(e,t),rm.has(e)&&t.abort()}function rI(e){e&&(!function(e){if(e.size<=5e4)return;let t=0;for(let r of e){if(t>=1e4)break;e.delete(r),t++}}(rm),rm.add(e),rh.get(e)?.abort())}function rb(e){e&&(rm.delete(e),rh.delete(e))}function rA(e){return!!e&&rm.has(e)}function rS(e){if(e)return rh.get(e)?.signal}function rx(){return new D("COMMAND_FAILED",rg,{reason:rw})}function r_(e){if(rA(e))throw rx()}function rN(e){return e instanceof D&&"COMMAND_FAILED"===e.code&&(e.details?.reason===rw||e.message===rg)}function rM(e,t=e=>e){let r=new h;return{resolve:n=>n?t(n):r.getStore()??e,run:async(e,n)=>e?await r.run(t(e),n):await n(),hasScope:()=>!!r.getStore()}}function rk(e,t){return"user-installed"===t?e.filter(e=>!e.bundleId.startsWith("com.apple.")):e}function rD(e,t){return{openBundle:async(t,r)=>{var n,i;let a;await e("open",(n=t,i=r,a=["-b",n],i&&a.push(i),a))},openTarget:async t=>{await e("open",[t])},readClipboard:async()=>{let t=await e("pbpaste",[],{allowFailure:!0});if(0!==t.exitCode)throw new D("COMMAND_FAILED","Failed to read macOS clipboard",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});return t.stdout.replace(/\r\n/g,"\n").replace(/\n$/,"")},writeClipboard:async t=>{let r=await e("pbcopy",[],{allowFailure:!0,stdin:t});if(0!==r.exitCode)throw new D("COMMAND_FAILED","Failed to write macOS clipboard",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})},readDarkMode:async()=>{let t=await e("osascript",["-e",'tell application "System Events" to tell appearance preferences to get dark mode'],{allowFailure:!0});if(0!==t.exitCode)throw new D("COMMAND_FAILED","Failed to read macOS appearance",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let r=t.stdout.trim().toLowerCase();if("true"===r)return!0;if("false"===r)return!1;throw new D("COMMAND_FAILED",`Unable to determine current macOS appearance from osascript output: ${t.stdout.trim()}`)},setDarkMode:async t=>{let r=`tell application "System Events" to tell appearance preferences to set dark mode to ${t?"true":"false"}`,n=await e("osascript",["-e",r],{allowFailure:!0});if(0!==n.exitCode)throw new D("COMMAND_FAILED","Failed to set macOS appearance",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})},listApps:async r=>await rO(e,t,r)}}async function rO(e,t,r){let n=["/Applications","/System/Applications",f.join(c.homedir(),"Applications")],i=new Set;for(let t of n){let r=await d.stat(t).catch(()=>null);if(!r?.isDirectory())continue;let n=await e("find",[t,"-maxdepth","4","-type","d","-name","*.app"],{allowFailure:!0});if(0===n.exitCode)for(let e of n.stdout.split("\n")){let t=e.trim();t&&i.add(t)}}return rk((await Promise.all(Array.from(i).map(async e=>{let r=await rP(e,t).catch(()=>({})),n=r.bundleId;return n?{bundleId:n,name:r.appName??f.basename(e,".app")}:null}))).filter(e=>null!==e).sort((e,t)=>e.name.localeCompare(t.name)),r)}async function rP(e,t){for(let r of[f.join(e,"Contents","Info.plist"),f.join(e,"Info.plist")]){let e=await t(r),n=rR(e,"CFBundleIdentifier"),i=rR(e,"CFBundleDisplayName"),a=rR(e,"CFBundleName");if(n||i||a)return{bundleId:n,appName:i??a}}return{}}function rR(e,t){let r=e?.[t];return"string"==typeof r&&r.trim()?r.trim():void 0}let rC={runCommand:R,simctl:{run:async(e,t)=>await R("xcrun",["simctl",...e],t)},devicectl:{run:async(e,t)=>await R("xcrun",["devicectl",...e],t)},plist:{readJson:async e=>await rG(R,e)},macosHost:rD(R,async e=>await rG(R,e)),whichCommand:E},rE=rM(rC,function(e){return"function"==typeof e?rL({runCommand:e}):rL(e)});function rL(e={}){let t={...rC,...e},r=e.plist??{readJson:async e=>await rG(t.runCommand,e)};return{...t,simctl:e.simctl??{run:async(e,r)=>await t.runCommand("xcrun",["simctl",...e],r)},devicectl:e.devicectl??{run:async(e,r)=>await t.runCommand("xcrun",["devicectl",...e],r)},plist:r,macosHost:e.macosHost??rD(t.runCommand,async e=>await r.readJson(e))}}function rT(e){return rE.resolve(e)}async function r$(e,t){return await rE.run(e,t)}async function rF(e,t,r){return await rT().runCommand(e,t,r)}async function rU(e,t){let r=rT(),[n,...i]=e;return"simctl"===n?await (r.simctl?.run(i,t)??r.runCommand("xcrun",e,t)):"devicectl"===n?await (r.devicectl?.run(i,t)??r.runCommand("xcrun",e,t)):await rF("xcrun",e,t)}async function rV(e){return await rT().plist?.readJson(e)??null}async function rG(e,t){try{let r=await e("plutil",["-convert","json","-o","-",t],{allowFailure:!0});if(0!==r.exitCode||!r.stdout.trim())return null;return JSON.parse(r.stdout)}catch{return null}}function rq(e,t={}){let r=Y(t.simulatorSetPath);return r?["simctl","--set",r,...e]:["simctl",...e]}function rB(e,t){return"ios"!==e.platform||"simulator"!==e.kind?["simctl",...t]:rq(t,{simulatorSetPath:e.simulatorSetPath})}let rj="If runner build products look stale or corrupted, run `pnpm clean:xcuitest` in a local checkout, or remove ~/.agent-device/ios-runner/derived, then retry.";function rH(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=`${e.message??""}`.toLowerCase();return!(t.includes("xcodebuild exited early")||t.includes("device is busy")&&t.includes("connecting"))&&!!(t.includes("runner did not accept connection")||t.includes("fetch failed")||t.includes("econnrefused")||t.includes("socket hang up"))}function rW(e){return!(e instanceof D)||"COMMAND_FAILED"!==e.code||!String(e.message??"").toLowerCase().includes("xcodebuild exited early")}function rz(e){let{port:t,endpoints:r,logPath:n,lastError:i}=e,a="Runner did not accept connection";return new D("COMMAND_FAILED",a,{port:t,endpoints:r,logPath:n,lastError:i?String(i):void 0,reason:U({error:i,message:a,context:{platform:"ios",phase:"connect"}}),hint:ei("IOS_RUNNER_CONNECT_TIMEOUT")})}async function rK(e){var t,r;let n,{session:i,port:a,logPath:o}=e,s=await i.testPromise,l="Runner did not accept connection (xcodebuild exited early)",u=U({message:l,stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});return new D("COMMAND_FAILED",l,{port:a,logPath:o,xcodebuild:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr},reason:u,hint:(t=s.stdout,r=s.stderr,(n=`${l}
2
- ${t}
3
- ${r}`.toLowerCase()).includes("device is busy")&&n.includes("connecting")?"Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.":`${ei("IOS_RUNNER_CONNECT_TIMEOUT")} ${rj}`)})}function rJ(e){return"interactionFrame"===e||"snapshot"===e||"screenshot"===e||"findText"===e||"querySelector"===e||"readText"===e||"alert"===e||"uptime"===e}function rX(e){if(rA(e))throw rx()}let rZ=new Map;async function rY(e,t,r,n,i=45e3,a,o){let s=et.fromTimeoutMs(i),{getEndpoints:l}=r0(e,t),{endpoints:u}=await l(s.remainingMs()),d=null,c=Math.max(1,Math.ceil(i/250));try{return await el(async({deadline:s})=>{if(s?.isExpired())throw new D("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:i});if(a&&null!==a.child.exitCode&&void 0!==a.child.exitCode)throw await rK({session:a,port:t,logPath:n});let c=!1;if("device"===e.kind){let e=await l(s?.remainingMs());u=e.endpoints,c=e.cached}let p=c?u[0]:null,f=await r1(u,{command:r,port:t,timeoutMs:i,signal:o,attemptDeadline:s,onError:(t,r)=>{var n;d=r,"device"===e.kind&&t===p&&(n=e.id,rZ.delete(n))}});if(f)return f;if("device"===e.kind&&c){var m;m=e.id,rZ.delete(m),u=(await l(s?.remainingMs(),!0)).endpoints;let n=await r1(u,{command:r,port:t,timeoutMs:i,signal:o,attemptDeadline:s,onError:(e,t)=>{d=t}});if(n)return n}if(o?.aborted)throw rx();throw new D("COMMAND_FAILED","Runner endpoint probe failed",{port:t,endpoints:u,lastError:d?String(d):void 0})},{maxAttempts:c,baseDelayMs:300,maxDelayMs:2e3,jitter:.2,shouldRetry:rW},{deadline:s,phase:"ios_runner_connect",signal:o})}catch(e){if(o?.aborted||rN(e))throw rx();d||(d=e)}if(o?.aborted)throw rx();if("simulator"===e.kind){let i=s.remainingMs();if(i<=0)throw rz({port:t,endpoints:u,logPath:n,lastError:d});let a=await r4(e,t,r,i,o);return new Response(a.body,{status:a.status})}throw rz({port:t,endpoints:u,logPath:n,lastError:d})}async function rQ(e,t,r,n=45e3,i){if(i?.aborted)throw rx();let a=et.fromTimeoutMs(n),{getEndpoints:o}=r0(e,t),{endpoints:s}=await o(a.remainingMs()),l=s[0];if(!l)throw new D("COMMAND_FAILED","Runner command endpoint not available",{port:t,endpoints:s});let u=a.remainingMs();if(u<=0)throw new D("COMMAND_FAILED","Runner command deadline exceeded",{timeoutMs:n});return await r3(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},u,i)}function r0(e,t){let r;return{getEndpoints:async(n,i=!1)=>{var a,o,s;let l,u=await r2({device:e,timeoutBudgetMs:n,forceRefresh:i,requestTunnelIp:r,setRequestTunnelIp:e=>{r=e}});return{endpoints:(a=e,o=t,s=u.ip,l=[`http://127.0.0.1:${o}/command`],"device"!==a.kind||s&&l.unshift(`http://[${s}]:${o}/command`),l),cached:u.sharedCacheHit}}}}async function r1(e,t){let{command:r,port:n,timeoutMs:i,signal:a,attemptDeadline:o,onError:s}=t;for(let t of e)try{let e=o?.remainingMs()??i;if(e<=0)throw new D("COMMAND_FAILED","Runner connection deadline exceeded",{port:n,timeoutMs:i});return await r3(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},Math.min(2e4,e),a)}catch(e){if(a?.aborted||rN(e))throw rx();s(t,e)}return null}async function r2(e){var t,r,n;let{device:i,timeoutBudgetMs:a,forceRefresh:o,requestTunnelIp:s,setRequestTunnelIp:l}=e;if("device"!==i.kind)return{ip:null,sharedCacheHit:!1};if(!o){let e,r=(t=i.id,(e=rZ.get(t))?e.expiresAt<=Date.now()?(rZ.delete(t),null):e.ip:null);if(r)return{ip:r,sharedCacheHit:!0};if(void 0!==s)return{ip:s,sharedCacheHit:!1}}let u=await r5(i.id,a);return l(u),u&&(r=i.id,n=u,rZ.set(r,{ip:n,expiresAt:Date.now()+3e4})),{ip:u,sharedCacheHit:!1}}async function r3(e,t,r,n){let i=AbortSignal.timeout(r),a=n?AbortSignal.any([n,i]):i;return await fetch(e,{...t,signal:a})}async function r5(e,t){if("number"==typeof t&&t<=0)return null;let r="number"==typeof t?Math.max(1,Math.min(1e4,t)):1e4,n=f.join(c.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(r/1e3)),i=await rU(["devicectl","device","info","details","--device",e,"--json-output",n,"--timeout",String(t)],{allowFailure:!0,timeoutMs:r});if(0!==i.exitCode||!l.existsSync(n))return null;let a=JSON.parse(l.readFileSync(n,"utf8"));if(a.info?.outcome&&"success"!==a.info.outcome)return null;let o=(a.result?.connectionProperties?.tunnelIPAddress??a.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return o&&o.length>0?o:null}catch{return null}finally{ne(n)}}async function r4(e,t,r,n,i){let a=JSON.stringify(r),o=rB(e,["spawn",e.id,"/usr/bin/curl","-s","-X","POST","-H","Content-Type: application/json","--data",a,`http://127.0.0.1:${t}/command`]),s=await rU(o,{allowFailure:!0,timeoutMs:n,signal:i}),l=s.stdout;if(0!==s.exitCode){let e=U({message:"Runner did not accept connection (simctl spawn)",stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});throw new D("COMMAND_FAILED","Runner did not accept connection (simctl spawn)",{port:t,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode,reason:e,hint:ei(e)})}return{status:200,body:l}}async function r8(){return await new Promise((e,t)=>{let r=m.createServer();r.listen(0,"127.0.0.1",()=>{let n=r.address();if("object"==typeof n&&n?.port){let t=n.port;r.close(()=>e(t))}else r.close(()=>t(new D("COMMAND_FAILED","Failed to allocate port")))}),r.on("error",t)})}function r6(e,t,r,n){t&&r7(t,e),r&&r7(r,e),n&&process.stderr.write(e)}let r9=new Map;function r7(e,t){let r=(r9.get(e)??Promise.resolve()).catch(()=>{}).then(()=>l.promises.appendFile(e,t)).catch(()=>{}).finally(()=>{r9.get(e)===r&&r9.delete(e)});r9.set(e,r)}function ne(e){try{l.existsSync(e)&&l.unlinkSync(e)}catch{}}let nt=new h;async function nr(e,t,r){let n=nt.getStore()??[];if(n.some(r=>r.locks===e&&r.key===t))return await r();let i=(e.get(t)??Promise.resolve()).catch(()=>{}).then(()=>nt.run([...n,{locks:e,key:t}],r));return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)})}function nn(e){return"apple"===e||"ios"===e||"macos"===e}function ni(e,t){return!t||("apple"===t?nn(e):e===t)}function na(e){let{simulatorSetPath:t,platform:r,target:n}=e;if(t&&"macos"!==r&&"desktop"!==n)return t}async function no(e,t,r={}){let n=e,i=e=>e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim();if(t.platform&&(n=n.filter(e=>ni(e.platform,t.platform))),t.target&&(n=n.filter(e=>(e.target??"mobile")===t.target)),t.udid){let e=n.find(e=>e.id===t.udid&&nn(e.platform));if(!e)throw new D("DEVICE_NOT_FOUND",`No Apple device with UDID ${t.udid}`);return e}if(t.serial){let e=n.find(e=>e.id===t.serial&&"android"===e.platform);if(!e)throw new D("DEVICE_NOT_FOUND",`No Android device with serial ${t.serial}`);return e}if(t.deviceName){let e=i(t.deviceName),r=n.find(t=>i(t.name)===e);if(!r)throw new D("DEVICE_NOT_FOUND",`No device named ${t.deviceName}`);return r}let a=n[0];if(void 0!==a&&1===n.length)return a;if(0===n.length){var o;let e=r.simulatorSetPath;if(e&&(!(o=t.platform)||"apple"===o||"ios"===o))throw new D("DEVICE_NOT_FOUND","No devices found in the scoped simulator set",{simulatorSetPath:e,hint:`The simulator set at "${e}" appears to be empty. Create a simulator first:
4
- xcrun simctl --set "${e}" create "iPhone 16" com.apple.CoreSimulator.SimDeviceType.iPhone-16 com.apple.CoreSimulator.SimRuntime.iOS-18-0`,selector:t});throw new D("DEVICE_NOT_FOUND","No devices found",{selector:t})}let s=n.filter(e=>"device"!==e.kind);s.length>0&&(n=s);let l=n.filter(e=>e.booted),u=l[0];if(void 0!==u&&1===l.length)return u;let d=l[0]??n[0];if(void 0===d)throw new D("DEVICE_NOT_FOUND","No devices found",{selector:t});return d}let ns=new Set(["RUNNER_PRODUCT_MISSING","RUNNER_PRODUCT_REPAIR_FAILED"]);async function nl(e,t,r){if("macos"!==e.platform)return;if(0===t.length)throw new D("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",xctestrunPath:r});let n=Array.from(new Set(t)).sort((e,t)=>t.length-e.length);for(let e of n)if(!l.existsSync(e))throw new D("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",productPath:e,xctestrunPath:r});for(let e of n)if(!await nu(e)){await rF("codesign",["--remove-signature",e],{allowFailure:!0});try{await rF("codesign",["--force","--sign","-",e])}catch(n){let t=n instanceof D?n:new D("COMMAND_FAILED",String(n));throw new D("COMMAND_FAILED","Failed to repair macOS runner product signature",{reason:"RUNNER_PRODUCT_REPAIR_FAILED",productPath:e,xctestrunPath:r,error:t.message,details:t.details})}}}async function nu(e){return 0===(await rF("codesign",["--verify","--deep","--strict",e],{allowFailure:!0})).exitCode}let nd=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.:-"),nc=new Set([" "," ","\n","\r"]),np=new Set(["__defineGetter__","__defineSetter__","__proto__","constructor","prototype"]);function nf(e,t={}){let r=t.maxDocumentChars??0x8000000;if(e.length>r)throw Error(`XML document exceeds maximum supported size of ${r} characters.`);return new nh(e).parse()}function nm(e,t){for(let r of e){if("dict"===r.name)for(let e=0;e<r.children.length-1;e+=1){let n=r.children[e],i=r.children[e+1];n?.name==="key"&&n.text&&i&&t(n.text,i)}nm(r.children,t)}}class nh{roots=[];stack=[];index=0;xml;constructor(e){this.xml=e}parse(){for(this.skipByteOrderMark();this.index<this.xml.length;)this.readNextToken();return this.assertFullyClosed(),this.roots}readNextToken(){"<"!==this.xml[this.index]?this.readText():this.resolveMarkupReader()()}resolveMarkupReader(){return this.startsWith("\x3c!--")?()=>this.skipUntil("--\x3e","Comment is not closed."):this.startsWith("<?")?()=>this.skipUntil("?>","Processing instruction is not closed."):this.startsWith("<![CDATA[")?()=>this.readCdata():this.startsWith("<!")?()=>this.skipDeclaration():this.startsWith("</")?()=>this.readClosingTag():()=>this.readOpeningTag()}assertFullyClosed(){if(this.stack.length>0){let e=this.stack[this.stack.length-1];throw Error(`Unclosed XML tag <${e?.name??"unknown"}>.`)}}skipByteOrderMark(){65279===this.xml.charCodeAt(0)&&(this.index=1)}readOpeningTag(){this.index+=1,this.skipWhitespace();let e=this.readRequiredName(`Missing XML tag name at offset ${this.index}.`),{attributes:t,selfClosing:r}=this.readOpeningTagBody(),n={name:e,attributes:t,text:null,children:[]};this.addNode(n),r||this.pushOpenNode(n)}readOpeningTagBody(){let e={};for(;;){this.skipWhitespace();let t=this.readOpeningTagEnd();if(t)return{attributes:e,selfClosing:"self-closing"===t};let r=this.readAttribute();e[r.name]=r.value}}readOpeningTagEnd(){if(this.index>=this.xml.length)throw Error("Opening XML tag is not closed.");return">"===this.xml[this.index]?(this.index+=1,"open"):"/"===this.xml[this.index]&&">"===this.xml[this.index+1]?(this.index+=2,"self-closing"):null}readAttribute(){let e=this.readRequiredName(`Invalid XML attribute at offset ${this.index}.`);if(function(e){if(np.has(e))throw Error(`Unsupported XML attribute name "${e}".`)}(e),this.skipWhitespace(),"="!==this.xml[this.index])throw Error(`Missing value for XML attribute "${e}".`);return this.index+=1,this.skipWhitespace(),{name:e,value:this.readAttributeValue(e)}}pushOpenNode(e){if(this.stack.length>=256)throw Error("Maximum XML nesting depth of 256 exceeded.");this.stack.push(e)}readClosingTag(){this.index+=2,this.skipWhitespace();let e=this.readName();if(this.skipWhitespace(),">"!==this.xml[this.index])throw Error(`Closing XML tag </${e}> is not closed.`);this.index+=1;let t=this.stack.pop();if(!t)throw Error(`Unexpected closing XML tag </${e}>.`);if(t.name!==e)throw Error(`Expected </${t.name}> before </${e}>.`)}readText(){let e=this.xml.indexOf("<",this.index),t=-1===e?this.xml.length:e;this.appendText(this.xml.slice(this.index,t),!0),this.index=t}readCdata(){let e=this.index+9,t=this.xml.indexOf("]]>",e);if(-1===t)throw Error("CDATA section is not closed.");this.appendText(this.xml.slice(e,t),!1),this.index=t+3}appendText(e,t){let r=e.trim();if(!r)return;let n=this.stack[this.stack.length-1];n&&(n.text=`${n.text??""}${t?nw(r):r}`)}addNode(e){let t=this.stack[this.stack.length-1];t?t.children.push(e):this.roots.push(e)}readName(){var e;let t=this.index;for(;this.index<this.xml.length&&void 0!==(e=this.xml[this.index])&&nd.has(e);)this.index+=1;return this.xml.slice(t,this.index)}readRequiredName(e){let t=this.readName();if(!t)throw Error(e);return t}readAttributeValue(e){let t=this.xml[this.index];if('"'!==t&&"'"!==t)throw Error(`XML attribute "${e}" must use a quoted value.`);this.index+=1;let r=this.index,n=this.xml.indexOf(t,r);if(-1===n)throw Error(`XML attribute "${e}" is not closed.`);return this.index=n+1,nw(this.xml.slice(r,n).trim())}skipDeclaration(){let e={quote:null,bracketDepth:0};for(let t=this.index+2;t<this.xml.length;t+=1)if(function(e,t){var r,n,i;return!(void 0===t||(r=e,n=t,r.quote?(n===r.quote&&(r.quote=null),!0):('"'===n||"'"===n)&&(r.quote=n,!0)))&&(function(e,t){if("["===t){e.bracketDepth+=1;return}"]"===t&&e.bracketDepth>0&&(e.bracketDepth-=1)}(e,t),i=e,">"===t&&0===i.bracketDepth)}(e,this.xml[t])){this.index=t+1;return}throw Error("XML declaration is not closed.")}skipUntil(e,t){let r=this.xml.indexOf(e,this.index+e.length);if(-1===r)throw Error(t);this.index=r+e.length}skipWhitespace(){for(var e;this.index<this.xml.length&&void 0!==(e=this.xml[this.index])&&nc.has(e);)this.index+=1}startsWith(e){return this.xml.startsWith(e,this.index)}}function nw(e){return e.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,(e,t)=>{switch(t){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'";default:var r=e,n=t;let i=n.startsWith("#x")?Number.parseInt(n.slice(2),16):Number(n.slice(1));if(!Number.isInteger(i)||i<0||i>1114111)return r;try{return String.fromCodePoint(i)}catch{return r}}})}let ng=new Set(["ProductPaths","DependentProductPaths","TestHostPath","TestBundlePath","UITargetAppPath"]);async function ny(e){var t;let r=await nv(e);if(!r||0===r.length)return null;let n=f.dirname(e),i=new Set,a=function(e,t){let r=[],n=new Set,i=[];for(let a of e){if(a.startsWith("__TESTHOST__/")){i.push(a.slice(13));continue}if(!a.startsWith("__TESTROOT__/"))continue;let e=a.slice(13);r.push(f.join(t,e));let o=function(e){let t=/\.app(?:\/|$)/.exec(e);return t&&void 0!==t.index?e.slice(0,t.index+4):null}(e);o&&n.add(f.join(t,o))}return{testRootPaths:r,hostRoots:Array.from(n),hostRelativePaths:i}}(r,n);for(let e of a.testRootPaths){if(!l.existsSync(e))return null;i.add(e)}for(let e of(t=a).hostRelativePaths.map(e=>{let r=t.hostRoots.find(t=>l.existsSync(f.join(t,e)));return r?f.join(r,e):null})){if(!e)return null;i.add(e)}return Array.from(i)}async function nv(e){let t=await rV(e);if(t){var r,n,i,a=t;let e=new Set;for(let t of[i=a,...function(e){let t=e.TestConfigurations;if(!Array.isArray(t))return[];let r=[];for(let e of t){if(!nI(e))continue;let t=e.TestTargets;Array.isArray(t)&&r.push(...t.filter(nI))}return r}(i),...Object.values(i).filter(e=>nI(e)&&"TestBundlePath"in e)])for(let r of function(e){let t=new Set;for(let[r,n]of Object.entries(e))if(ng.has(r)){if("string"==typeof n){t.add(n);continue}if(Array.isArray(n))for(let e of n)"string"==typeof e&&t.add(e)}return Array.from(t)}(t))e.add(r);return Array.from(e)}if("darwin"===process.platform)return null;try{let t;return r=l.readFileSync(e,"utf8"),n=nf(r),t=new Set,nm(n,(e,r)=>{if(ng.has(e)){if("string"===r.name&&r.text)return void t.add(r.text);if("array"===r.name)for(let e of r.children)"string"===e.name&&e.text&&t.add(e.text)}}),Array.from(t)}catch{return null}}function nI(e){return!!e&&"object"==typeof e}let nb=["CFBundleIcons","CFBundleIcons~ipad"];async function nA(e){let t=e.filter(nM);if(0===t.length)return;let r=e.filter(e=>nD(e)&&!nk(e));for(let e of t){let t=function(e,t){let r=f.dirname(e);return t.find(e=>f.dirname(e)===r&&"AgentDeviceRunner.app"===f.basename(e))??t.find(t=>f.dirname(t)===r&&t!==e)??null}(e,r);t&&await nS(t,e)}}async function nS(e,t){var r;let n,i=function(e,t){let r=!1;for(let i of l.readdirSync(e,{withFileTypes:!0})){var n;if(i.isFile()&&(n=i.name,/^AppIcon.*\.png$/.test(n)||"Assets.car"===n))(function(e,t){if(l.existsSync(t)){let r=l.readFileSync(e),n=l.readFileSync(t);return!r.equals(n)&&(l.copyFileSync(e,t),!0)}return l.copyFileSync(e,t),!0})(f.join(e,i.name),f.join(t,i.name))&&(r=!0)}return r}(e,t),a=await nx(e,t);(i||a)&&(await nN(t),r=t,n=new Date,l.utimesSync(r,n,n))}async function nx(e,t){var r,n;let i=f.join(e,"Info.plist"),a=f.join(t,"Info.plist"),o=await rV(i),s=await rV(a);if(!o||!s)return!1;let l=(r=o,n=s,nb.flatMap(e=>{let t=r[e];return void 0===t||JSON.stringify(n[e])===JSON.stringify(t)?[]:[{key:e,value:t,shouldInsert:void 0===n[e]}]}));if(0===l.length)return!1;for(let e of l)await n_(a,e.key,e.value,e.shouldInsert);return!0}async function n_(e,t,r,n){let i=await rF("plutil",[n?"-insert":"-replace",t,"-json",JSON.stringify(r),e],{allowFailure:!0});if(0!==i.exitCode)throw new D("COMMAND_FAILED","Failed to update XCTest runner icon plist",{key:t,plistPath:e,stderr:i.stderr})}async function nN(e){let t=await rF("codesign",["--force","--sign","-","--timestamp=none","--generate-entitlement-der",e],{allowFailure:!0});if(0!==t.exitCode)throw new D("COMMAND_FAILED","Failed to sign XCTest runner app after icon update",{runnerAppPath:e,stderr:t.stderr})}function nM(e){return nD(e)&&nk(e)&&(e.includes("Debug-iphonesimulator")||e.includes("Release-iphonesimulator")||e.includes("Debug-appletvsimulator")||e.includes("Release-appletvsimulator"))}function nk(e){return f.basename(e).endsWith("-Runner.app")}function nD(e){return f.basename(e).endsWith(".app")}let nO="XCTestDevices",nP=".agent-device-backup",nR=".agent-device-xctestdevices-backup-",nC=f.join(c.homedir(),".agent-device","ios-runner"),nE=".agent-device-runner-cache.json",nL={PreferredScreenCaptureFormat:"screenshots",SystemAttachmentLifetime:"keepNever",UserAttachmentLifetime:"keepNever"},nT=new Map,n$=new Set;function nF(e){return e?.trim()??""}function nU(e=process.env){return nF(e.AGENT_DEVICE_IOS_BUNDLE_ID)||nF(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||"com.callstack.agentdevice.runner"}function nV(e=process.env){let t=nF(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID);return t||`${nU(e)}.uitests`}let nG=function(e=process.env){let t=nU(e),r=nV(e);return Array.from(new Set([nF(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${r}.xctrunner`,t].filter(e=>e.length>0)))}(process.env);function nq(e=c.homedir()){return f.join(e,"Library","Developer","XCTestDevices")}async function nB(e,t={}){if("ios"!==e.platform||"simulator"!==e.kind)return null;let r=Y(e.simulatorSetPath);if(!r)return null;let n=f.resolve(r),i=f.resolve(t.xctestDeviceSetPath??nq()),a=f.resolve(t.backupPath??function(e=nq()){return`${e}${nP}`}(i)),o=f.resolve(t.lockDirPath??function(e=c.homedir()){return f.join(e,".agent-device","xctest-device-set.lock")}()),s=t.ownerStartTime??eh(process.pid),u=await nW({lockDirPath:o,owner:{pid:t.ownerPid??process.pid,startTime:s,acquiredAtMs:t.nowMs??Date.now()}});try{if(nj({xctestDeviceSetPath:i,backupPath:a}),function(e,t){if(f.resolve(e)===f.resolve(t))return!0;try{return l.realpathSync.native(e)===l.realpathSync.native(t)}catch{return!1}}(n,i))return await u(),null;l.mkdirSync(n,{recursive:!0}),l.existsSync(i)&&l.renameSync(i,a),function(e){let{requestedSetPath:t,xctestDeviceSetPath:r}=e,n=f.dirname(r),i=f.join(n,`${nO}.agent-device-link-${process.pid}-${Date.now()}`);l.mkdirSync(n,{recursive:!0});try{l.symlinkSync(t,i,"dir"),l.renameSync(i,r)}catch(e){throw l.existsSync(i)&&nH(i),e}}({requestedSetPath:n,xctestDeviceSetPath:i})}catch(e){throw nj({xctestDeviceSetPath:i,backupPath:a}),await u(),new D("COMMAND_FAILED","Failed to redirect XCTest device set path",{requestedSetPath:n,xctestDeviceSetPath:i,backupPath:a,error:String(e)})}let d=!1;return{release:async()=>{if(!d){d=!0;try{nj({xctestDeviceSetPath:i,backupPath:a})}finally{await u()}}}}}function nj(e){let{xctestDeviceSetPath:t,backupPath:r}=e,n=[r,...function(e){let t=f.dirname(e),r=f.basename(e).replace(nP,""),n=r===nO?nR:`${r}${nR}`;try{return l.readdirSync(t).filter(e=>e.startsWith(n)).sort().map(e=>f.join(t,e))}catch{return[]}}(r)],i=n.find(e=>l.existsSync(e)),a=l.existsSync(t)&&l.lstatSync(t).isSymbolicLink();if(i){if(a&&nH(t),l.existsSync(t))if(!a)return void eN({level:"warn",phase:"ios_runner_xctest_device_set_restore_collision",data:{xctestDeviceSetPath:t,activeBackupPath:i}});else i!==r?l.rmSync(i,{recursive:!0,force:!0}):l.rmSync(r,{recursive:!0,force:!0});else l.mkdirSync(f.dirname(t),{recursive:!0}),l.renameSync(i,t);for(let e of n)e!==i&&l.existsSync(e)&&l.rmSync(e,{recursive:!0,force:!0});return}a&&(eN({level:"warn",phase:"ios_runner_xctest_device_set_orphaned_symlink",data:{xctestDeviceSetPath:t}}),nH(t))}function nH(e){!l.existsSync(e)||l.lstatSync(e).isSymbolicLink()&&l.unlinkSync(e)}async function nW(e){let{lockDirPath:t,owner:r}=e,n=f.join(t,"owner.json"),i=Date.now()+3e4;for(l.mkdirSync(f.dirname(t),{recursive:!0});Date.now()<i;)try{l.mkdirSync(t),function(e,t){let r=`${e}.${process.pid}.${Date.now()}.tmp`;l.writeFileSync(r,JSON.stringify(t),"utf8"),l.renameSync(r,e)}(n,r);let e=!1;return async()=>{e||(e=!0,l.rmSync(t,{recursive:!0,force:!0}))}}catch(e){if("EEXIST"!==e.code)throw e;if(function(e,t){let r=null;try{r=l.statSync(e)}catch{return!0}let n=function(e){try{return JSON.parse(l.readFileSync(e,"utf8"))}catch{return null}}(t);if(n){var i;return!(Number.isInteger((i=n).pid)&&!(i.pid<=0)&&eb(i.pid)&&(!i.startTime||eh(i.pid)===i.startTime))&&(l.rmSync(e,{recursive:!0,force:!0}),!0)}return!(Date.now()-r.mtimeMs<5e3)&&(l.rmSync(e,{recursive:!0,force:!0}),!0)}(t,n))continue;await e8(100)}throw new D("COMMAND_FAILED","Timed out waiting for XCTest device set lock",{lockDirPath:t})}async function nz(e,t){var r;let n,i=(r=e,(n=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim())?f.resolve(n):"macos"===r.platform?f.join(nC,"derived","macos"):"simulator"===r.kind?f.join(nC,"derived"):f.join(nC,"derived",r.kind)),a=eW();return await nr(nT,i,async()=>{let r=function(e,t=eW()){var r;let n;return{schemaVersion:1,packageVersion:eH(),runnerSourceFingerprint:function(e){let t=f.join(e,"ios-runner","AgentDeviceRunner"),r=function(e){if(!l.existsSync(e))return[];let t=[],r=[e];for(;r.length>0;){let e=r.pop();for(let a of l.readdirSync(e,{withFileTypes:!0})){var n,i;let o=f.join(e,a.name);if(a.isDirectory()){if("xcuserdata"===a.name)continue;r.push(o);continue}a.isFile()&&(n=a.name,i=o,"project.pbxproj"===n?i.includes(`${f.sep}.xcodeproj${f.sep}`):[".jpg",".json",".png",".swift",".plist",".entitlements",".xctestplan",".xcconfig",".storyboard",".xib"].includes(f.extname(n)))&&t.push(o)}}return t.sort((e,t)=>e.localeCompare(t))}(t),n=function(e,t){let r=o.createHash("sha256");for(let n of t){let t=f.relative(e,n),i=l.statSync(n);r.update(t),r.update("\0"),r.update(String(i.size)),r.update("\0"),r.update(String(Math.trunc(i.mtimeMs))),r.update("\0")}return r.digest("hex")}(t,r),i=n1.get(t);if(i?.fileStatsFingerprint===n)return i.sourceFingerprint;let a=o.createHash("sha256");for(let e of r){let r=f.relative(t,e);a.update(r),a.update("\0"),a.update(l.readFileSync(e)),a.update("\0")}let s=a.digest("hex");return n1.set(t,{fileStatsFingerprint:n,sourceFingerprint:s}),s}(t),platformName:it(e),deviceKind:e.kind,target:e.target??"phone",buildDestinationFamily:"macOS"===(n=it(r=e))?`platform=macOS,arch=${ir()}`:"simulator"===r.kind?`generic/platform=${n} Simulator`:`generic/platform=${n}`,runnerBundleBuildSettings:io(process.env),runnerSigningBuildSettings:ia(process.env,"device"===e.kind,e.platform),runnerPerformanceBuildSettings:is()}}(e,a);V(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)&&(id("clean","forced_clean",{derived:i}),il(i),nK(i));let n=await iu({derived:i,projectRoot:a,expectedCacheMetadata:r,findXctestrun:t=>n2(t,e),xctestrunReferencesProjectRoot:n5,resolveExistingXctestrunProductPaths:ny});if("reuse_ready"!==n.reason&&id("rebuild",n.reason,{derived:i,xctestrunPath:n.xctestrunPath}),"reuse_ready"===n.reason)try{return await nl(e,n.productPaths,n.xctestrunPath),id("reuse","reuse_ready",{derived:i,xctestrunPath:n.xctestrunPath}),nX(i,nY(r,n.xctestrunPath,n.productPaths)),n.xctestrunPath}catch(e){if(!function(e){if(!(e instanceof D))return!1;let t=e.details&&"object"==typeof e.details?e.details.reason:void 0;return"string"==typeof t&&ns.has(t)}(e))throw e;id("rebuild","repair_failed",{derived:i,xctestrunPath:n.xctestrunPath})}n.xctestrunPath&&(il(i),nK(i));let s=f.join(a,"ios-runner","AgentDeviceRunner","AgentDeviceRunner.xcodeproj");if(!l.existsSync(s))throw new D("COMMAND_FAILED","iOS runner project not found",{projectPath:s});await ie(e,s,i,t);let u=n2(i,e);if(!u)throw new D("COMMAND_FAILED","Failed to locate .xctestrun after build");let d=await ny(u);if(!d)throw new D("COMMAND_FAILED","Runner build is missing expected products",{xctestrunPath:u});return await nl(e,d,u),await nA(d),nX(i,nY(r,u,d)),id("build","built_new",{derived:i,xctestrunPath:u}),u})}function nK(e){try{if(!l.existsSync(e))return;if("derived"!==f.basename(e))return void l.rmSync(e,{recursive:!0,force:!0});for(let r of l.readdirSync(e,{withFileTypes:!0})){var t;t=r.name,nJ.has(t)&&l.rmSync(f.join(e,r.name),{recursive:!0,force:!0})}}catch{}}let nJ=new Set([nE,"Build","BuildCache.noindex","Index.noindex","Logs","ModuleCache.noindex","SDKStatCaches.noindex","SourcePackages","TextBasedInstallAPI","info.plist"]);function nX(e,t){l.mkdirSync(e,{recursive:!0}),l.writeFileSync(f.join(e,nE),`${JSON.stringify(t,null,2)}
5
- `)}function nZ(e){let{artifacts:t,...r}=e;return r}function nY(e,t,r){let n=function(e,t){let r=n0(e);if(null===r||0===t.length)return null;let n=[];for(let e of t){let t=n0(e);if(null===t)return null;n.push({path:e,mtimeMs:t})}return{xctestrunPath:e,xctestrunMtimeMs:r,productPaths:n}}(t,r);return n?{...e,artifacts:n}:e}function nQ(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.path&&Number.isInteger(e.mtimeMs)}function n0(e){try{return Math.trunc(l.statSync(e).mtimeMs)}catch{return null}}let n1=new Map;function n2(e,t){if(!l.existsSync(e))return null;let r=[],n=[e];for(;n.length>0;){let e=n.pop();for(let t of l.readdirSync(e,{withFileTypes:!0})){let i=f.join(e,t.name);if(t.isDirectory()){n.push(i);continue}if(t.isFile()&&t.name.endsWith(".xctestrun"))try{let e=l.statSync(i);r.push({path:i,mtimeMs:e.mtimeMs})}catch{}}}return 0===r.length?null:(r.sort((e,r)=>{if(t){let n=n3(r.path,t)-n3(e.path,t);if(0!==n)return n}return r.mtimeMs-e.mtimeMs||e.path.localeCompare(r.path)}),r[0]?.path??null)}function n3(e,t){var r;let n=0,i=e.toLowerCase();f.basename(i).startsWith("agentdevicerunner.env.")&&(n-=1e3),i.includes(`${f.sep}macos${f.sep}`)&&(n-=5e3);let a="macos"===(r=t).platform?{preferred:["macos"],disallowed:["iphoneos","iphonesimulator","appletvos","appletvsimulator"]}:"tv"===r.target?"simulator"===r.kind?{preferred:["appletvsimulator"],disallowed:["appletvos","iphoneos","iphonesimulator","macos"]}:{preferred:["appletvos"],disallowed:["appletvsimulator","iphoneos","iphonesimulator","macos"]}:"simulator"===r.kind?{preferred:["iphonesimulator"],disallowed:["iphoneos","appletvos","appletvsimulator","macos"]}:{preferred:["iphoneos"],disallowed:["iphonesimulator","appletvos","appletvsimulator","macos"]};return a.preferred.length>0&&(a.preferred.some(e=>i.includes(e))?n+=2e3:n-=500),a.disallowed.some(e=>i.includes(e))&&(n-=2500),n}function n5(e,t){try{let r=l.readFileSync(e,"utf8"),n=new Set([t]);try{n.add(l.realpathSync(t))}catch{}for(let e of n)if(r.includes(e))return!0;return!1}catch{return!1}}async function n4(e,t,r){let n=f.dirname(e),i=r.replace(/[^a-zA-Z0-9._-]/g,"_"),a=f.join(n,`AgentDeviceRunner.env.${i}.json`),o=f.join(n,`AgentDeviceRunner.env.${i}.xctestrun`),s=await n8(e);return n9(s,e=>{var r,n;return r=e,n=t,void(r.EnvironmentVariables={...r.EnvironmentVariables??{},...n},r.UITestEnvironmentVariables={...r.UITestEnvironmentVariables??{},...n},r.UITargetAppEnvironmentVariables={...r.UITargetAppEnvironmentVariables??{},...n},r.TestingEnvironmentVariables={...r.TestingEnvironmentVariables??{},...n})}),n9(s,e=>Object.assign(e,nL),{requireTestBundlePath:!0}),await n6(s,a,o),{xctestrunPath:o,jsonPath:a}}async function n8(e){let t=await rF("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==t.exitCode||!t.stdout.trim())throw new D("COMMAND_FAILED","Failed to read xctestrun plist",{xctestrunPath:e,stderr:t.stderr});try{let e=JSON.parse(t.stdout);if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Root must be an object");return e}catch(t){throw new D("COMMAND_FAILED","Failed to parse xctestrun JSON",{xctestrunPath:e,error:String(t)})}}async function n6(e,t,r){l.writeFileSync(t,JSON.stringify(e,null,2));let n=await rF("plutil",["-convert","xml1","-o",r,t],{allowFailure:!0});if(0!==n.exitCode)throw new D("COMMAND_FAILED","Failed to write xctestrun plist",{tmpXctestrunPath:r,stderr:n.stderr})}function n9(e,t,r={}){let n=e.TestConfigurations;if(Array.isArray(n))for(let e of n)e&&"object"==typeof e&&function(e,t,r){if(Array.isArray(e))for(let n of e){let e=n7(n,r);e&&t(e)}}(e.TestTargets,t,r);for(let r of Object.values(e)){let e=n7(r,{requireTestBundlePath:!0});e&&t(e)}}function n7(e,t){return!e||"object"!=typeof e||Array.isArray(e)||t.requireTestBundlePath&&!e.TestBundlePath?null:e}async function ie(e,t,r,n){let i=io(process.env),a=ia(process.env,"device"===e.kind,e.platform),o="device"===e.kind?["-allowProvisioningUpdates"]:[],s=is(),l=await nB(e);try{var u;let l;await P("xcodebuild",["build-for-testing","-project",t,"-scheme","AgentDeviceRunner","-parallel-testing-enabled","NO",ii(e),"1","-destination",(u=e,l=it(u),"macOS"===l?`platform=macOS,arch=${ir()}`:"simulator"===u.kind?`platform=${l} Simulator,id=${u.id}`:`generic/platform=${l}`),"-derivedDataPath",r,...s,...i,...o,...a],{detached:!0,onSpawn:e=>{n$.add(e),e.on("close",()=>{n$.delete(e)})},onStdoutChunk:e=>{r6(e,n.logPath,n.traceLogPath,n.verbose)},onStderrChunk:e=>{r6(e,n.logPath,n.traceLogPath,n.verbose)}})}catch(a){let e,t,r=a instanceof D?a:new D("COMMAND_FAILED",String(a)),i=(e=r.details?JSON.stringify(r.details):"",((t=`${r.message}
6
- ${e}`.toLowerCase()).includes("failed registering bundle identifier")||t.includes("app identifier")&&t.includes("not available")?"Set AGENT_DEVICE_IOS_BUNDLE_ID to a unique reverse-DNS value (for example, com.yourname.agentdevice.runner), then retry.":t.includes("requires a development team")?"Configure signing in Xcode or set AGENT_DEVICE_IOS_TEAM_ID for physical-device runs.":t.includes("no profiles for")||t.includes("provisioning profile")?"Install/select a valid iOS provisioning profile, or set AGENT_DEVICE_IOS_PROVISIONING_PROFILE.":t.includes("code signing")?"Enable Automatic Signing in Xcode or provide AGENT_DEVICE_IOS_TEAM_ID and optional AGENT_DEVICE_IOS_SIGNING_IDENTITY.":void 0)??rj);throw new D("COMMAND_FAILED","xcodebuild build-for-testing failed",{error:r.message,details:r.details,logPath:n.logPath,hint:i})}finally{await l?.release()}}function it(e){var t;if("ios"!==e.platform&&"macos"!==e.platform)throw new D("UNSUPPORTED_PLATFORM",`Unsupported platform for iOS runner: ${e.platform}`);return"macos"===e.platform?"macOS":"macos"===(t=e.target)||"desktop"===t?"macOS":"tv"===t?"tvOS":"iOS"}function ir(){return"arm64"===process.arch?"arm64":"x86_64"}function ii(e){return"macos"===e.platform||"device"===e.kind?"-maximum-concurrent-test-device-destinations":"-maximum-concurrent-test-simulator-destinations"}function ia(e=process.env,t=!1,r="ios"){if("macos"===r)return["CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO","CODE_SIGN_IDENTITY=","DEVELOPMENT_TEAM="];if(!t)return[];let n=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||"",i=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||"",a=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||"",o=["CODE_SIGN_STYLE=Automatic"];return n&&o.push(`DEVELOPMENT_TEAM=${n}`),i&&o.push(`CODE_SIGN_IDENTITY=${i}`),a&&o.push(`PROVISIONING_PROFILE_SPECIFIER=${a}`),o}function io(e=process.env){let t=nU(e),r=nV(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${r}`]}function is(){return["COMPILER_INDEX_STORE_ENABLE=NO","ENABLE_CODE_COVERAGE=NO"]}function il(e,t=process.env){if(t.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()){var r;let t,n;if(r=e,t=f.resolve(eW(),".tmp"),""===(n=f.relative(t,f.resolve(r)))||n.startsWith("..")||f.isAbsolute(n))throw new D("COMMAND_FAILED","Refusing to clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH automatically",{derivedPath:e,hint:`Unset AGENT_DEVICE_IOS_CLEAN_DERIVED, or move AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH under a subdirectory of ${f.join(eW(),".tmp")}.`})}}async function iu(e){var t,r;let n,i=(t=e.derived,r=e.expectedCacheMetadata,(n=function(e){try{let t=JSON.parse(l.readFileSync(f.join(e,nE),"utf8"));if(!t||"object"!=typeof t||Array.isArray(t))return null;return t}catch{return null}}(t))?JSON.stringify(nZ(n))!==JSON.stringify(nZ(r))?{ok:!1,reason:"cache_metadata_mismatch"}:{ok:!0,metadata:n}:{ok:!1,reason:"cache_metadata_missing"}),a=i.ok?function(e){var t;let r=e?.artifacts;if(!(!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&"string"==typeof t.xctestrunPath&&Number.isInteger(t.xctestrunMtimeMs)&&Array.isArray(t.productPaths)&&t.productPaths.length>0&&t.productPaths.every(nQ))||n0(r.xctestrunPath)!==r.xctestrunMtimeMs)return null;let n=[];for(let e of r.productPaths){if(n0(e.path)!==e.mtimeMs)return null;n.push(e.path)}return{xctestrunPath:r.xctestrunPath,productPaths:n}}(i.metadata):null,o=a?.xctestrunPath??e.findXctestrun(e.derived);if(!o)return{reason:"missing_xctestrun",xctestrunPath:null};let s=a?.xctestrunPath===o?a.productPaths:await e.resolveExistingXctestrunProductPaths(o);return s?e.xctestrunReferencesProjectRoot(o,e.projectRoot)?i.ok?{reason:"reuse_ready",xctestrunPath:o,productPaths:s}:{reason:i.reason,xctestrunPath:o,productPaths:s}:{reason:"project_root_mismatch",xctestrunPath:o,productPaths:s}:{reason:"missing_products",xctestrunPath:o,productPaths:[]}}function id(e,t,r){eN({level:"rebuild"===e?"warn":"info",phase:"runner_xctestrun_cache",data:{action:e,reason:t,...r}})}let ic=new Map,ip=new Map;async function im(e,t){return await nr(ip,e.id,async()=>{let r,n,i=ic.get(e.id);if(i){if(ib(i.child.pid))return eN({level:"debug",phase:"ios_runner_session_reuse",data:{deviceId:e.id,sessionId:i.sessionId,ready:i.ready}}),i;await iN({},"stop_stale_session",async()=>{await ig(e.id,i)})}let a={};await iN(a,"ensure_booted",async()=>{var t;await ("simulator"!==(t=e).kind?Promise.resolve():t.booted?(eN({level:"debug",phase:"ios_runner_startup_ensure_booted_skipped",data:{deviceId:t.id}}),Promise.resolve()):iS(t))}),t.cleanStaleBundles?await iN(a,"cleanup_stale_bundles",async()=>{await ih(e)}):(a.cleanup_stale_bundles=0,eN({level:"debug",phase:"ios_runner_startup_cleanup_stale_bundles_skipped"}));let o=await iN(a,"ensure_xctestrun",async()=>await nz(e,t)),s=await iN(a,"allocate_port",async()=>await r8()),{xctestrunPath:l,jsonPath:u}=await iN(a,"prepare_xctestrun_env",async()=>await n4(o,{AGENT_DEVICE_RUNNER_PORT:String(s)},`session-${e.id}-${s}`)),d=await iN(a,"simulator_set_redirect",async()=>await nB(e));try{({child:r,wait:n}=await iN(a,"launch_xcodebuild",()=>{let t;return O("xcodebuild",["test-without-building","-only-testing","AgentDeviceRunnerUITests/RunnerTests/testCommand","-parallel-testing-enabled","NO","-test-timeouts-enabled","NO","-collect-test-diagnostics","never",ii(e),"1","-destination-timeout",String(20),"-xctestrun",l,"-destination",(t=it(e),"macOS"===t?`platform=macOS,arch=${ir()}`:"simulator"===e.kind?`platform=${t} Simulator,id=${e.id}`:`platform=${t},id=${e.id}`)],{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(s)},detached:!0})}))}catch(e){throw await d?.release(),e}r.stdout?.on("data",e=>{r6(e,t.logPath,t.traceLogPath,t.verbose)}),r.stderr?.on("data",e=>{r6(e,t.logPath,t.traceLogPath,t.verbose)});let c={sessionId:`${e.id}:${s}:${Date.now()}`,device:e,deviceId:e.id,port:s,xctestrunPath:l,jsonPath:u,testPromise:n,child:r,ready:!1,startupTimings:a,simulatorSetRedirect:d??void 0};return ic.set(e.id,c),c})}async function ih(e){if("simulator"===e.kind)for(let t of nG){let r=await rU(rB(e,["uninstall",e.id,t]),{allowFailure:!0});if(0!==r.exitCode){let e=`${r.stdout}
7
- ${r.stderr}`.toLowerCase();if(!e.includes("not installed")&&!e.includes("found nothing")&&!e.includes("no such file")&&!e.includes("invalid device")&&!e.includes("could not find"))continue}}}async function iw(e,t){await nr(ip,e.deviceId,async()=>{ic.get(e.deviceId)===e&&(eN({level:"warn",phase:"ios_runner_session_invalidated",data:{deviceId:e.deviceId,sessionId:e.sessionId,reason:t}}),await ig(e.deviceId,e,{graceful:!1,waitTimeoutMs:1e3}))})}async function ig(e,t,r={}){let n=t??ic.get(e);if(n){var i;if(!1!==r.graceful)try{await rY(n.device,n.port,{command:"shutdown"},void 0,15e3)}catch{await iA(n.child.pid,"SIGTERM")}else await iA(n.child.pid,"SIGTERM");try{await Promise.race([n.testPromise,new Promise(e=>setTimeout(e,r.waitTimeoutMs??1e4))])}catch{}(i=n.child.pid)&&(ib(i)||ev(i))&&await iA(n.child.pid,"SIGKILL"),ne(n.xctestrunPath),ne(n.jsonPath),await n.simulatorSetRedirect?.release(),ic.get(e)===n&&ic.delete(e)}}async function iy(e){await nr(ip,e,async()=>{await ig(e)})}async function iv(){let e=Array.from(ic.values()),t=Array.from(n$);await Promise.allSettled(e.map(async e=>{await iA(e.child.pid,"SIGINT")})),await Promise.allSettled(t.map(async e=>{await iA(e.pid,"SIGINT")})),await Promise.allSettled(e.map(async e=>{await iA(e.child.pid,"SIGTERM")})),await Promise.allSettled(t.map(async e=>{await iA(e.pid,"SIGTERM")})),await Promise.allSettled(e.map(async e=>{await iA(e.child.pid,"SIGKILL")})),await Promise.allSettled(t.map(async e=>{await iA(e.pid,"SIGKILL"),n$.delete(e)})),await Promise.allSettled(e.map(async e=>{await e.simulatorSetRedirect?.release()}))}async function iI(){await iv();let e=Array.from(ic.keys());await Promise.allSettled(e.map(async e=>{await iy(e)}));let t=Array.from(n$);await Promise.allSettled(t.map(async e=>{try{await iA(e.pid,"SIGTERM"),await iA(e.pid,"SIGKILL")}finally{n$.delete(e)}}))}function ib(e){return!!e&&eb(e)}async function iA(e,t){if(!e||e<=0)return;try{process.kill(-e,t)}catch{}try{process.kill(e,t)}catch{}let r="SIGINT"===t?"INT":"SIGTERM"===t?"TERM":"KILL";try{await rF("pkill",[`-${r}`,"-P",String(e)],{allowFailure:!0})}catch{}}async function iS(e){await rU(rB(e,["bootstatus",e.id,"-b"]),{timeoutMs:45e3})}async function ix(e,t,r,n,i,a){var o,s;if(o=t,s=r.command,o.startupTimingsReported||!o.startupTimings||(o.startupTimingsReported=!0,eN({level:"info",phase:"ios_runner_session_startup_timings",durationMs:Object.values(o.startupTimings).reduce((e,t)=>e+t,0),data:{command:s,sessionId:o.sessionId,ready:o.ready,timings:o.startupTimings}})),rJ(r.command)){let o=await e_("ios_runner_command_send",async()=>await rY(e,t.port,r,n,i,t,a),{command:r.command,readOnly:!0,sessionReady:t.ready,timeoutMs:i});return await i_(o,t,n)}let l=et.fromTimeoutMs(i);if(function(e,t){if(!e.ready||"tap"!==t.command&&"tapSeries"!==t.command)return!0;let r=e.lastSuccessfulRunnerResponseAtMs;return void 0===r||Date.now()-r>1e4}(t,r)){let i=t.ready?Math.min(5e3,l.remainingMs()):Math.min(45e3,l.remainingMs()),o=await e_("ios_runner_readiness_preflight",async()=>await rY(e,t.port,{command:"uptime"},n,i,t,a),{command:r.command,sessionReady:t.ready,timeoutMs:i});await i_(o,t,n)}else eN({level:"debug",phase:"ios_runner_readiness_preflight_skipped",data:{command:r.command,lastSuccessfulRunnerResponseAgeMs:void 0===t.lastSuccessfulRunnerResponseAtMs?void 0:Date.now()-t.lastSuccessfulRunnerResponseAtMs,sessionReady:t.ready}});let u=l.remainingMs();if(u<=0)throw new D("COMMAND_FAILED","Runner command deadline exceeded",{timeoutMs:i});let d=await e_("ios_runner_command_send",async()=>await rQ(e,t.port,r,u,a),{command:r.command});return await i_(d,t,n)}async function i_(e,t,r){let n,i=await e.text();try{let e=JSON.parse(i);n=e&&"object"==typeof e?e:{}}catch{throw new D("COMMAND_FAILED","Invalid runner response",{text:i})}if(!n.ok){let e=n.error?.code;throw new D("string"==typeof e&&e.trim().length>0?N(e):"COMMAND_FAILED",("string"==typeof n.error?.message?n.error.message:void 0)??"Runner error",{runner:n,xcodebuild:{exitCode:1,stdout:"",stderr:""},logPath:r})}return(t.ready=!0,t.lastSuccessfulRunnerResponseAtMs=Date.now(),n.data&&"object"==typeof n.data&&!Array.isArray(n.data))?n.data:{}}async function iN(e,t,r){let n=Date.now();try{return await r()}finally{let r=Date.now()-n;e[t]=r,eN({level:"debug",phase:`ios_runner_startup_${t}`,durationMs:r})}}let iM=new h;function ik(e,t={}){let r=iM.getStore();return r&&r.deviceId===e.id&&(r.requestId?r.requestId===t.requestId:!t.requestId)?r:void 0}async function iD(e,t,r){if(!e)return await r();let n={provider:iO(e),deviceId:t.deviceId,requestId:t.requestId};return await iM.run(n,r)}function iO(e){return"function"==typeof e?{runCommand:e}:e}async function iP(e,t,r={}){if("ios"!==e.platform&&"macos"!==e.platform)throw new D("UNSUPPORTED_PLATFORM",`Unsupported platform for iOS runner: ${e.platform}`);if("simulator"!==e.kind&&"device"!==e.kind)throw new D("UNSUPPORTED_OPERATION",`Unsupported iOS device kind for runner: ${e.kind}`);rX(r.requestId);let n=function(e,t,r,n={}){if(r)return iO(r);let i=ik(e,n);return i?iO(i.provider):iO(t)}(e,{runCommand:iR},void 0,{requestId:r.requestId});return rJ(t.command)?$(()=>(rX(r.requestId),n.runCommand(e,t,r)),{shouldRetry:e=>(rX(r.requestId),rH(e))}):n.runCommand(e,t,r)}async function iR(e,t,r){let n;rX(r.requestId);let i=rS(r.requestId);try{let a=((n=await im(e,r)).ready,45e3);return await ix(e,n,t,r.logPath,a,i)}catch(o){let a=o instanceof D?o:new D("COMMAND_FAILED",String(o));if("COMMAND_FAILED"===a.code&&"string"==typeof a.message&&a.message.includes("Runner did not accept connection")&&rW(a)&&n){rX(r.requestId),await iw(n,"runner_connect_failed_before_command_send"),n=await im(e,{...r,cleanStaleBundles:!0});try{return await ix(e,n,t,r.logPath,45e3,i)}catch(e){throw rH(e instanceof D?e:new D("COMMAND_FAILED",String(e)))&&await iw(n,"transport_error_after_retry_command_send"),e}}throw!n&&a.message.includes("Runner did not accept connection")&&await iy(e.id),n&&rH(a)&&await iw(n,"transport_error_after_command_send"),o}}function iC(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}let iE=["platform","device","udid","serial","out","verbose","metroHost","metroPort","bundleUrl","launchUrl","snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw",...e4,"relaunch","saveScript","noRecord","fps","quality","hideTouches","count","intervalMs","delayMs","holdMs","jitterPx","doubleTap","clickButton","pauseMs","pattern"];function iL(e){let t=e.result?.text;if("string"==typeof t&&t.trim().length>0)return t;let r=e.positionals??[];if(0===r.length)return"";let n=r[0];return n?.startsWith("@")?r.length>=3?r.slice(2).join(" ").trim():r.slice(1).join(" ").trim():!(r.length>=3)||Number.isNaN(Number(r[0]))||Number.isNaN(Number(r[1]))?r.slice(1).join(" ").trim():r.slice(2).join(" ").trim()}function iT(e){let t=new Set,r=[];for(let n of e)t.has(n)||(t.add(n),r.push(n));return r}let i$=/^-?\d+(\.\d+)?$/,iF=/^[^\s"\\]+$/,iU=new Map([["--count","count"],["--interval-ms","intervalMs"],["--hold-ms","holdMs"],["--jitter-px","jitterPx"]]),iV=new Map([["--count","count"],["--pause-ms","pauseMs"]]),iG=new Map([["--delay-ms","delayMs"]]);function iq(e){return"click"===e||"press"===e}function iB(e){return iq(e)||"longpress"===e}function ij(e){return"type"===e||"fill"===e}function iH(e){return iz(e,iK)}function iW(e){return JSON.stringify(e)}function iz(e,t){return t(e)?e:iW(e)}function iK(e){return iJ(e)&&e.startsWith("@")||i$.test(e)}function iJ(e){return iF.test(e)}function iX(e,t){let r=t.flags??{};if(iq(t.command)){"number"==typeof r.count&&e.push("--count",String(r.count)),"number"==typeof r.intervalMs&&e.push("--interval-ms",String(r.intervalMs)),"number"==typeof r.holdMs&&e.push("--hold-ms",String(r.holdMs)),"number"==typeof r.jitterPx&&e.push("--jitter-px",String(r.jitterPx)),!0===r.doubleTap&&e.push("--double-tap");let t=r.clickButton;t&&"primary"!==t&&e.push("--button",t);return}if("swipe"===t.command){"number"==typeof r.count&&e.push("--count",String(r.count)),"number"==typeof r.pauseMs&&e.push("--pause-ms",String(r.pauseMs)),("one-way"===r.pattern||"ping-pong"===r.pattern)&&e.push("--pattern",r.pattern);return}ij(t.command)&&"number"==typeof r.delayMs&&e.push("--delay-ms",String(r.delayMs))}function iZ(e,t){t&&(("ios"===t.platform||"android"===t.platform)&&e.push("--platform",t.platform),"string"==typeof t.metroHost&&t.metroHost.length>0&&e.push("--metro-host",iz(t.metroHost,iJ)),"number"==typeof t.metroPort&&e.push("--metro-port",String(t.metroPort)),"string"==typeof t.bundleUrl&&t.bundleUrl.length>0&&e.push("--bundle-url",iz(t.bundleUrl,iJ)),"string"==typeof t.launchUrl&&t.launchUrl.length>0&&e.push("--launch-url",iz(t.launchUrl,iJ)))}function iY(e,t){let r=[],n={},i=iq(e)?iU:"swipe"===e?iV:ij(e)?iG:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(iq(e)&&"--double-tap"===o){n.doubleTap=!0;continue}let s=t[a+1];if(iq(e)&&"--button"===o&&void 0!==s){("primary"===s||"secondary"===s||"middle"===s)&&(n.clickButton=s),a+=1;continue}let l=i?.get(o);if(l&&void 0!==s){let e=i0(s);if(null!==e){n[l]=e,a+=1;continue}}if("swipe"===e&&"--pattern"===o&&void 0!==s){("one-way"===s||"ping-pong"===s)&&(n.pattern=s),a+=1;continue}r.push(o)}return{positionals:r,flags:n}}function iQ(e){let t=[],r={};for(let n=0;n<e.length;n+=1){let i=e[n],a=e[n+1];if("--platform"===i&&void 0!==a){("ios"===a||"android"===a)&&(r.platform=a),n+=1;continue}if("--metro-host"===i&&void 0!==a){r.metroHost=a,n+=1;continue}if("--metro-port"===i&&void 0!==a){let e=i0(a);null!==e&&(r.metroPort=e),n+=1;continue}if("--bundle-url"===i&&void 0!==a){r.bundleUrl=a,n+=1;continue}if("--launch-url"===i&&void 0!==a){r.launchUrl=a,n+=1;continue}t.push(i)}return{positionals:t,flags:r}}function i0(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function i1(e,t={}){let r=[e.command];if("snapshot"===e.command)e.flags?.snapshotInteractiveOnly&&r.push("-i"),e.flags?.snapshotCompact&&r.push("-c"),"number"==typeof e.flags?.snapshotDepth&&r.push("-d",String(e.flags.snapshotDepth)),e.flags?.snapshotScope&&r.push("-s",iH(e.flags.snapshotScope)),e.flags?.snapshotRaw&&r.push("--raw");else if("open"===e.command){for(let t of e.positionals??[])r.push(iH(t));e.flags?.relaunch&&r.push("--relaunch"),iZ(r,e.runtime)}else if("runtime"===e.command)!function(e,t,r={}){let n=t.positionals??[];for(let t of r.includeAllPositionals?n:n.slice(0,1))e.push(iz(t,iJ));iZ(e,t.flags)}(r,e,{includeAllPositionals:t.runtimeIncludeAllPositionals});else if("record"===e.command)!function(e,t){let[r,...n]=t.positionals??[];for(let t of(r&&e.push(iz(r,iJ)),n))e.push(iH(t));"number"==typeof t.flags?.fps&&e.push("--fps",String(t.flags.fps)),"number"==typeof t.flags?.quality&&e.push("--quality",String(t.flags.quality)),t.flags?.hideTouches&&e.push("--hide-touches")}(r,e);else if("screenshot"===e.command){for(let t of e.positionals??[])r.push(iH(t));eE(r,e.flags)}else{for(let t of e.positionals??[])r.push(iH(t));iX(r,e)}return r.join(" ")}class i2{sessionsDir;constructor(e){this.sessionsDir=e}write(e){let t;try{if(!e.recordSession)return{written:!1};t=this.resolveScriptPath(e);let r=f.dirname(t);l.existsSync(r)||l.mkdirSync(r,{recursive:!0});let n=function(e){var t=e,r=function(e){let t=[];for(let r of e.actions){if("snapshot"===r.command)continue;let n=function(e){let t=function(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];return t.length>0?t.join(" || "):void 0}(e);if(t&&i3(e.command))return iq(e.command)?{...e,positionals:[t]}:"longpress"===e.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);if(!(e.length<=1)&&void 0!==t&&""!==t.trim())return Number.isFinite(Number(t))?t:void 0}(e.positionals??[]);return{...e,positionals:r?[t,r]:[t]}}(e,t):"fill"===e.command?function(e,t){let r=iL(e);return r.length>0?{...e,positionals:[t,r]}:void 0}(e,t):function(e,t){let r=e.positionals?.[0];return"text"===r||"attrs"===r?{...e,positionals:[r,t]}:void 0}(e,t)}(r);if(n){t.push(n);continue}let i=function(e,t){if(!i3(t.command))return;let r=t.result?.refLabel;if("string"!=typeof r||0===r.trim().length)return;let n=r.trim();return{ts:t.ts,command:"snapshot",positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotCompact:!0,snapshotScope:n},result:{scope:n}}}(e,r);i&&t.push(i),t.push(r)}return t}(e);let n=[],i=t.device.kind?` kind=${t.device.kind}`:"";for(let e of(n.push(`context platform=${t.device.platform} device=${iW(t.device.name)}${i} theme=unknown`),r))e.flags?.noRecord||n.push(function(e){var t,r;let n=(t=[e.command],r=e,iq(r.command)?function(e,t){let r=t.positionals?.[0];if(r){if(r.startsWith("@"))return e.push(iH(r)),i5(e,t),iX(e,t),e.join(" ");if(1===t.positionals.length)return e.push(iH(r)),iX(e,t),e.join(" ")}}(t,r):"fill"===r.command?function(e,t){let r=t.positionals?.[0];if(!r?.startsWith("@"))return;e.push(iH(r)),i5(e,t);let n=t.positionals.slice(1).join(" ");return t.positionals.length>1&&e.push(iH(n)),iX(e,t),e.join(" ")}(t,r):"get"===r.command?function(e,t){let r=t.positionals?.[0],n=t.positionals?.[1];if(r&&n)return e.push(iH(r)),e.push(iH(n)),n.startsWith("@")&&i5(e,t),e.join(" ")}(t,r):void 0);return n||i1(e)}(e));return`${n.join("\n")}
8
- `}(e);return l.writeFileSync(t,n),{written:!0,path:t}}catch(r){return eN({level:"warn",phase:"session_script_write_failed",data:{session:e.name,path:t,error:r instanceof Error?r.message:String(r)}}),{written:!1}}}resolveScriptPath(e){if(e.saveScriptPath)return e6(e.saveScriptPath,{cwd:void 0});l.existsSync(this.sessionsDir)||l.mkdirSync(this.sessionsDir,{recursive:!0});let t=iC(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,"-");return f.join(this.sessionsDir,`${t}-${r}.ad`)}}function i3(e){return iB(e)||"fill"===e||"get"===e}function i5(e,t){let r=t.result?.refLabel;"string"==typeof r&&r.trim().length>0&&e.push(iH(r))}class i4{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new i2(e)}get(e){return this.sessions.get(e)}has(e){return this.sessions.has(e)}set(e,t){this.sessions.set(e,t)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){t.flags?.noRecord||(t.flags?.saveScript&&(e.recordSession=!0,"string"==typeof t.flags.saveScript&&(e.saveScriptPath=e6(t.flags.saveScript,{cwd:void 0}))),e.actions.push({ts:Date.now(),command:t.command,positionals:t.positionals,runtime:t.runtime,flags:function(e){if(!e)return{};let t={};for(let r of iE)void 0!==e[r]&&(t[r]=e[r]);return t}(t.flags),result:t.result}),eN({level:"debug",phase:"record_action",data:{command:t.command,session:e.name}}))}writeSessionLog(e){let t=this.scriptWriter.write(e);t.written&&eN({level:"info",phase:"session_script_written",data:{session:e.name,path:t.path}})}defaultTracePath(e){let t=iC(e.name),r=new Date().toISOString().replace(/[:.]/g,"-");return f.join(this.sessionsDir,`${t}-${r}.trace.log`)}resolveAppLogPath(e){return f.join(this.sessionsDir,iC(e),"app.log")}resolveAppLogPidPath(e){return f.join(this.sessionsDir,iC(e),"app-log.pid")}static expandHome(e,t){return e6(e,{cwd:t})}}let i8="app-log.pid";function i6(e){let t=e.trim();if(!t)return null;if(/^\d+$/.test(t))return{pid:Number.parseInt(t,10)};try{let e=JSON.parse(t);if(!Number.isInteger(e.pid)||e.pid<=0)return null;return e}catch{return null}}function i9(e,t){if(!e)return;let r=f.dirname(e);l.existsSync(r)||l.mkdirSync(r,{recursive:!0});let n={pid:t,startTime:eh(t)??void 0,command:eg(t)??void 0};l.writeFileSync(e,`${JSON.stringify(n)}
9
- `)}function i7(e){if(e&&l.existsSync(e))try{l.unlinkSync(e)}catch{}}async function ae(e,t=2e3){await Promise.race([e.then(()=>void 0).catch(()=>void 0),new Promise(e=>setTimeout(e,t))])}function at(e,t){let r=t.includeTokens?.filter(e=>e.length>0)??[],n="",i=n=>{(!(r.length>0)||r.some(e=>n.includes(e)))&&e.write(function(e,t){if(0===t.length)return e;let r=e;for(let e of t)r=r.replace(e,"[REDACTED]");return r}(n,t.redactionPatterns))};return{onChunk:e=>{let t=`${n}${e}`.split("\n");for(let e of(n=t.pop()??"",t))i(`${e}
10
- `)},flush:()=>{n&&(i(n),n="")}}}function ar(e,t,r){let n=e.stdout,i=e.stderr;return n&&i?(n.setEncoding("utf8"),i.setEncoding("utf8"),n.on("data",r.writer.onChunk),i.on("data",r.writer.onChunk),t.on("error",()=>{e.killed||e.kill("SIGKILL")}),e.on("error",()=>t.destroy()),new Promise(n=>{e.on("close",e=>{r.writer.flush(),r.endStreamOnClose&&t.end(),n({stdout:"",stderr:"",exitCode:e??1})})})):Promise.resolve({stdout:"",stderr:"missing stdio pipes",exitCode:1})}function an(e){if(!/^[a-zA-Z0-9._:-]+$/.test(e))throw new D("INVALID_ARGS",`Invalid Android package name for logs: ${e}`)}async function ai(e,t){let r=(await tn(z(e))(["shell","pidof",t],{allowFailure:!0})).stdout.trim().split(/\s+/)[0];return r&&/^\d+$/.test(r)?r:null}async function aa(e,t){var r,n;let i;an(t);let a=await ai(e,t),o=tn(z(e)),s=await K(o,{lines:4e3,timeoutMs:3e3}).catch(()=>"");if(0===s.trim().length)return null;let l=function(e,t,r){let n=new Set;for(let i of(r&&n.add(r),e.split("\n")))if(i.includes(t))for(let e of function(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=[RegExp(`\\bStart proc\\s+(\\d+):${r}(?:\\b|/)`,"i"),RegExp(`\\b(\\d+):${r}(?:\\b|/)`,"i"),RegExp(`${r}.*?\\bpid\\s*[=:]?\\s*(\\d+)\\b`,"i"),RegExp(`\\bpid\\s*[=:]?\\s*(\\d+)\\b.*${r}`,"i")],i=[];for(let t of n){let r=t.exec(e),n=r?.[1];n&&/^\d+$/.test(n)&&i.push(n)}return i}(i,t))n.add(e);return[...n]}(s,t,a);if(0===l.length)return null;let u=(r=s,n=t,i=new Set(l),r.split("\n").filter(e=>{var t;let r;if(!e.trim())return!1;if(e.includes(n))return!0;let a=(t=e,r=/\(\s*(\d+)\)\s*:/.exec(t),r?.[1]??null);return!!a&&i.has(a)}).join("\n"));return 0===u.trim().length?null:{pid:a,text:u,recoveredPids:l}}async function ao(e,t,r,n,i){let a,o,s="recovering",l=!1,u=(async()=>{try{for(;!l;){let u=await ai(e,t);if(!u){s="recovering",await e8(1e3);continue}let d=tt(z(e)),c=G(d,{pid:u});a=c;let p=at(r,{redactionPatterns:n});if(o=ar(c,r,{endStreamOnClose:!1,writer:p}),"number"==typeof c.pid&&i9(i,c.pid),s="active",await o,i7(i),a=void 0,o=void 0,l)break;s="recovering",await e8(500)}return{stdout:"",stderr:"",exitCode:0}}finally{r.end(),i7(i)}})();return{backend:"android",getState:()=>s,startedAt:Date.now(),wait:u,stop:async()=>{l=!0,a&&!a.killed&&a.kill("SIGINT"),o&&await ae(o),a&&!a.killed&&a.kill("SIGKILL"),await ae(u),i7(i)}}}function as(e,t){let r=ad(e),n=[`subsystem == "${r}"`,`subsystem CONTAINS "${r}"`,`processImagePath ENDSWITH[c] "/${r}"`,`senderImagePath ENDSWITH[c] "/${r}"`];if(t){let e=ad(t);n.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return n.join(" OR ")}async function al(e){let{deviceId:t,appBundleId:r,executableName:n,startedAt:i,simulatorSetPath:a}=e,o=rq(["spawn",t,"log","show","--style","compact","--info","--predicate",as(r,n)],{simulatorSetPath:a});"number"==typeof i&&Number.isFinite(i)&&i>0?o.push("--start",`@${Math.floor(i/1e3)}`):o.push("--last","5m");let s=await rU(o,{allowFailure:!0,timeoutMs:4e3});if(0!==s.exitCode||0===s.stdout.trim().length)return null;let l=s.stdout.split("\n").map(e=>e.trimEnd()).filter(e=>{let t=e.trim();return t.length>0&&!t.startsWith("Timestamp Ty Process[PID:TID]")});return 0===l.length?null:{text:`${l.join("\n")}
11
- `,recoveredLineCount:l.length}}async function au(e,t,r,n,i,a){let o=await ac({deviceId:e,appBundleId:t,simulatorSetPath:i});return am({backend:"ios-simulator",cmd:"xcrun",args:function(e){let{deviceId:t,appBundleId:r,executableName:n,simulatorSetPath:i}=e;return rq(["spawn",t,"log","stream","--style","compact","--level","info","--predicate",as(r,n)],{simulatorSetPath:i})}({deviceId:e,appBundleId:t,executableName:o,simulatorSetPath:i}),stream:r,redactionPatterns:n,pidPath:a})}function ad(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}async function ac(e){let{deviceId:t,appBundleId:r,simulatorSetPath:n}=e,i=await rU(rq(["get_app_container",t,r,"app"],{simulatorSetPath:n}),{allowFailure:!0,timeoutMs:4e3});if(0!==i.exitCode)return;let a=i.stdout.trim();if(!a)return;let o=f.join(a,"Info.plist"),s=await R("plutil",["-extract","CFBundleExecutable","raw","-o","-",o],{allowFailure:!0,timeoutMs:4e3});if(0===s.exitCode)return s.stdout.trim()||void 0}async function ap(e,t,r,n){return am({backend:"macos",cmd:"log",args:["stream","--style","compact","--predicate",as(e)],stream:t,redactionPatterns:r,pidPath:n})}async function af(e,t,r,n){return am({backend:"ios-device",cmd:"xcrun",args:["devicectl","device","log","stream","--device",e],stream:t,redactionPatterns:r,pidPath:n})}function am(e){let t="active",r=O(e.cmd,e.args,{allowFailure:!0,captureOutput:!1});r.wait.catch(()=>{});let n=r.child,i=at(e.stream,{redactionPatterns:e.redactionPatterns});"number"==typeof n.pid&&i9(e.pidPath,n.pid);let a=ar(n,e.stream,{endStreamOnClose:!0,writer:i}).then(r=>(0!==r.exitCode&&(t="failed"),i7(e.pidPath),r),r=>{throw t="failed",i7(e.pidPath),r});return{backend:e.backend,getState:()=>t,startedAt:Date.now(),wait:a,stop:async()=>{n.killed||n.kill("SIGINT"),await ae(a),n.killed||n.kill("SIGKILL"),await ae(a),i7(e.pidPath)}}}let ah=RegExp("\\b(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b\\s+https?:\\/\\/","i"),aw=/https?:\/\/[^\s"'<>\])]+/i,ag=[/\bstatus(?:Code)?["'=: ]+([1-5]\d{2})\b/i,/\bresponse(?:\s+code)?["'=: ]+([1-5]\d{2})\b/i,/\bHTTP\/[0-9.]+\s+([1-5]\d{2})\b/i];function ay(e,t,r=e.limits.maxEntries){let n=[...e.entries],i=new Set(n.map(e=>aI(e)));for(let e of t.entries){let t=aI(e);if(!i.has(t)&&(i.add(t),n.push(e),n.length>=r))break}return{...e,matchedLines:n.length,entries:n}}function av(e,t){let r=aO(t?.maxEntries,25,1,200),n=t?.backend,i=t?.include??"summary",a=aO(t?.maxPayloadChars,2048,64,16384),o=aO(t?.maxScanLines,4e3,100,2e4),s=e.split("\n"),l=Math.max(0,s.length-o),u=s.slice(l),d=[];for(let e=u.length-1;e>=0&&d.length<r;e-=1){let t=u[e];if(!t?.trim())continue;let r=function(e,t,r,n,i,a){let o=e[t]?.trim();if(!o)return null;let s=function(e){let t=e.indexOf("{");if(t<0)return null;let r=e.lastIndexOf("}");if(r<=t)return null;let n=e.slice(t,r+1);try{let e=JSON.parse(n);return e&&"object"==typeof e?e:null}catch{return null}}(o),l=aN(s,["method","httpMethod"]),u=aN(s,["url","requestUrl"]),d=function(e,t){if(!e)return null;for(let r of t){let t=e[r];if("number"==typeof t&&Number.isInteger(t))return t;if("string"==typeof t&&/^\d{3}$/.test(t.trim()))return Number.parseInt(t.trim(),10)}return null}(s,["status","statusCode","responseCode"]),c=ah.exec(o),p=/\bmethod["'=: ]+([A-Z]+)\b/i.exec(o),f=(l??p?.[1]??c?.[1])?.toUpperCase(),m=aw.exec(o),h=u??m?.[0];if(!h)return null;let w=d??aA(o)??void 0;if(!(l||p?.[1]||c?.[1]||void 0!==w||/\bURL["'=: ]+https?:\/\//i.test(o)||/\bheaders?["'=: ]+/i.test(o)||/\b(?:requestBody|responseBody|payload|request|response)["'=: ]+/i.test(o)))return null;let g={method:f,url:h,status:w,timestamp:aS(o),packetId:ax(o)??void 0,durationMs:a_(o)??void 0,raw:aD(o,a),line:r};if("android"===n&&function(e,t,r){let n=ab(t,r,5),i=e.packetId??n.map(e=>ax(e)).find(e=>"string"==typeof e&&e.length>0);i&&(e.packetId=i);let a=i?ab(t,r,12).filter(e=>ax(e)===i):n;e.timestamp||(e.timestamp=a.map(e=>aS(e)).find(e=>"string"==typeof e&&e.length>0)),void 0===e.status&&(e.status=a.map(e=>aA(e)).find(e=>"number"==typeof e)),void 0===e.durationMs&&(e.durationMs=a.map(e=>a_(e)).find(e=>"number"==typeof e))}(g,e,t),"headers"===i||"all"===i){let e=function(e,t){if(t){let e=t.headers??t.requestHeaders??t.responseHeaders;if(void 0!==e)return ak(e)}let r=/\bheaders?["'=: ]+(\{.*\})/i.exec(e);return r?.[1]?.trim()}(o,s);e&&(g.headers=aD(e,a))}if("body"===i||"all"===i){let e=aM(o,s,["requestBody","body","payload","request"]),t=aM(o,s,["responseBody","response"]);e&&(g.requestBody=aD(e,a)),t&&(g.responseBody=aD(t,a))}return g}(u,e,l+e+1,n,i,a);r&&d.push(r)}return{path:t?.path??"<memory>",exists:!0,scannedLines:u.length,matchedLines:d.length,entries:d,include:i,limits:{maxEntries:r,maxPayloadChars:a,maxScanLines:o}}}function aI(e){return`${e.timestamp??""}|${e.method??""}|${e.url}|${e.status??""}|${e.raw}`}function ab(e,t,r){let n=[],i=Math.max(0,t-r),a=Math.min(e.length-1,t+r);for(let t=i;t<=a;t+=1){let r=e[t]?.trim();r&&n.push(r)}return n}function aA(e){for(let t of ag){let r=t.exec(e);if(!r)continue;let n=Number.parseInt(r[1]??"",10);if(Number.isInteger(n))return n}return null}function aS(e){let t=/\b\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z)?\b/.exec(e);if(t)return t[0];let r=/\b\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+\b/.exec(e);return r?.[0]}function ax(e){let t=/\bpacket id (\d+)\b/i.exec(e);return t?.[1]??null}function a_(e){let t=/\b(?:duration|elapsed request\/response time, ms)[:= ]+(\d+)\b/i.exec(e);if(!t)return null;let r=Number.parseInt(t[1]??"",10);return Number.isInteger(r)?r:null}function aN(e,t){if(e)for(let r of t){let t=e[r];if("string"==typeof t&&t.trim().length>0)return t.trim()}}function aM(e,t,r){if(t){for(let e of r)if(void 0!==t[e])return ak(t[e])}for(let t of r){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=RegExp(`\\b${r}["'=: ]+(.+)$`,"i").exec(e);if(n?.[1])return n[1].trim()}}function ak(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}}function aD(e,t){return e.length<=t?e:`${e.slice(0,t)}...<truncated>`}function aO(e,t,r,n){return void 0!==e&&Number.isInteger(e)?Math.max(r,Math.min(n,e)):t}let aP={start:async e=>await aU(e)},aR=rM(aP,function(e={}){return{...aP,...e}});async function aC(e,t){return await aR.run(e,t)}function aE(e,t){let r=process.env[e];if(!r)return t;let n=Number.parseInt(r,10);return Number.isInteger(n)&&n>0?n:t}function aL(e){let t=f.dirname(e);l.existsSync(t)||l.mkdirSync(t,{recursive:!0}),function(e,t){if(l.existsSync(e)&&!(l.statSync(e).size<t.maxBytes))for(let r=t.maxRotatedFiles;r>=1;r-=1){let t=1===r?e:`${e}.${r-1}`,n=`${e}.${r}`;l.existsSync(t)&&(l.existsSync(n)&&l.unlinkSync(n),l.renameSync(t,n))}}(e,{maxBytes:aE("AGENT_DEVICE_APP_LOG_MAX_BYTES",5242880),maxRotatedFiles:aE("AGENT_DEVICE_APP_LOG_MAX_FILES",1)})}async function aT(e){var t,r,n,i;let a,o,s,u,{device:d,appBundleId:c,appLogState:p,appLogStartedAt:f,appLogPath:m,maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y}=e,v="macos"===d.platform?"macos":"ios"===d.platform?"device"===d.kind?"ios-device":"ios-simulator":"android",I=(t={backend:v,maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y},a=aO(t?.maxEntries,25,1,200),o=t?.include??"summary",s=aO(t?.maxPayloadChars,2048,64,16384),u=aO(t?.maxScanLines,4e3,100,2e4),l.existsSync(m)?av(l.readFileSync(m,"utf8"),{...t,path:m}):{path:m,exists:!1,scannedLines:0,matchedLines:0,entries:[],include:o,limits:{maxEntries:a,maxPayloadChars:s,maxScanLines:u}}),b=[],A=await a$({device:d,appBundleId:c,appLogPath:m,appLogState:p});if(A){let e=await aa(d.id,c);if(e){let t=av(e.text,{path:`${m} (adb logcat recovery)`,backend:"android",maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y});t.entries.length>0&&(I=ay(t,I,h),b.push((r=A,n=e.recoveredPids,"stale-active"===r.reason?`Session app log stream was still bound to prior Android PID ${r.trackedPid}. Recovered recent Android HTTP entries from adb logcat for PID set ${n.join(", ")}.`:`Session app log stream was inactive. Recovered recent Android HTTP entries from adb logcat for PID set ${n.join(", ")}.`)))}}if("ios"===d.platform&&"simulator"===d.kind&&c&&0===I.entries.length){let e=await aV({deviceId:d.id,appBundleId:c,startedAt:f,simulatorSetPath:d.simulatorSetPath,appLogPath:m,maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y});e&&(e.dump.entries.length>0?(I=ay(e.dump,I,h),b.push(`Recovered ${e.dump.entries.length} iOS simulator HTTP entr${1===e.dump.entries.length?"y":"ies"} from simctl log show (${e.recoveredLineCount} app log lines scanned).`)):e.recoveredLineCount>0&&b.push(`Recovered ${e.recoveredLineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`))}return void 0===p?b.push("Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests."):"active"!==p&&0===b.length&&("ios"===d.platform&&"simulator"===d.kind?b.push("Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop."):b.push("Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.")),0===I.entries.length&&b.push("ios"===(i=d).platform&&"simulator"===i.kind?"No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.":"ios"===i.platform?"No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.":"No HTTP(s) entries were found in recent session app logs."),{backend:v,dump:I,notes:b}}async function a$(e){let{device:t,appBundleId:r,appLogPath:n,appLogState:i}=e;if("android"!==t.platform||!r)return null;if(void 0!==i&&"active"!==i)return{reason:"inactive"};if("active"!==i)return null;let a=function(e){let t=function(e){if(!e||!l.existsSync(e))return null;try{return i6(l.readFileSync(e,"utf8"))}catch{return null}}(e)?.command;if(!t)return null;let r=/(?:^|\s)--pid\s+(\d+)(?:\s|$)/.exec(t);return r?.[1]??null}(f.join(f.dirname(n),i8));if(!a)return null;let o=await ai(t.id,r);return o&&o!==a?{reason:"stale-active",trackedPid:a}:null}async function aF(e,t,r,n){return await aR.resolve(void 0).start({device:e,appBundleId:t,outPath:r,pidPath:n})}async function aU({device:e,appBundleId:t,outPath:r,pidPath:n}){aL(r);let i=l.createWriteStream(r,{flags:"a"}),a=function(){let e=process.env.AGENT_DEVICE_APP_LOG_REDACT_PATTERNS;if(!e)return[];let t=e.split(",").map(e=>e.trim()).filter(e=>e.length>0),r=[];for(let e of t)try{r.push(RegExp(e,"gi"))}catch{}return r}();if("ios"===e.platform)return"device"===e.kind?await af(e.id,i,a,n):await au(e.id,t,i,a,e.simulatorSetPath,n);if("android"===e.platform)return an(t),await ao(e.id,t,i,a,n);if("macos"===e.platform)return await ap(t,i,a,n);throw i.end(),new D("UNSUPPORTED_PLATFORM",`unsupported platform: ${e.platform}`)}async function aV(e){let t=await al({deviceId:e.deviceId,appBundleId:e.appBundleId,startedAt:e.startedAt,simulatorSetPath:e.simulatorSetPath});return t?{dump:av(t.text,{path:`${e.appLogPath} (simctl log show recovery)`,backend:"ios-simulator",maxEntries:e.maxEntries,include:e.include,maxPayloadChars:e.maxPayloadChars,maxScanLines:e.maxScanLines}),recoveredLineCount:t.recoveredLineCount}:null}async function aG(e){await e.stop(),await ae(e.wait)}async function aq(e,t){let r={},n=[];if(t||n.push("No app bundle is tracked in this session. Run open <app> first for app-scoped logs."),"android"===e.platform){try{let t=await Z(e,["shell","echo","ok"],{allowFailure:!0,timeoutMs:1e3});r.adbAvailable=0===t.exitCode}catch{r.adbAvailable=!1}if(t)try{r.androidPidVisible=(await Z(e,["shell","pidof",t],{allowFailure:!0,timeoutMs:1e3})).stdout.trim().length>0}catch{r.androidPidVisible=!1}}if("ios"===e.platform&&"simulator"===e.kind)try{let e=await rU(["simctl","help"],{allowFailure:!0});r.simctlAvailable=0===e.exitCode}catch{r.simctlAvailable=!1}if("ios"===e.platform&&"device"===e.kind)try{let e=await rU(["devicectl","--version"],{allowFailure:!0});r.devicectlAvailable=0===e.exitCode}catch{r.devicectlAvailable=!1}if("macos"===e.platform)try{let e=await R("log",["help"],{allowFailure:!0});r.logAvailable=0===e.exitCode}catch{r.logAvailable=!1}return{checks:r,notes:n}}function aB(e){let t=f.dirname(e),r=f.basename(e);l.existsSync(t)||l.mkdirSync(t,{recursive:!0}),l.existsSync(e)?l.truncateSync(e,0):l.writeFileSync(e,"","utf8");let n=0;for(let e of l.readdirSync(t)){if(!e.startsWith(`${r}.`))continue;let i=e.slice(r.length+1);if(/^\d+$/.test(i))try{l.unlinkSync(f.join(t,e)),n+=1}catch{}}return{path:e,cleared:!0,removedRotatedFiles:n}}let aj=new Map;function aH(e){let t=o.randomUUID(),r=setTimeout(()=>{aW(t)},9e5);return r.unref(),aj.set(t,{artifactPath:e.artifactPath,tenantId:e.tenantId,fileName:e.fileName,deleteAfterDownload:!1!==e.deleteAfterDownload,timer:r}),t}function aW(e){let t=aj.get(e);if(t&&(clearTimeout(t.timer),aj.delete(e),t.deleteAfterDownload))try{l.rmSync(t.artifactPath,{force:!0})}catch{}}let az=new Map;function aK(e,t){let r=az.get(e);if(!r)throw new D("INVALID_ARGS",`Uploaded artifact not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new D("UNAUTHORIZED","Uploaded artifact belongs to a different tenant");return clearTimeout(r.timer),r.artifactPath}function aJ(e){let t=az.get(e);t&&(clearTimeout(t.timer),az.delete(e),l.rmSync(t.tempDir,{recursive:!0,force:!0}))}async function aX(e){let t=await aZ(e);await R("tar",["xf",e.archivePath,"-C",e.tempDir]);let r=f.join(e.tempDir,t);if(!l.existsSync(r))throw new D("INVALID_ARGS",`Expected extracted bundle "${t}" not found in archive`);return r}async function aZ(e){let t=await R("tar",["-tf",e.archivePath],{allowFailure:!0});if(0!==t.exitCode)throw new D("INVALID_ARGS","Artifact is not a valid tar archive",{archivePath:e.archivePath,stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let r=t.stdout.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);if(0===r.length)throw new D("INVALID_ARGS","Uploaded app bundle archive is empty");let n=r.map(aY),i=e.expectedRootName??function(e,t){let r=new Set;for(let t of e){let[e]=t.split("/");e&&r.add(e)}let n=[...r];if("ios"===t){let e=n.filter(e=>e.toLowerCase().endsWith(".app")),t=e[0];if(void 0!==t&&1===e.length)return t;if(0===e.length)throw new D("INVALID_ARGS","iOS app bundle archives must contain a single top-level .app directory");throw new D("INVALID_ARGS",`iOS app bundle archives must contain exactly one top-level .app directory, found: ${e.join(", ")}`)}let i=n[0];if(void 0!==i&&1===n.length)return i;throw new D("INVALID_ARGS",`Archive must contain a single top-level bundle, found: ${n.join(", ")}`)}(n,e.platform);if(!n.some(e=>e===i||e.startsWith(`${i}/`)))throw new D("INVALID_ARGS",`Uploaded archive must contain a top-level "${i}" bundle`);for(let e of n){var a=e,o=i;if(a!==o&&!a.startsWith(`${o}/`))throw new D("INVALID_ARGS",`Archive entry must stay inside top-level "${o}" bundle: ${a}`)}for(let t of(await R("tar",["-tvf",e.archivePath])).stdout.split(/\r?\n/).filter(Boolean))if("l"===t[0]||"h"===t[0])throw new D("INVALID_ARGS","Uploaded app bundle archive cannot contain symlinks or hard links");return i}function aY(e){if(e.includes("\0"))throw new D("INVALID_ARGS",`Invalid archive entry: ${e}`);if(f.posix.isAbsolute(e))throw new D("INVALID_ARGS",`Archive entry must be relative: ${e}`);let t=f.posix.normalize(e).replace(/^(\.\/)+/,"");if(!t||"."===t||t.startsWith("../"))throw new D("INVALID_ARGS",`Archive entry escapes bundle root: ${e}`);return t}function aQ(e,t){return new Promise((r,n)=>{let i,a=!1,o=0,s=l.createWriteStream(t),u=e=>{if(!a){if(a=!0,i&&clearTimeout(i),e)return void a0(s,t).finally(()=>n(e));r()}},d=()=>{i&&clearTimeout(i),i=setTimeout(()=>{let t=new D("COMMAND_FAILED","Artifact transfer timed out due to inactivity",{timeoutMs:6e4});"destroy"in e&&"function"==typeof e.destroy&&e.destroy(t),c.destroy(t),u(t)},6e4)},c=new I({transform(e,t,r){d();let n=Buffer.isBuffer(e)?e.length:Buffer.byteLength(e,t);(o+=n)>0x80000000?r(new D("INVALID_ARGS","Upload exceeds maximum size of 2147483648 bytes")):r(null,e)}});e.on("aborted",()=>{u(new D("COMMAND_FAILED","Artifact transfer was interrupted"))}),d(),b(e,c,s).then(()=>u(),e=>u(e))})}async function a0(e,t){if(e.destroy(),!e.closed)try{await v(e,"close")}catch{}await l.promises.rm(t,{force:!0}).catch(()=>{})}async function a1(e){let t,r=e.headers["x-artifact-type"],n=e.headers["x-artifact-filename"];if(!r||!n)throw new D("INVALID_ARGS","Missing required headers: x-artifact-type and x-artifact-filename");if("file"!==r&&"app-bundle"!==r)throw new D("INVALID_ARGS",`Invalid x-artifact-type: ${r}. Must be "file" or "app-bundle".`);!function(e){if(void 0===e)return;let t=Number(e);if(Number.isFinite(t)&&t>0x80000000)throw new D("INVALID_ARGS","Upload exceeds maximum size of 2147483648 bytes")}(e.headers["content-length"]);let i=function(e){let t=e.trim(),r=f.basename(t);if(!r||"."===r||".."===r)throw new D("INVALID_ARGS",`Invalid artifact filename: ${e}`);return r}(n),a=(t=function(e){let t=e?.trim();if(!t)return"request";let r=t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");return r.length>0?r.slice(0,48):"request"}("upload"),l.mkdtempSync(f.join(c.tmpdir(),`agent-device-artifact-${t}-`)));try{if("file"===r){let t=f.join(a,i);return await aQ(e,t),{artifactPath:t,tempDir:a}}let t=f.join(a,"artifact.tar");await aQ(e,t);let n=await aX({archivePath:t,tempDir:a,platform:"ios",expectedRootName:i});return l.rmSync(t,{force:!0}),{artifactPath:n,tempDir:a}}catch(e){throw l.rmSync(a,{recursive:!0,force:!0}),e}}let a2=new h;async function a3(e,t){return await a2.run(e,t)}function a5(e){a2.getStore()?.(e)}let a4=new Set(["agent_device.command","agent-device.command"]),a8=new Set(["agent_device.install_from_source","agent-device.install_from_source"]),a6=new Set(["agent_device.release_materialized_paths","agent-device.release_materialized_paths"]),a9={"agent_device.lease.allocate":"lease_allocate","agent-device.lease.allocate":"lease_allocate","agent_device.lease.heartbeat":"lease_heartbeat","agent-device.lease.heartbeat":"lease_heartbeat","agent_device.lease.release":"lease_release","agent-device.lease.release":"lease_release"},a7=new Set([...a4,...a8,...a6,...Object.keys(a9)]);function oe(e,t,r,n){return{jsonrpc:"2.0",id:e,error:{code:t,message:r,data:n}}}function ot(e,t,r=200){e.statusCode=r,e.setHeader("content-type","application/json"),e.end(JSON.stringify(t))}function or(e,t){e.destroyed||(e.write(eT(t)),e.end())}function on(e){switch(e){case"INVALID_ARGS":return 400;case"UNAUTHORIZED":return 401;case"SESSION_NOT_FOUND":return 404;default:return 500}}function oi(e,t){let r="string"==typeof t.authorization?t.authorization:"",n=r.toLowerCase().startsWith("bearer ")?r.slice(7):void 0,i="string"==typeof t["x-agent-device-token"]?t["x-agent-device-token"]:void 0;return("string"==typeof e.token?e.token:void 0)??i??n??""}function oa(e,t){let r=e[t];return"string"==typeof r?r:void 0}function oo(e,t){let r=e[t];return Number.isInteger(r)?Number(r):void 0}function os(e,t){let r="string"==typeof e[t]?e[t].trim():"";if(!r)throw new D("INVALID_ARGS",`Invalid params: source.${t} is required for github-actions-artifact sources`);return r}function ol(e,t){let r=e[t],n="number"==typeof r?r:"string"==typeof r?Number(r):NaN;if(!Number.isInteger(n))throw new D("INVALID_ARGS",`Invalid params: source.${t} must be an integer`);return n}async function ou(e,t){if(!e)return{ok:!0};let r=await e(t);if(void 0===r||!0===r)return{ok:!0};if(!1===r){let e=k(new D("UNAUTHORIZED","Request rejected by auth hook"));return{ok:!1,statusCode:401,response:oe(t.rpcRequest.id??null,-32001,e.message,e)}}if(!1===r.ok){let e=k(new D(N(r.code,"UNAUTHORIZED"),r.message??"Request rejected by auth hook",r.details));return{ok:!1,statusCode:401,response:oe(t.rpcRequest.id??null,-32001,e.message,e)}}if("string"==typeof r.tenantId&&r.tenantId.length>0){let e=eP(r.tenantId);if(!e){let e=k(new D("INVALID_ARGS","Auth hook returned invalid tenantId"));return{ok:!1,statusCode:500,response:oe(t.rpcRequest.id??null,-32e3,e.message,e)}}return{ok:!0,tenantId:e}}return{ok:!0}}async function od(){let e,t=process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;if(!t)return null;let r=process.env.AGENT_DEVICE_HTTP_AUTH_EXPORT||"default",n=f.isAbsolute(t)?t:f.resolve(t);try{e=await import(y(n).href)}catch(e){throw new D("COMMAND_FAILED","Failed to load AGENT_DEVICE_HTTP_AUTH_HOOK module",{hookPath:n,error:e instanceof Error?e.message:String(e)})}let i=e[r];if("function"!=typeof i)throw new D("INVALID_ARGS",`Auth hook export ${r} is not a function`,{hookPath:n,exportName:r});return i}async function oc(e){let t=await od(),{handleRequest:r,token:n}=e;return w.createServer((e,i)=>{if("GET"===e.method&&"/health"===e.url){i.statusCode=200,i.setHeader("content-type","application/json"),i.end(JSON.stringify({ok:!0}));return}if("POST"===e.method&&"/upload"===e.url)return void op(e,i,t,n);if("GET"===e.method&&e.url?.startsWith("/artifacts/"))return void of(e,i,t,n);if("POST"!==e.method||"/rpc"!==e.url){i.statusCode=404,i.end("Not found");return}let a="";e.setEncoding("utf8"),e.on("data",t=>{(a+=t).length>1048576&&e.destroy(Error("request too large"))}),e.on("error",()=>{i.headersSent||ot(i,oe(null,-32700,"Parse error"),400)}),e.on("end",async()=>{let n,o;try{n=JSON.parse(a)}catch{ot(i,oe(null,-32700,"Parse error"),400);return}if("2.0"!==n.jsonrpc||"string"!=typeof n.method)return void ot(i,oe(n.id??null,-32600,"Invalid Request"),400);if(!a7.has(n.method))return void ot(i,oe(n.id??null,-32601,`Method not found: ${n.method}`),404);if(!n.params||"object"!=typeof n.params)return void ot(i,oe(n.id??null,-32602,"Invalid params"),400);try{var s;let a=n.params,l=function(e,t,r){if(a4.has(e))return{token:oi(t,r),session:t.session??"default",command:t.command??"",positionals:Array.isArray(t.positionals)?t.positionals:[],flags:t.flags,runtime:t.runtime,meta:t.meta};if(a8.has(e)){let e,n=oa(t,"platform");if("ios"!==n&&"android"!==n)throw new D("INVALID_ARGS",'Invalid params: platform must be "ios" or "android"');return{token:oi(t,r),session:oa(t,"session")??"default",command:"install_source",positionals:[],flags:{platform:n},meta:{requestId:oa(t,"requestId"),installSource:function(e){let t=e.source;if(!t||"object"!=typeof t)throw new D("INVALID_ARGS","Invalid params: source is required");if("url"===t.kind){let e="string"==typeof t.url?t.url.trim():"";if(!e)throw new D("INVALID_ARGS","Invalid params: source.url is required for url sources");let r=t.headers,n={};if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw new D("INVALID_ARGS","Invalid params: source.headers must be a string map");for(let[e,t]of Object.entries(r)){if("string"!=typeof t)throw new D("INVALID_ARGS","Invalid params: source.headers values must be strings");n[e]=t}}return Object.keys(n).length>0?{kind:"url",url:e,headers:n}:{kind:"url",url:e}}if("path"===t.kind){let e="string"==typeof t.path?t.path.trim():"";if(!e)throw new D("INVALID_ARGS","Invalid params: source.path is required for path sources");return{kind:"path",path:e}}if("github-actions-artifact"===t.kind)return function(e){let t,r=os(e,"owner"),n=os(e,"repo"),i=void 0!==e.artifactId,a=void 0!==e.runId,o=void 0!==e.artifactName;if(i&&(a||o))throw new D("INVALID_ARGS","Invalid params: source must specify either artifactId or artifactName, not both");if(!i&&a&&!o)throw new D("INVALID_ARGS","Invalid params: source.artifactName is required when source.runId is specified");if(!i&&!o)throw new D("INVALID_ARGS","Invalid params: source must specify artifactId or artifactName");return i?{kind:"github-actions-artifact",owner:r,repo:n,artifactId:ol(e,"artifactId")}:(a&&(t=ol(e,"runId")),{kind:"github-actions-artifact",owner:r,repo:n,...a?{runId:t}:{},artifactName:os(e,"artifactName")})}(t);throw new D("INVALID_ARGS",'Invalid params: source.kind must be "url", "path", or "github-actions-artifact"')}(t),retainMaterializedPaths:(e=t.retainPaths,"boolean"==typeof e?e:void 0),materializedPathRetentionMs:oo(t,"retentionMs")}}}if(a6.has(e)){let e=oa(t,"materializationId")?.trim();if(!e)throw new D("INVALID_ARGS","Invalid params: materializationId is required");return{token:oi(t,r),session:oa(t,"session")??"default",command:"release_materialized_paths",positionals:[],meta:{requestId:oa(t,"requestId"),materializationId:e}}}let n=a9[e];if(n)return{token:oi(t,r),session:oa(t,"session")??"default",command:n,positionals:[],meta:{tenantId:oa(t,"tenantId")??oa(t,"tenant"),runId:oa(t,"runId"),leaseId:oa(t,"leaseId"),leaseTtlMs:oo(t,"ttlMs"),leaseBackend:oa(t,"backend")}};throw new D("INVALID_ARGS",`Method not found: ${e}`)}(n.method,a,e.headers);if(s=n.method,a4.has(s)&&("string"!=typeof l.command||0===l.command.length))return void ot(i,oe(n.id??null,-32602,"Invalid params: command is required"),400);o=ry(l.meta?.requestId,n.id),l.meta={...l.meta,requestId:o},rv(o);let u=()=>{i.writableFinished||rI(o)};e.on("aborted",u),i.on("close",u);let d=await ou(t,{headers:e.headers,rpcRequest:n,daemonRequest:l});if(!d.ok)return void ot(i,d.response,d.statusCode);if(d.tenantId&&(l.meta={...l.meta,tenantId:d.tenantId,sessionIsolation:l.meta?.sessionIsolation??l.flags?.sessionIsolation??"tenant"}),eU(l)){i.statusCode=200,i.setHeader("content-type","application/x-ndjson");let e=await a3(e=>{!i.destroyed&&i.write(e5(e))},async()=>await r(l)),t=e.ok?{jsonrpc:"2.0",id:n.id??null,result:e}:oe(n.id??null,-32e3,e.error.message,e.error);or(i,t);return}let c=await r(l);if(c.ok)return void ot(i,{jsonrpc:"2.0",id:n.id??null,result:c});ot(i,oe(n.id??null,-32e3,c.error.message,c.error),on(c.error.code))}catch(t){let e=k(t);if(i.headersSent)return void or(i,oe(n.id??null,-32e3,e.message,e));ot(i,oe(n.id??null,-32e3,e.message,e),on(e.code))}finally{rb(o)}})})}async function op(e,t,r,n){try{var i;let a,s,l=await om({req:e,res:t,authHook:r,expectedToken:n,daemonRequest:{command:"upload",positionals:[]}});if(!l)return;let u=await a1(e),d=(i={artifactPath:u.artifactPath,tempDir:u.tempDir,tenantId:l.tenantId},a=o.randomUUID(),(s=setTimeout(()=>{aJ(a)},3e5)).unref(),az.set(a,{artifactPath:i.artifactPath,tempDir:i.tempDir,tenantId:i.tenantId,timer:s}),a);t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!0,uploadId:d}))}catch(e){oh(t,k(e))}}async function of(e,t,r,n){let i=e.url?.slice("/artifacts/".length)??"";if(!i){t.statusCode=400,t.end("Missing artifact id");return}try{let a=await om({req:e,res:t,authHook:r,expectedToken:n,daemonRequest:{command:"download_artifact",positionals:[i]}});if(!a)return;let o=function(e,t){let r=aj.get(e);if(!r)throw new D("INVALID_ARGS",`Artifact not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new D("UNAUTHORIZED","Artifact belongs to a different tenant");if(!l.existsSync(r.artifactPath))throw aW(e),new D("COMMAND_FAILED",`Artifact file is missing: ${r.artifactPath}`);return{artifactPath:r.artifactPath,fileName:r.fileName,deleteAfterDownload:r.deleteAfterDownload}}(i,a.tenantId),s=l.createReadStream(o.artifactPath);t.statusCode=200,t.setHeader("content-type","application/octet-stream"),o.fileName&&t.setHeader("content-disposition",`attachment; filename="${o.fileName.replace(/"/g,"")}"`),s.on("error",e=>{if(t.headersSent)t.destroy(e);else{let r=k(e);t.statusCode=on(r.code),t.end(r.message)}}),t.on("close",()=>{t.writableFinished&&aW(i)}),s.pipe(t)}catch(e){oh(t,k(e))}}async function om(e){var t,r;let{req:n,res:i,authHook:a,expectedToken:o,daemonRequest:s}=e,l=oi({},n.headers),u=(t=l,(r=o)&&t!==r?k(new D("UNAUTHORIZED","Invalid token")):null);if(u)return oh(i,u),null;let d=await ou(a,{headers:n.headers,rpcRequest:{jsonrpc:"2.0",id:null,method:"agent_device.command"},daemonRequest:{token:l,session:"default",command:s.command,positionals:s.positionals}});return d.ok?{tenantId:d.tenantId}:(i.statusCode=d.statusCode,i.setHeader("content-type","application/json"),i.end(JSON.stringify({ok:!1,error:d.response.error?.data?.message??d.response.error?.message??"Unauthorized"})),null)}function oh(e,t){e.statusCode=on(t.code),e.setHeader("content-type","application/json"),e.end(JSON.stringify({ok:!1,error:t.message,code:t.code}))}function ow(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}function og(e){if(!e)return;let t=e.trim();if(t&&/^[a-f0-9]{16,128}$/i.test(t))return t.toLowerCase()}function oy(e){let t=(e??"").trim().toLowerCase();if(!t||"ios-simulator"===t)return"ios-simulator";if("ios-instance"===t||"android-instance"===t)return t;throw new D("INVALID_ARGS",`Unsupported lease backend: ${e??""}`)}class ov{leases=new Map;runBindings=new Map;maxActiveSimulatorLeases;defaultLeaseTtlMs;minLeaseTtlMs;maxLeaseTtlMs;now;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.defaultLeaseTtlMs=Number.isInteger(e.defaultLeaseTtlMs)?Math.max(1,Number(e.defaultLeaseTtlMs)):6e4,this.minLeaseTtlMs=Number.isInteger(e.minLeaseTtlMs)?Math.max(1,Number(e.minLeaseTtlMs)):5e3,this.maxLeaseTtlMs=Number.isInteger(e.maxLeaseTtlMs)?Math.max(this.minLeaseTtlMs,Number(e.maxLeaseTtlMs)):6e5,this.now=e.now??(()=>Date.now())}allocateLease(e){let t=oy(e.backend),r=eP(e.tenantId);if(!r)throw new D("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");let n=ow(e.runId);if(!n)throw new D("INVALID_ARGS","Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");this.cleanupExpiredLeases();let i=this.resolveLeaseTtlMs(e.ttlMs),a=this.bindingKey(r,n,t),s=this.runBindings.get(a);if(s){let e=this.leases.get(s);if(e)return this.refreshLease(e,i);this.runBindings.delete(a)}this.enforceCapacity(t);let l=this.now(),u={leaseId:o.randomBytes(16).toString("hex"),tenantId:r,runId:n,backend:t,createdAt:l,heartbeatAt:l,expiresAt:l+i};return this.leases.set(u.leaseId,u),this.runBindings.set(a,u.leaseId),{...u}}heartbeatLease(e){let t=og(e.leaseId);if(!t)throw new D("INVALID_ARGS","Invalid lease id.");this.cleanupExpiredLeases();let r=this.leases.get(t);if(!r)throw new D("UNAUTHORIZED","Lease is not active",{reason:"LEASE_NOT_FOUND"});this.assertOptionalScopeMatch(r,e.tenantId,e.runId);let n=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(r,n)}releaseLease(e){let t=og(e.leaseId);if(!t)throw new D("INVALID_ARGS","Invalid lease id.");this.cleanupExpiredLeases();let r=this.leases.get(t);return r?(this.assertOptionalScopeMatch(r,e.tenantId,e.runId),this.leases.delete(t),this.runBindings.delete(this.bindingKey(r.tenantId,r.runId,r.backend)),{released:!0}):{released:!1}}assertLeaseAdmission(e){let t=oy(e.backend),r=eP(e.tenantId);if(!r)throw new D("INVALID_ARGS","tenant isolation requires tenant id.");let n=ow(e.runId);if(!n)throw new D("INVALID_ARGS","tenant isolation requires run id.");let i=og(e.leaseId);if(!i)throw new D("INVALID_ARGS","tenant isolation requires lease id.");this.cleanupExpiredLeases();let a=this.leases.get(i);if(!a)throw new D("UNAUTHORIZED","Lease is not active",{reason:"LEASE_NOT_FOUND"});if(a.backend!==t||a.tenantId!==r||a.runId!==n)throw new D("UNAUTHORIZED","Lease does not match tenant/run scope",{reason:"LEASE_SCOPE_MISMATCH"})}listActiveLeases(){return this.cleanupExpiredLeases(),Array.from(this.leases.values()).map(e=>({...e}))}cleanupExpiredLeases(){let e=this.now();for(let t of this.leases.values())t.expiresAt>e||(this.leases.delete(t.leaseId),this.runBindings.delete(this.bindingKey(t.tenantId,t.runId,t.backend)))}enforceCapacity(e){if("ios-simulator"!==e||this.maxActiveSimulatorLeases<=0)return;let t=Array.from(this.leases.values()).filter(e=>"ios-simulator"===e.backend).length;if(!(t<this.maxActiveSimulatorLeases))throw new D("COMMAND_FAILED","No simulator lease capacity available",{reason:"LEASE_CAPACITY_EXCEEDED",activeLeases:t,maxActiveLeases:this.maxActiveSimulatorLeases,backend:e,hint:"Retry after releasing another simulator lease."})}resolveLeaseTtlMs(e){if(!Number.isInteger(e))return this.defaultLeaseTtlMs;let t=Number(e);if(t<this.minLeaseTtlMs||t>this.maxLeaseTtlMs)throw new D("INVALID_ARGS",`Lease ttlMs must be between ${this.minLeaseTtlMs} and ${this.maxLeaseTtlMs}.`);return t}refreshLease(e,t){let r=this.now(),n={...e,heartbeatAt:r,expiresAt:r+t};return this.leases.set(n.leaseId,n),this.runBindings.set(this.bindingKey(n.tenantId,n.runId,n.backend),n.leaseId),{...n}}bindingKey(e,t,r){return`${e}:${t}:${r}`}assertOptionalScopeMatch(e,t,r){let n=eP(t),i=ow(r);if(t&&!n)throw new D("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if(r&&!i)throw new D("INVALID_ARGS","Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if(n&&e.tenantId!==n||i&&e.runId!==i)throw new D("UNAUTHORIZED","Lease does not match tenant/run scope",{reason:"LEASE_SCOPE_MISMATCH"})}}function oI(){return{platform:"macos",id:"host-macos-local",name:c.hostname(),kind:"device",target:"desktop",booted:!0}}async function ob(){return[oI()]}let oA=/^(iphone|ipad|ipod|appletv)/i,oS=/\b(iphone|ipad|ipod)\b/i,ox=/^appletv/i,o_=["apple tv","appletv","tvos"],oN=/^==\s*(.+?)\s*==$/,oM=/^(?<name>.+?)\s+\[(?<id>[^[\]]+)\]\s*$/;function ok(e){return(e??"").trim().toLowerCase()}function oD(e){return ok(e.hardwareProperties?.platform)}function oO(e){return e.includes("tvos")}function oP(e){let t=ok(e);return o_.some(e=>t.includes(e))}function oR(e){return[e.name??"",e.deviceProperties?.name??"",e.deviceProperties?.deviceType??""]}function oC(e){return e.hardwareProperties?.productType??e.deviceProperties?.productType??""}async function oE(e={}){let t,r,n=Y(e.simulatorSetPath),i=e.target;try{t=await rU(rq(["list","devices","-j"],{simulatorSetPath:n}))}catch{return null}try{r=JSON.parse(t.stdout)}catch{return null}let a=oL(r,n),o=null,s=null,l=null;for(let e of a)i&&e.target!==i||(e.booted&&(o=o??e),"mobile"===e.target&&(s=s??e),l=l??e);return o??s??l}function oL(e,t){let r=[];for(let[n,i]of Object.entries(e.devices))if(function(e){let t=ok(e);return t.includes("ios")||t.includes("tvos")}(n))for(let e of i)e.isAvailable&&r.push({platform:"ios",id:e.udid,name:e.name,kind:"simulator",target:oO(ok(n))?"tv":"mobile",booted:"Booted"===e.state,...t?{simulatorSetPath:t}:{}});return r}function oT(e,t){let r=new Set(e.map(e=>e.id)),n=[...e];for(let e of t)r.has(e.id)||(r.add(e.id),n.push(e));return n}async function o$(){let e=null;try{e=f.join(c.tmpdir(),`agent-device-devicectl-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);let t=await rU(["devicectl","list","devices","--json-output",e],{allowFailure:!0,timeoutMs:8e3});if(0!==t.exitCode)return[];let r=await d.readFile(e,"utf8");return function(e){let t=[];for(let r of e.result?.devices??[]){if(!function(e){var t;let r=oD(e);return!!(r.includes("ios")||r.includes("tvos"))||(t=oC(e),!!oA.test(t.trim())||oR(e).some(oP))}(r))continue;let e=r.hardwareProperties?.udid??r.identifier??"",n=r.name??r.deviceProperties?.name??e;e&&t.push({platform:"ios",id:e,name:n,kind:"device",target:function(e){var t;return oO(oD(e))?"tv":(t=oC(e),ox.test(t.trim())||oR(e).some(oP))?"tv":"mobile"}(r),booted:!0})}return t}(JSON.parse(r))}catch{return[]}finally{e&&await d.rm(e,{force:!0}).catch(()=>{})}}async function oF(){try{let e=await rU(["xctrace","list","devices"],{allowFailure:!0});if(0!==e.exitCode)return[];return function(e){let t=[],r=null;for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e)continue;let i=oN.exec(e);if(i){r=i[1]?.trim()??null;continue}if("Devices"!==r)continue;let a=oM.exec(e),o=a?.groups?.id?.trim()??"",s=a?.groups?.name?.trim()??"";if(!o||!s)continue;let l=function(e){return oP(e)?"tv":oS.test(e.trim())?"mobile":null}(s);l&&t.push({platform:"ios",id:o,name:s,kind:"device",target:l,booted:!0})}return t}(e.stdout)}catch{return[]}}async function oU(e={}){if("darwin"!==process.platform)throw new D("UNSUPPORTED_PLATFORM","Apple tools are only available on macOS");if(!await rT().whichCommand("xcrun"))throw new D("TOOL_MISSING","xcrun not found in PATH");let t=Y(e.simulatorSetPath),r=await rU(rq(["list","devices","-j"],{simulatorSetPath:t})),n=[];try{let e=JSON.parse(r.stdout);n=oL(e,t)}catch(e){throw new D("COMMAND_FAILED","Failed to parse simctl devices JSON",void 0,e)}if(n.push(oI()),e.udid&&n.some(t=>"ios"===t.platform&&t.id===e.udid)||t)return n;let[i,a]=await Promise.all([o$(),oF()]);return n=oT(n,i),oT(n,a)}async function oV(){return"linux"!==process.platform?[]:[{platform:"linux",id:"local",name:p(),kind:"device",target:"desktop",booted:!0}]}let oG=new h,oq=new h;async function oB(e,t,r){var n,i;let a=await oj(e,t,r);if(n=t,i=a,!oH(n)&&(!n.platform||"apple"===n.platform||"ios"===n.platform)&&"desktop"!==n.target&&(!i||"device"===i.kind)){let e=await oE({simulatorSetPath:r.simulatorSetPath,target:t.target});if(e)return e}if(a)return a;throw new D("DEVICE_NOT_FOUND","No devices found",{selector:t})}async function oj(e,t,r){try{return await no(e,t,r)}catch(e){var n;if(n=e,!oH(t)&&n instanceof D&&"DEVICE_NOT_FOUND"===n.code)return;throw e}}function oH(e){return!!(e.udid||e.serial||e.deviceName)}async function oW(e){let t=e.platform,r=na({simulatorSetPath:Y(e.iosSimulatorDeviceSet),platform:t,target:e.target}),n=ep(e.androidDeviceAllowlist),i=function(e){let{flags:t,normalizedPlatform:r,iosSimulatorSetPath:n,androidSerialAllowlist:i}=e;return JSON.stringify({platform:r,target:t.target,device:t.device,udid:t.udid,serial:t.serial,iosSimulatorSetPath:n,androidSerialAllowlist:i?Array.from(i).sort():void 0})}({flags:e,normalizedPlatform:t,iosSimulatorSetPath:r,androidSerialAllowlist:n}),a={platform:t,target:e.target,cacheHit:!1};return await e_("resolve_target_device",async()=>{let o=function(e){let t=oG.getStore(),r=t?.get(e);if(r)return{...r}}(i);if(o)return a.cacheHit=!0,o;let s={platform:t,target:e.target,deviceName:e.device,udid:e.udid,serial:e.serial};if(s.target&&!s.platform)throw new D("INVALID_ARGS","Device target selector requires --platform. Use --platform ios|macos|android|linux|apple with --target mobile|tv|desktop.");let l=await oZ({...s,iosSimulatorSetPath:r,androidSerialAllowlist:n?Array.from(n).sort():void 0});if(l)return oQ(s)?o0(i,await oB(l,s,{simulatorSetPath:r})):o0(i,await no(l,s,{simulatorSetPath:r}));"android"===s.platform&&await er();let u=await oY({...s,iosSimulatorSetPath:r,androidSerialAllowlist:n?Array.from(n).sort():void 0});return oQ(s)?o0(i,await oB(u,s,{simulatorSetPath:r})):o0(i,await no(u,s,{simulatorSetPath:r}))},a)}async function oz(e){return oG.getStore()?await e():await oG.run(new Map,e)}async function oK(e,t){return e?await oq.run(e,t):await t()}async function oJ(e,t){return await oK(e,async()=>await oz(t))}async function oX(e){return await oZ(e)??await oY(e)}async function oZ(e){let t=oq.getStore();if(!t)return null;let r=await t(e);return null==r?null:r.map(e=>({...e}))}async function oY(e){if("macos"===e.platform||"apple"===e.platform&&"desktop"===e.target)return await ob();if("linux"===e.platform)return await oV();if("android"===e.platform)return await F({serialAllowlist:e.androidSerialAllowlist?new Set(e.androidSerialAllowlist):void 0});if(e.platform)return await oU({simulatorSetPath:e.iosSimulatorSetPath,udid:e.udid});let t=[];try{t.push(...await F({serialAllowlist:e.androidSerialAllowlist?new Set(e.androidSerialAllowlist):void 0}))}catch{}try{t.push(...await oU({simulatorSetPath:e.iosSimulatorSetPath,udid:e.udid}))}catch{}try{t.push(...await oV())}catch{}return t}function oQ(e){return!!e.platform&&"android"!==e.platform&&"linux"!==e.platform}function o0(e,t){return oG.getStore()?.set(e,{...t}),t}let o1={runCommand:R,whichCommand:E,desktop:o8(R,E),clipboard:o6(R,E),screenshot:o9(R,E)},o2=rM(o1,function(e={}){let t={...o1,...e};return{...t,desktop:e.desktop??o8(t.runCommand,t.whichCommand),clipboard:e.clipboard??o6(t.runCommand,t.whichCommand),screenshot:e.screenshot??o9(t.runCommand,t.whichCommand)}});function o3(e){return o2.resolve(e)}async function o5(e,t){return await o2.run(e,t)}async function o4(e,t,r){return await o3().runCommand(e,t,r)}function o8(e,t){return{async openTarget(r){if(r.includes("://")||r.startsWith("/"))return void await e("xdg-open",[r]);if(await t(r)){e(r,[],{allowFailure:!0}).catch(e=>{eN({level:"warn",phase:"linux_app_launch",data:{app:r,error:String(e)}})}),await e8(500);return}await e("xdg-open",[r],{allowFailure:!0})},async closeApp(r){await t("wmctrl")?await e("wmctrl",["-c",r],{allowFailure:!0}):await e("pkill",["-x",r],{allowFailure:!0})}}}function o6(e,t){return{async readText(){let r=st[await si(t,o7)];return(await e(r.cmd,r.args,r.options)).stdout},async writeText(r){let n=sr[await si(t,o7)](r);await e(n.cmd,n.args,n.options)}}}function o9(e,t){return{async capture(r){let n=sn[await si(t,se)](r);await e(n.cmd,n.args,n.options)}}}let o7={wayland:[{tool:"wl-clipboard",command:"wl-paste"}],x11:[{tool:"xclip",command:"xclip"},{tool:"xsel",command:"xsel"}],waylandError:"wl-paste (wl-clipboard) is required for clipboard access on Wayland. Install via your package manager.",x11Error:"xclip or xsel is required for clipboard access on X11. Install via your package manager."},se={wayland:[{tool:"grim",command:"grim"},{tool:"gnome-screenshot",command:"gnome-screenshot"}],x11:[{tool:"scrot",command:"scrot"},{tool:"import",command:"import"},{tool:"gnome-screenshot",command:"gnome-screenshot"}],waylandError:"grim or gnome-screenshot is required for screenshots on Wayland. Install via your package manager.",x11Error:"scrot, import (ImageMagick), or gnome-screenshot is required for screenshots on X11. Install via your package manager."},st={"wl-clipboard":{cmd:"wl-paste",args:["--no-newline"],options:{allowFailure:!0,timeoutMs:5e3}},xclip:{cmd:"xclip",args:["-selection","clipboard","-o"],options:{allowFailure:!0,timeoutMs:5e3}},xsel:{cmd:"xsel",args:["--clipboard","--output"],options:{allowFailure:!0,timeoutMs:5e3}}},sr={"wl-clipboard":e=>({cmd:"wl-copy",args:["--",e],options:{allowFailure:!1,timeoutMs:5e3}}),xclip:e=>({cmd:"xclip",args:["-selection","clipboard"],options:{allowFailure:!1,timeoutMs:5e3,stdin:e}}),xsel:e=>({cmd:"xsel",args:["--clipboard","--input"],options:{allowFailure:!1,timeoutMs:5e3,stdin:e}})},sn={grim:e=>({cmd:"grim",args:[e]}),scrot:e=>({cmd:"scrot",args:[e]}),import:e=>({cmd:"import",args:["-window","root",e]}),"gnome-screenshot":e=>({cmd:"gnome-screenshot",args:["-f",e]})};async function si(e,t){let r=process.env.WAYLAND_DISPLAY||"wayland"===process.env.XDG_SESSION_TYPE?"wayland":"x11";for(let n of t[r])if(await e(n.command))return n.tool;throw new D("TOOL_MISSING","wayland"===r?t.waylandError:t.x11Error)}async function sa(e,t){let r=["devicectl",...e],n=await rU(r,{allowFailure:!0,timeoutMs:2e4});if(0===n.exitCode)return;let i=String(n.stdout??""),a=String(n.stderr??"");throw new D("COMMAND_FAILED",`Failed to ${t.action}`,{cmd:"xcrun",args:r,exitCode:n.exitCode,stdout:i,stderr:a,deviceId:t.deviceId,hint:sd(i,a)??su})}async function so(e,t){var r;return r=function(e){let t=e?.result?.apps;if(!Array.isArray(t))return[];let r=[];for(let e of t){if(!e||"object"!=typeof e)continue;let t="string"==typeof e.bundleIdentifier?e.bundleIdentifier.trim():"";if(!t)continue;let n="string"==typeof e.name&&e.name.trim().length>0?e.name.trim():t,i="string"==typeof e.url&&e.url.trim().length>0?e.url.trim():void 0;r.push({bundleId:t,name:n,url:i})}return r}(await sl(e,{jsonPrefix:"agent-device-ios-apps",args:["devicectl","device","info","apps","--device",e.id,"--include-all-apps"],failureMessage:"Failed to list iOS apps",parseFailureMessage:"Failed to parse iOS apps list"})),"user-installed"===t?r.filter(e=>!e.bundleId.startsWith("com.apple.")):r}async function ss(e){return function(e){let t=e?.result?.runningProcesses;if(!Array.isArray(t))return[];let r=[];for(let e of t){if(!e||"object"!=typeof e)continue;let t="string"==typeof e.executable?e.executable.trim():"",n="number"==typeof e.processIdentifier&&Number.isFinite(e.processIdentifier)?e.processIdentifier:NaN;t&&Number.isFinite(n)&&r.push({executable:t,pid:n})}return r}(await sl(e,{jsonPrefix:"agent-device-ios-processes",args:["devicectl","device","info","processes","--device",e.id],failureMessage:"Failed to list iOS processes",parseFailureMessage:"Failed to parse iOS process list"}))}async function sl(e,t){let r=f.join(c.tmpdir(),`${t.jsonPrefix}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),n=[...t.args,"--json-output",r],i=await rU(n,{allowFailure:!0,timeoutMs:2e4});try{if(0!==i.exitCode){let r=String(i.stdout??""),a=String(i.stderr??"");throw new D("COMMAND_FAILED",t.failureMessage,{cmd:"xcrun",args:n,exitCode:i.exitCode,stdout:r,stderr:a,deviceId:e.id,hint:sd(r,a)??su})}return JSON.parse(await d.readFile(r,"utf8"))}catch(r){if(r instanceof D)throw r;throw new D("COMMAND_FAILED",t.parseFailureMessage,{deviceId:e.id,cause:String(r)})}finally{await d.unlink(r).catch(()=>{})}}let su="Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.";function sd(e,t){let r=`${e}
12
- ${t}`.toLowerCase();return r.includes("device is busy")&&r.includes("connecting")?"iOS device is still connecting. Keep it unlocked and connected by cable until it is fully available in Xcode Devices, then retry.":r.includes("coredeviceservice")&&r.includes("timed out")?"CoreDevice service timed out. Reconnect the device and retry; if it persists restart Xcode and the iOS device.":null}let sc=new Map;async function sp(e){var t;let r,n=(r="simulator"===(t=e).kind?t.simulatorSetPath??"":"",JSON.stringify([t.platform,t.kind,t.id,t.target??"",r])),i=sc.get(n);if(void 0!==i){if(i>Date.now())return;sc.delete(n)}if("ios"===e.platform){if("simulator"===e.kind){let{ensureBootedSimulator:t}=await Promise.resolve(rf);await t(e),sf(n);return}if("device"===e.kind){await sm(e.id),sf(n);return}}if("android"===e.platform){let{waitForAndroidBoot:t}=await import("../1769.js");await t(e.id),sf(n)}}function sf(e){sc.set(e,Date.now()+5e3)}async function sm(e){let t=f.join(c.tmpdir(),`agent-device-ready-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),r=Math.max(1,Math.ceil(15));try{let n=await rU(["devicectl","device","info","details","--device",e,"--json-output",t,"--timeout",String(r)],{allowFailure:!0,timeoutMs:18e3}),i=String(n.stdout??""),a=String(n.stderr??""),o=await sh(t);if(0===n.exitCode){if(!o.parsed)throw new D("COMMAND_FAILED","iOS device readiness probe failed",{kind:"probe_inconclusive",deviceId:e,stdout:i,stderr:a,hint:"CoreDevice returned success but readiness JSON output was missing or invalid. Retry; if it persists restart Xcode and the iOS device."});let t=o?.tunnelState?.toLowerCase();if("connecting"===t)throw new D("COMMAND_FAILED","iOS device is not ready for automation",{kind:"not_ready",deviceId:e,tunnelState:t,hint:"Device tunnel is still connecting. Keep the device unlocked and connected by cable until it is fully available in Xcode Devices, then retry."});return}throw new D("COMMAND_FAILED","iOS device is not ready for automation",{kind:"not_ready",deviceId:e,stdout:i,stderr:a,exitCode:n.exitCode,tunnelState:o?.tunnelState,hint:sw(i,a)})}catch(t){if(t instanceof D&&"COMMAND_FAILED"===t.code){if("not_ready"===("string"==typeof t.details?.kind?t.details.kind:""))throw t;let r=t.details??{},n=String(r.stdout??""),i=String(r.stderr??""),a=Number(r.timeoutMs??15e3),o=`CoreDevice did not respond within ${a}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;throw new D("COMMAND_FAILED","iOS device readiness probe failed",{deviceId:e,cause:t.message,timeoutMs:a,stdout:n,stderr:i,hint:n||i?sw(n,i):o},t)}throw new D("COMMAND_FAILED","iOS device readiness probe failed",{deviceId:e,hint:"Reconnect the device, keep it unlocked, and retry."},t instanceof Error?t:void 0)}finally{await d.rm(t,{force:!0}).catch(()=>{})}}async function sh(e){try{let t=await d.readFile(e,"utf8"),r=JSON.parse(t),n=function(e){let t=e?.result;if(!t||"object"!=typeof t)return{};let r=t.connectionProperties?.tunnelState,n=t.device?.connectionProperties?.tunnelState,i="string"==typeof r?r:"string"==typeof n?n:void 0;return i?{tunnelState:i}:{}}(r);return{parsed:!0,tunnelState:n.tunnelState}}catch{return{parsed:!1}}}function sw(e,t){let r=sd(e,t);return r||(`${e}
13
- ${t}`.toLowerCase().includes("timed out waiting for all destinations")?"Xcode destination did not become available in time. Keep device unlocked and retry.":su)}function sg(e){let t=e.direction,r="up"===t||"down"===t?e.referenceHeight:e.referenceWidth,n=function(e){if(void 0===e)return .6;if(!Number.isFinite(e)||e<=0)throw new D("INVALID_ARGS","scroll amount must be a positive number");return e}(e.amount),i=void 0!==e.pixels?function(e){if(!Number.isFinite(e)||e<=0)throw new D("INVALID_ARGS","scroll pixels must be a positive integer");return Math.max(1,Math.round(e))}(e.pixels):Math.round(r*n),a=Math.max(1,Math.round(.05*r)),o=Math.max(1,Math.min(i,Math.max(1,r-2*a))),s=Math.round(o/2),l=Math.round(e.referenceWidth/2),u=Math.round(e.referenceHeight/2),d=(r,n,i,a)=>({direction:t,x1:r,y1:n,x2:i,y2:a,referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:o});switch(t){case"up":return d(l,u-s,l,u+s);case"down":return d(l,u+s,l,u-s);case"left":return d(l-s,u,l+s,u);case"right":return d(l+s,u,l-s,u)}}function sy(e){if(0===e.length)return null;let t=[...e].sort((e,t)=>e-t);return t[Math.floor(t.length/2)]??null}function sv(e,t){let r=Math.max(24,Math.round(.2*Math.min(e.size,t.size))),n=Math.max(48,Math.round(.15*Math.min(e.crossSize,t.crossSize)));return Math.abs(e.size-t.size)<=r&&Math.abs(e.crossSize-t.crossSize)<=n}function sI(e,t){return{start:e.y-t.y,size:e.height,crossSize:e.width}}let sb=["device offline","device not found","transport error","connection reset","broken pipe","timed out","no such file or directory"];async function sA(e,t={}){let r=tt(e,t.helperAdb).exec;return(await s_(e,t,r)).xml}async function sS(e,t={}){let r=tt(e,t.helperAdb).exec,n=await s_(e,t,r),i=n.xml,a=!1!==t.includeHiddenContentHints;if(!t.interactiveOnly){let o=to(i,800,t);return a&&function(e,t){for(let[r,n]of e){let e=t[r];e&&(n.hiddenContentAbove&&(e.hiddenContentAbove=!0),n.hiddenContentBelow&&(e.hiddenContentBelow=!0))}}(await sE(e,o.nodes,i,r),o.nodes),{...o,androidSnapshot:n.metadata}}let o=tl(i),s=tm(o,800,t);a&&await sx({device:e,options:t,tree:o,xml:i,adb:r,interactiveSnapshot:s});let{sourceNodes:l,...u}=s;return{...u,androidSnapshot:n.metadata}}async function sx(e){if(sT(e.interactiveSnapshot.nodes).size>0||sL(e.xml))return;let t=tm(e.tree,800,{...e.options,interactiveOnly:!1}),r=await sE(e.device,t.nodes,e.xml,e.adb);sq(r,t,e.interactiveSnapshot),0===r.size&&sq(tI(tY(t.nodes)),t,e.interactiveSnapshot)}async function s_(e,t,r){let n=await e_("android_snapshot_helper_artifact_resolution",async()=>await sR(t.helperArtifact));return n.artifact?await sN(e,t,r,n.artifact):(eN({level:n.fallbackReason?"warn":"info",phase:"android_snapshot_helper_unavailable",data:{reason:n.fallbackReason??"artifact_not_found"}}),await sC(e,n.fallbackReason,r))}async function sN(e,t,r,n){var i,a,o,s;let l=(i=e,`${i.platform}:${i.id}`),u=tt(e,t.helperAdb);try{let e=await sM(t,r,u,n,l);return e.installed&&await th(l),a=await sk(t,r,u,n,l),o=n,s=e.reason,{xml:a.xml,metadata:{backend:"android-helper",helperVersion:o.manifest.version,helperApiVersion:a.metadata.helperApiVersion,helperTransport:a.metadata.transport,helperSessionReused:a.metadata.sessionReused,installReason:s,waitForIdleTimeoutMs:a.metadata.waitForIdleTimeoutMs,waitForIdleQuietMs:a.metadata.waitForIdleQuietMs,timeoutMs:a.metadata.timeoutMs,maxDepth:a.metadata.maxDepth,maxNodes:a.metadata.maxNodes,rootPresent:a.metadata.rootPresent,captureMode:a.metadata.captureMode,windowCount:a.metadata.windowCount,nodeCount:a.metadata.nodeCount,helperTruncated:a.metadata.truncated,elapsedMs:a.metadata.elapsedMs}}}catch(t){return await sD({error:t,helperDeviceKey:l,artifact:n,device:e,adb:r})}}async function sM(e,t,r,n,i){let a=await e_("android_snapshot_helper_install",async()=>await ts({adb:t,adbProvider:r,artifact:n,deviceKey:i,installPolicy:e.helperInstallPolicy,timeoutMs:3e4}),{packageName:n.manifest.packageName,versionCode:n.manifest.versionCode,installPolicy:e.helperInstallPolicy??"missing-or-outdated"});return eN({phase:"android_snapshot_helper_install_decision",data:{packageName:a.packageName,versionCode:a.versionCode,installedVersionCode:a.installedVersionCode,installed:a.installed,reason:a.reason}}),a}async function sk(e,t,r,n,i){let a={adb:t,adbProvider:r,deviceKey:i,helperVersion:n.manifest.version,helperVersionCode:n.manifest.versionCode,packageName:n.manifest.packageName,instrumentationRunner:n.manifest.instrumentationRunner,waitForIdleTimeoutMs:e.helperWaitForIdleTimeoutMs??25,timeoutMs:5e3,commandTimeoutMs:3e4};try{let e=await e_("android_snapshot_helper_session_capture",async()=>await td(a),{packageName:n.manifest.packageName,version:n.manifest.version,timeoutMs:5e3});if(e)return e}catch(e){eN({level:"warn",phase:"android_snapshot_helper_session_fallback",data:{reason:k(e).message}})}return await e_("android_snapshot_helper_capture",async()=>await tu(a),{packageName:n.manifest.packageName,version:n.manifest.version,timeoutMs:5e3,commandTimeoutMs:3e4})}async function sD(e){let t=function(e){var t;let r=k(e);if(!function(e,t){if(!e||"object"!=typeof e)return!1;let r="errorType"in e?String(e.errorType):"",n=sP(e)??t;return/TimeoutException/.test(r)||/timed out/i.test(n)}(r.details?.helper,r.message)&&(t=r,!(t.details?.exitCode===137&&/Android snapshot helper (failed before returning parseable output|output could not be parsed)/.test(t.message))))return;let n=sO(e);return new D(N(r.code),`${n}. Stock UIAutomator fallback was skipped because this usually means the Android accessibility tree is busy or stalled.`,{...r.details,hint:"Android accessibility snapshots can be blocked by busy or continuously changing app UI. Use screenshot as visual truth after this timeout and report the busy UI if it persists."},e)}(e.error);if(t)throw t;let r=sO(e.error);return eN({level:"warn",phase:"android_snapshot_helper_fallback",data:{reason:r}}),await th(e.helperDeviceKey),tf({deviceKey:e.helperDeviceKey,packageName:e.artifact.manifest.packageName,versionCode:e.artifact.manifest.versionCode}),await sC(e.device,r,e.adb)}function sO(e){let t=k(e),r=sP(t.details?.helper);if(r&&r!==t.message)return`${t.message}: ${r}`;if(r)return r;let n=("string"==typeof t.details?.stderr?t.details.stderr.trim():"").split(/\r?\n/).find(e=>e.trim());return n?`${t.message}: ${n}`:t.message}function sP(e){if(!e||"object"!=typeof e||!("message"in e))return;let t=String(e.message).trim();return t&&"null"!==t?t:void 0}async function sR(e){if(e)return{artifact:e};let t=eH(),r=f.join(eW(),"android-snapshot-helper","dist"),n=f.join(r,`agent-device-android-snapshot-helper-${t}.manifest.json`);try{await A.access(n)}catch{return{}}try{let e=tc(JSON.parse(await A.readFile(n,"utf8"))),t=f.join(r,e.assetName??`agent-device-android-snapshot-helper-${e.version}.apk`);return await A.access(t),{artifact:{apkPath:t,manifest:e}}}catch(e){return{fallbackReason:k(e).message}}}async function sC(e,t,r){let n;try{n=await e_("android_snapshot_stock_capture",async()=>await s$(e,r),{fallbackReason:t,timeoutMs:8e3})}catch(e){if(t){var i,a;let r;throw i=e,a=t,new D(N((r=k(i)).code),`${r.message} Android snapshot helper failed before stock fallback: ${a}`,{...r.details,androidSnapshotHelperFallbackReason:a,...r.hint?{hint:r.hint}:{}},i)}throw e}return{xml:n,metadata:{backend:"uiautomator-dump",...t?{fallbackReason:t}:{}}}}async function sE(e,t,r,n){if(!t.some(e=>ta(e.type)))return new Map;let i=sT(t);if(i.size>0||sL(r))return i;let a=await sG(e,n);return a?function(e,t){let r=function(e){let t={className:"root",rect:{x:0,y:0,width:0,height:0},children:[]},r=[{indent:-1,node:t}],n=/^(\s*)([\w.$]+)\{[^}]* (-?\d+),(-?\d+)-(-?\d+),(-?\d+) #/;for(let t of e.split("\n")){let e=n.exec(t);if(!e)continue;let[i,a,o,s,l,u]=e.slice(1);if(void 0===i||void 0===a||void 0===o||void 0===s||void 0===l||void 0===u)continue;let d=i.length,c=Number(o),p=Number(s),f={className:a,rect:{x:c,y:p,width:Math.max(0,Number(l)-c),height:Math.max(0,Number(u)-p)},children:[]};for(;r.length>1&&d<=r[r.length-1].indent;)r.pop();r[r.length-1].node.children.push(f),r.push({indent:d,node:f})}return t.children.length>0?t:null}(t);if(!r)return new Map;let n=function(e){let t=[],r=[e];for(;r.length>0;){let e=r.pop();if(ta(e.className)){let r=function(e){let t=e.children[0];if(!t)return null;let r=Math.max(t.rect.height,...t.children.map(e=>e.rect.y+e.rect.height)),n=t.children.filter(e=>e.rect.height>0).map(t=>sI(t.rect,e.rect)).sort((e,t)=>e.start-t.start);return 0===n.length?null:{rect:e.rect,contentExtent:r,contentBlocks:n}}(e);r&&t.push(r)}r.push(...e.children)}return t}(r);if(0===n.length)return new Map;let i=new Map;for(let t of e){if(!t.rect||!ta(t.type))continue;let r=function(e,t){let r=null,n=1/0;for(let i of t){let t=Math.abs(i.rect.width-e.width)+Math.abs(i.rect.height-e.height);if(t>32)continue;let a=4*t+(Math.abs(i.rect.x-e.x)+Math.abs(i.rect.y-e.y));a<n&&(r=i,n=a)}return r}(t.rect,n);if(!r)continue;let a=function(e,t){let r=function(e,t){let r=t,n=new Set;for(;!n.has(r.index);){var i,a;n.add(r.index);let o=e.filter(e=>e.parentIndex===r.index&&e.rect);if(1!==o.length)return r;let s=o[0];if(i=s.rect,a=t.rect,i.x!==a.x||i.y!==a.y||i.width!==a.width||i.height!==a.height)return r;r=s}return t}(e,t);return e.filter(e=>e.parentIndex===r.index&&e.rect).map(e=>e.rect).filter(e=>e.height>0).sort((e,t)=>e.y-t.y).map(e=>sI(e,t.rect))}(e,t),o=function(e){let{viewportRect:t,visibleBlocks:r,nativeScrollView:n}=e;if(0===r.length||0===n.contentBlocks.length)return null;let i=function(e){if(0===e.contentBlocks.length)return null;let t=e.contentBlocks[0],r=e.contentBlocks[e.contentBlocks.length-1];if(!t||!r)return null;let n=sy(e.contentBlocks.map(e=>e.size))??e.rect.height,i=Math.max(48,Math.round(.5*n)),a=Math.max(24,Math.round(.25*n)),o=t.start>=i,s=e.contentExtent-(r.start+r.size)>=a;return o||s?{above:o,below:s}:null}(n),a=function(e,t){let r=new Map;for(let n of e)for(let e of t){if(!sv(n,e))continue;let t=n.start-e.start,i=8*Math.round(t/8),a=r.get(i)??[];a.push(t),r.set(i,a)}let n=null;for(let e of r.values())(!n||e.length>n.length)&&(n=e);if(!n||n.length<2)return null;let i=[...n].sort((e,t)=>e-t);return i[Math.floor(i.length/2)]??null}(n.contentBlocks,r)??function(e){let{nativeBlocks:t,visibleBlocks:r,viewportExtent:n,contentExtent:i}=e,a=[],o=[];for(let e of t)for(let t of r){if(!sv(e,t))continue;let r=e.start-t.start;16>=Math.abs(r)&&a.push(r),16>=Math.abs(r+n-i)&&o.push(r)}return o.length>0?sy(o):a.length>0?sy(a):null}({nativeBlocks:n.contentBlocks,visibleBlocks:r,viewportExtent:t.height,contentExtent:n.contentExtent});if(null===a)return i;let o=t.height;return{above:(i?.above??!1)||a>16,below:(i?.below??!1)||a+o<n.contentExtent-16}}({viewportRect:t.rect,visibleBlocks:a,nativeScrollView:r});if(!o)continue;let s={};o.above&&(s.hiddenContentAbove=!0),o.below&&(s.hiddenContentBelow=!0),(s.hiddenContentAbove||s.hiddenContentBelow)&&i.set(t.index,s)}return i}(t,a):new Map}function sL(e){return e.includes(" can-scroll-forward=")||e.includes(" can-scroll-backward=")}function sT(e){let t=new Map;for(let r of e){let e={};r.hiddenContentAbove&&(e.hiddenContentAbove=!0),r.hiddenContentBelow&&(e.hiddenContentBelow=!0),(e.hiddenContentAbove||e.hiddenContentBelow)&&t.set(r.index,e)}return t}async function s$(e,t=tn(e)){try{return await $(()=>sF(t),{shouldRetry:sV})}catch(t){var r,n;let e;if((r=t)instanceof D&&"COMMAND_FAILED"===r.code&&"number"==typeof r.details?.timeoutMs&&r.details?.cmd==="adb"&&(e=Array.isArray(n=r.details?.args)?n.map(String):"string"==typeof n?n.split(/\s+/):[]).includes("uiautomator")&&e.includes("dump")){let e="Android accessibility snapshots can be blocked by busy or continuously changing app UI. Use screenshot as visual truth after this timeout. Stock Android UIAutomator may still time out on app-owned infinite animations.";throw new D("COMMAND_FAILED",`Android UI hierarchy dump timed out while waiting for the UI to become idle. ${e}`,{...t.details??{},hint:e},t)}throw t}}async function sF(e){var t,r;let n,i,a=await e(["exec-out","uiautomator","dump","/dev/tty"],{allowFailure:!0,timeoutMs:8e3}),o=sU(a.stdout,a.stderr);if(o)return o;let s="/sdcard/window_dump.xml",l=await e(["shell","uiautomator","dump",s],{allowFailure:!0,timeoutMs:8e3}),u=(t=l.stdout,r=l.stderr,n=`${t}
14
- ${r}`,i=/dumped to:\s*(\S+)/i.exec(n),i?.[1]);if(0!==l.exitCode&&!u)throw new D("COMMAND_FAILED","uiautomator dump did not return XML",{stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode,reason:"missing_fresh_dump"});let d=await e(["shell","cat",u??s]),c=sU(d.stdout,d.stderr);if(!c)throw new D("COMMAND_FAILED","uiautomator dump did not return XML",{stdout:d.stdout,stderr:d.stderr});return c}function sU(e,t){let r=`${e}
15
- ${t}`,n=r.indexOf("<?xml"),i=n>=0?n:r.indexOf("<hierarchy");if(i<0)return null;let a=r.lastIndexOf("</hierarchy>");if(a<0||a<i)return null;let o=r.slice(i,a+12).trim();return o.length>0?o:null}function sV(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details?.stderr,r=("string"==typeof t?t:"").toLowerCase();return sb.some(e=>r.includes(e))}async function sG(e,t=tn(e)){try{let e=await t(["shell","dumpsys","activity","top"],{allowFailure:!0,timeoutMs:8e3}),r=`${e.stdout}
16
- ${e.stderr}`.trim();return r.length>0?r:null}catch{return null}}function sq(e,t,r){if(0===e.size)return;let n=new Map;for(let[e,t]of r.sourceNodes.entries()){let i=r.nodes[e];i&&n.set(t,i)}for(let[r,i]of e){let e=t.sourceNodes[r];if(!e)continue;let a=n.get(e);a&&(i.hiddenContentAbove&&(a.hiddenContentAbove=!0),i.hiddenContentBelow&&(a.hiddenContentBelow=!0))}}function sB(e){var t;return!!e&&(!!e.password||!!(t=e.text)&&Array.from(t).every(sH))}function sj(e){if(!e)return null;let t=sB(e);return{...e,text:t?null:e.text,...t?{textRedacted:!0}:{}}}function sH(e){return"•"===e||"*"===e||"●"===e}async function sW(e,t,r,n){let i=null,a=null,o=await sZ(e);for(let s of[0,150,350]){s>0&&await e8(s);let l=await sK(e,t,r,n,o);if(i=l,"ime_capture"===l.reason)return l;a=l.ok?l:null}return a??i??{ok:!1,actual:null,reason:"text_mismatch",targetInput:null,actualInput:null}}async function sz(e,t,r){var n,i,a;return n=await sA(e),i=t,a=r,sJ(n,i,a).actualInput?.text??null}async function sK(e,t,r,n,i){return function(e,t,r,n,i={}){var a,o;let s,l=sJ(e,t,r,i);return!function(e){let{targetInput:t,actualInput:r}=e;return!!t&&!!r&&r!==t&&r.inputMethodOwned&&!t.inputMethodOwned}(l)?function(e,t){let r=e.actualInput;if(!r||!sB(r))return null;let n=r.text??null,i=Array.from(n??"").length,a=Array.from(t).length,o=null!==n&&i>0&&a>0&&i===a;return{ok:o,actual:n,reason:o?void 0:"masked_unverified",masked:!0,targetInput:e.targetInput,actualInput:r}}(l,n)??(a=l,o=n,{ok:function(e,t){if(e===t)return!0;let r=sX(e),n=sX(t);return!!r&&!!n&&!!(r===n||function(e,t){if(e.length!==t.length||0===e.length||e.slice(1)!==t.slice(1))return!1;let r=e[0],n=t[0];return!!r&&!!n&&n.toLowerCase()===n&&r===n.toUpperCase()}(r,n))}(s=a.actualInput?.text??null,o),actual:s,reason:"text_mismatch",targetInput:a.targetInput,actualInput:a.actualInput}):{ok:!1,actual:l.actualInput?.text??null,reason:"ime_capture",targetInput:l.targetInput,actualInput:l.actualInput}}(await sA(e),t,r,n,i)}function sJ(e,t,r,n={}){var i;let a,o={focusedEdit:null,editAtPoint:null,anyAtPoint:null};for(let i of tp(e)){let e=function(e,t){if(!e.rect)return null;let r=e.text??"",n=Math.max(1,e.rect.width*e.rect.height);return{text:r||null,className:e.className,resourceId:e.resourceId,packageName:e.packageName,rect:e.rect,focused:e.focused??!1,password:!0===e.password,inputMethodOwned:ed({packageName:e.packageName,resourceId:e.resourceId,activeInputMethodPackage:t.activeInputMethodPackage}),area:n,editText:function(e){let t=e.toLowerCase();return t.includes("edittext")||t.includes("textfield")}(e.className??"")}}(i,n);e&&function(e,t,r,n){var i,a,o;let s=(i=t.rect,a=r,o=n,a>=i.x&&a<=i.x+i.width&&o>=i.y&&o<=i.y+i.height);if(s&&t.editText&&(e.editAtPoint=sY(e.editAtPoint,t)),t.focused&&t.editText){e.focusedEdit=sY(e.focusedEdit,t);return}s&&t.text&&(e.anyAtPoint=sY(e.anyAtPoint,t))}(o,e,t,r)}return{targetInput:a=(i=o).editAtPoint??i.anyAtPoint,actualInput:(i.focusedEdit?.text?i.focusedEdit:null)??a}}function sX(e){return(e??"").replace(/\s+/g," ").trim()}async function sZ(e){try{return{activeInputMethodPackage:(await ea(e)).inputMethodPackage}}catch(e){return eN({level:"warn",phase:"android_fill_verification_input_method_probe_failed",data:{error:e instanceof Error?e.message:String(e)}}),{}}}function sY(e,t){return e&&e.area<t.area?e:t}async function sQ(e,t,r){await Z(e,["shell","input","tap",String(t),String(r)])}async function s0(e,t,r,n,i,a=250){await Z(e,["shell","input","swipe",String(t),String(r),String(n),String(i),String(a)])}async function s1(e){await Z(e,["shell","input","keyevent","4"])}async function s2(e){await Z(e,["shell","input","keyevent","3"])}async function s3(e){await Z(e,["shell","input","keyevent","ENTER"])}async function s5(e,t){let r=function(e){switch(e){case"portrait":return"0";case"landscape-left":return"1";case"portrait-upside-down":return"2";case"landscape-right":return"3";default:throw new D("INVALID_ARGS",`Unsupported Android rotation: ${e}`)}}(t);await Z(e,["shell","settings","put","system","accelerometer_rotation","0"]),await Z(e,["shell","settings","put","system","user_rotation",r])}async function s4(e){await Z(e,["shell","input","keyevent","187"])}async function s8(e,t,r,n=800){await Z(e,["shell","input","swipe",String(t),String(r),String(t),String(r),String(n)])}async function s6(e,t,r=0){let n=te(e);if(n){await n({action:"type",text:t,delayMs:r}),ld("type","provider-native",t);return}(ll(t),await lr(e,"type"),r>0&&Array.from(t).length>1)?await lo(e,{action:"type",text:t,chunkSize:1,delayMs:r}):await lo(e,{action:"type",text:t,chunkSize:la,delayMs:0})}async function s9(e,t,r){await sQ(e,t,r)}async function s7(e,t,r,n,i=0){let a=te(e);if(a){await a({action:"fill",target:{x:t,y:r},text:n,delayMs:i}),ld("fill","provider-native",n);let o=await sW(e,t,r,n);if(o.ok)return;le(n,o)}ll(n);let o=Array.from(n).length,s=null;for(let a of[{clearPadding:12,minClear:8,maxClear:48,chunkSize:i>0?1:la,inputDelayMs:i},{clearPadding:24,minClear:16,maxClear:96,chunkSize:i>0?1:4,inputDelayMs:i>0?i:15}]){var l,u;await s9(e,t,r),await lr(e,"fill");let i=(l=o+a.clearPadding,u=a.minClear,Math.max(u,Math.min(a.maxClear,l)));await lc(e,i),await lo(e,{action:"fill",text:n,chunkSize:a.chunkSize,delayMs:a.inputDelayMs});let d=await sW(e,t,r,n);if(s=d,d.ok)return;"ime_capture"===d.reason&&le(n,d)}le(n,s)}function le(e,t){let r;throw new D("COMMAND_FAILED",t?.reason==="ime_capture"?"Android fill input was captured by the active keyboard instead of the app field":t?.reason==="masked_unverified"?"Android fill verification could not confirm masked text value":"Android fill verification failed",(r=function(e,t){var r;if(!t)return{expected:e,actual:null,failureReason:"text_mismatch",targetInput:null,actualInput:null};let n=!0===(r=t).masked||sB(r.targetInput)||sB(r.actualInput),i={failureReason:t.reason??"text_mismatch",targetInput:sj(t.targetInput),actualInput:sj(t.actualInput)};return n?{...i,expectedLength:Array.from(e).length,actual:null,masked:!0,actualLength:Array.from(t.actual??"").length}:{...i,expected:e,actual:t.actual}}(e,t),t?.reason==="ime_capture"&&(r.hint="The focused input belongs to the Android keyboard/IME, not the app field. Disable handwriting/stylus input or switch to a standard IME, then retry fill."),r))}async function lt(e,t,r){let n=await li(e),i=sg({direction:t,amount:r?.amount,pixels:r?.pixels,referenceWidth:n.width,referenceHeight:n.height});return await Z(e,["shell","input","swipe",String(i.x1),String(i.y1),String(i.x2),String(i.y2),"300"]),i}async function lr(e,t){let r;try{r=await ea(e)}catch(e){eN({level:"warn",phase:"android_input_ownership_probe_failed",data:{action:t,error:e instanceof Error?e.message:String(e)}});return}if("ime"===r.inputOwner)throw new D("COMMAND_FAILED","KEYBOARD_OVERLAY_BLOCKING: Android text input is blocked because the focused input belongs to the active keyboard/IME.",{failureReason:"ime_capture",action:t,inputOwner:r.inputOwner,inputType:r.inputType,type:r.type,inputMethodPackage:r.inputMethodPackage,focusedPackage:r.focusedPackage,focusedResourceId:r.focusedResourceId,nextAction:"Focused input appears to be owned by the keyboard/IME; dismiss or change the IME before retrying text entry."})}async function ln(e){let t=(await Z(e,["shell","wm","size"])).stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(!t)throw new D("COMMAND_FAILED","Unable to read screen size");return{width:Number(t[1]),height:Number(t[2])}}async function li(e){try{let t=await sA(e),r=function(e){let t=null;for(let r of tp(e)){let e=r.rect;if(!e||e.width<=0||e.height<=0)continue;let n=e.width*e.height;(!t||n>t.area)&&(t={width:e.x+e.width,height:e.y+e.height,area:n})}return t?{width:t.width,height:t.height}:null}(t);if(r)return r}catch(e){eN({level:"warn",phase:"android_gesture_viewport_probe_failed",data:{error:e instanceof Error?e.message:String(e)}})}return await ln(e)}let la=8;async function lo(e,t){let r=t.text.split("\n");for(let[n,i]of r.entries()){let a=function(e,t){let r=Math.max(1,Math.floor(t)),n=[],i=Array.from(e);for(let e=0;e<i.length;e+=r)n.push(i.slice(e,e+r).join(""));return n.length>0?n:[""]}(i,t.chunkSize);for(let[i,o]of a.entries())await ls(e,o),t.delayMs>0&&(i+1<a.length||n+1<r.length)&&await e8(t.delayMs);n+1<r.length&&await Z(e,["shell","input","keyevent","ENTER"])}ld(t.action,"adb-shell",t.text)}async function ls(e,t){if(t)try{await Z(e,["shell","input","text",t.replace(/ /g,"%s")])}catch(e){if(function(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details?.stderr,r=("string"==typeof t?t:"").toLowerCase();return!!(r.includes("exception occurred while executing 'text'")||r.includes("nullpointerexception")&&r.includes("inputshellcommand.sendtext"))}(e))throw lu(t,e);throw e}}function ll(e){if(!function(e){for(let t of e){let e=t.codePointAt(0);if(void 0!==e&&"\n"!==t&&(e<32||e>126))return!1}return!0}(e))throw lu(e)}function lu(e,t){return new D("COMMAND_FAILED","Android text input requires provider-native text injection for non-ASCII/control characters; the current adb-shell fallback supports ASCII text only.",{backend:"adb-shell",textLength:Array.from(e).length,textPreview:e.slice(0,32)},t instanceof Error?t:void 0)}function ld(e,t,r){eN({phase:"android_text_injection",data:{action:e,backend:t,textLength:Array.from(r).length}})}async function lc(e,t){let r=Math.max(0,t);await Z(e,["shell","input","keyevent","KEYCODE_MOVE_END"],{allowFailure:!0});for(let t=0;t<r;t+=24){let n=Math.min(24,r-t);await Z(e,["shell","input","keyevent",...Array(n).fill("KEYCODE_DEL")],{allowFailure:!0})}}async function lp(e,t,r){let n="string"==typeof r.action&&r.action.trim()?r.action.trim():`${t}.TEST_PUSH`,i=["shell","am","broadcast","-a",n,"-p",t],a="string"==typeof r.receiver?r.receiver.trim():"";a&&i.push("-n",a);let o=r.extras;if(void 0!==o&&("object"!=typeof o||null===o||Array.isArray(o)))throw new D("INVALID_ARGS","Android push payload extras must be an object");let s=0;for(let[e,t]of Object.entries(o??{}))e&&(function(e,t,r){if("string"==typeof r)return e.push("--es",t,r);if("boolean"==typeof r)return e.push("--ez",t,r?"true":"false");if("number"==typeof r&&Number.isFinite(r))return Number.isInteger(r)?e.push("--ei",t,String(r)):e.push("--ef",t,String(r));throw new D("INVALID_ARGS",`Unsupported Android broadcast extra type for "${t}". Use string, boolean, or number.`)}(i,e,t),s+=1);return await Z(e,i),{action:n,extrasCount:s}}let lf="android-multitouch-helper-v1",lm="ANDROID_MULTITOUCH_HELPER_NO_FINAL_RESULT",lh="ANDROID_MULTITOUCH_HELPER_REPORTED_FAILURE";async function lw(e,t){if(!Number.isFinite(t.scale)||t.scale<=0)throw new D("INVALID_ARGS","gesture pinch requires scale > 0");let r=await lv(e,t.x,t.y);return await lI(e,{kind:"pinch",x:r.x,y:r.y,scale:t.scale,durationMs:t.durationMs})}async function lg(e,t){if(!Number.isFinite(t.degrees))throw new D("INVALID_ARGS","gesture rotate requires finite degrees");if(void 0!==t.velocity&&(!Number.isFinite(t.velocity)||0===t.velocity))throw new D("INVALID_ARGS","gesture rotate velocity must be a non-zero number");let r=await lv(e,t.x,t.y),n=t.degrees;return await lI(e,{kind:"rotate",x:r.x,y:r.y,degrees:n,durationMs:t.durationMs})}async function ly(e,t){if(!Number.isFinite(t.scale)||t.scale<=0)throw new D("INVALID_ARGS","gesture transform requires scale > 0");if(!Number.isFinite(t.degrees))throw new D("INVALID_ARGS","gesture transform requires finite degrees");if(![t.x,t.y,t.dx,t.dy].every(Number.isFinite))throw new D("INVALID_ARGS","gesture transform requires finite x y dx dy");return await lI(e,{kind:"transform",x:t.x,y:t.y,dx:t.dx,dy:t.dy,scale:t.scale,degrees:t.degrees,durationMs:t.durationMs})}async function lv(e,t,r){if(void 0!==t&&void 0!==r)return{x:t,y:r};let n=await ln(e);return{x:Math.round(n.width/2),y:Math.round(n.height/2)}}async function lI(e,t){let r=tr(e);if(r)return{backend:"provider-native-touch",...await r(t)??{}};let n=tn(e),i=await lS(),a=tt(e),o=await e_("android_multitouch_helper_install",async()=>{var t;return await lx({adb:n,adbProvider:a,artifact:i,deviceKey:(t=e,`${t.platform}:${t.id}`)})},{packageName:i.manifest.packageName,versionCode:i.manifest.versionCode});eN({phase:"android_multitouch_helper_install_decision",data:o});let s=await e_("android_multitouch_helper_gesture",async()=>await lb({adb:n,request:function(e){var t;let r=Math.round(void 0!==(t=e).durationMs?t.durationMs:"pinch"===t.kind?300:Math.min(Math.max(300,16*Math.ceil(Math.abs(t.degrees)/3)),2400));switch(e.kind){case"pinch":return{kind:"pinch",x:Math.round(e.x),y:Math.round(e.y),scale:e.scale,radius:160,durationMs:r};case"rotate":return{kind:"rotate",x:Math.round(e.x),y:Math.round(e.y),degrees:e.degrees,radius:160,durationMs:r};case"transform":return{kind:"transform",x:Math.round(e.x),y:Math.round(e.y),dx:Math.round(e.dx),dy:Math.round(e.dy),scale:e.scale,degrees:e.degrees,durationMs:r}}}(t),packageName:i.manifest.packageName,instrumentationRunner:i.manifest.instrumentationRunner}),{packageName:i.manifest.packageName,version:i.manifest.version});return{backend:"android-multitouch-helper",helperVersion:i.manifest.version,installReason:o.reason,...s}}async function lb(e){let t,r=Buffer.from(JSON.stringify({protocol:lf,...e.request})).toString("base64"),n=await e.adb(["shell","am","instrument","-w","-e","payloadBase64",r,e.instrumentationRunner],{allowFailure:!0,timeoutMs:45e3});try{t=function(e){let t=(function(e){let t=[],r=null;for(let n of e.split(/\r?\n/))n.startsWith("INSTRUMENTATION_RESULT: ")?(r??={},function(e,t){let r=e.indexOf("=");r>=0&&(t[e.slice(0,r)]=e.slice(r+1))}(n.slice(24),r)):n.startsWith("INSTRUMENTATION_CODE: ")&&r&&(t.push(r),r=null);return r&&t.push(r),t})(e).find(e=>e.agentDeviceProtocol===lf);if(!t)throw new D(lm,"Android multi-touch helper did not return a final result");if("true"!==t.ok){var r;throw new D(lh,(r=t).message&&"null"!==r.message?r.message:r.errorType||"Android multi-touch helper returned an error",{errorType:t.errorType,helper:t})}return{kind:t.kind,helperApiVersion:t.helperApiVersion,injectedEvents:lA(t.injectedEvents),elapsedMs:lA(t.elapsedMs)}}(`${n.stdout}
17
- ${n.stderr}`)}catch(e){if(e instanceof D){if(e.code===lh)throw new D("COMMAND_FAILED",e.message,e.details,e);if(e.code!==lm)throw e}throw new D("COMMAND_FAILED",0===n.exitCode?"Android multi-touch helper output could not be parsed":"Android multi-touch helper failed before returning parseable output",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode},e)}if(0!==n.exitCode)throw new D("COMMAND_FAILED","Android multi-touch helper failed",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,helper:t});return t}function lA(e){if(void 0===e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}async function lS(){let e=eH(),t=f.join(eW(),"android-multitouch-helper","dist"),r=f.join(t,`agent-device-android-multitouch-helper-${e}.manifest.json`);try{let e=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new D("INVALID_ARGS","Android multi-touch helper manifest must be an object.");return{name:lO(e.name,"name","android-multitouch-helper"),version:lD(e.version,"version"),assetName:lD(e.assetName,"assetName"),sha256:function(e){let t=lD(e,"sha256").trim().toLowerCase();if(64!==t.length||!/^[0-9a-f]+$/.test(t))throw new D("INVALID_ARGS","Android multi-touch helper manifest sha256 must be a 64-character hex string.");return t}(e.sha256),packageName:lO(e.packageName,"packageName","com.callstack.agentdevice.multitouchhelper"),versionCode:function(e,t){if(!Number.isInteger(e))throw new D("INVALID_ARGS",`Android multi-touch helper manifest ${t} must be an integer.`);return e}(e.versionCode,"versionCode"),instrumentationRunner:lO(e.instrumentationRunner,"instrumentationRunner","com.callstack.agentdevice.multitouchhelper/.MultiTouchInstrumentation"),statusProtocol:lO(e.statusProtocol,"statusProtocol",lf)}}(JSON.parse(await A.readFile(r,"utf8"))),n=f.join(t,e.assetName);return await A.access(n),{apkPath:n,manifest:e}}catch(e){throw new D("UNSUPPORTED_OPERATION","gesture pinch/rotate/transform on Android requires the bundled Android multi-touch helper artifact, but it was not found or could not be read",{manifestPath:r,error:k(e).message},e)}}async function lx(e){let{adb:t,artifact:r}=e,n=r.manifest.packageName,i=r.manifest.versionCode,a=`${e.deviceKey}\0${n}\0${i}`;if(l_.has(a))return{packageName:n,versionCode:i,installed:!1,reason:"current"};let o=await lN(t,n);if(void 0!==o&&o>=i)return l_.add(a),{packageName:n,versionCode:i,installedVersionCode:o,installed:!1,reason:"current"};await lM(r);let s=await ti(r.apkPath,{provider:e.adbProvider,replace:!0,allowTestPackages:!0,allowFailure:!0,timeoutMs:3e4});if(0!==s.exitCode)throw new D("COMMAND_FAILED","Failed to install Android multi-touch helper",{packageName:n,versionCode:i,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode});return l_.add(a),{packageName:n,versionCode:i,installedVersionCode:o,installed:!0,reason:void 0===o?"missing":"outdated"}}let l_=new Set;async function lN(e,t){let r=await e(["shell","cmd","package","list","packages","--show-versioncode",t],{allowFailure:!0,timeoutMs:5e3});if(0!==r.exitCode)return;let n=RegExp(`package:${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$).*versionCode:(\\d+)`).exec(`${r.stdout}
18
- ${r.stderr}`);return n?Number(n[1]):void 0}async function lM(e){let t=await lk(e.apkPath);if(t!==e.manifest.sha256)throw new D("COMMAND_FAILED","Android multi-touch helper APK checksum mismatch",{apkPath:e.apkPath,expectedSha256:e.manifest.sha256,actualSha256:t})}async function lk(e){let t=o.createHash("sha256");return t.update(await A.readFile(e)),t.digest("hex")}function lD(e,t){if("string"!=typeof e||0===e.length)throw new D("INVALID_ARGS",`Android multi-touch helper manifest ${t} is required.`);return e}function lO(e,t,r){if(e!==r)throw new D("INVALID_ARGS",`Android multi-touch helper manifest ${t} must be "${r}".`);return r}function lP(e){return e.map(e=>({args:e.args.join(" "),exitCode:e.exitCode,stderr:e.stderr.slice(0,400)}))}let lR=["camera","microphone","photos","contacts","contacts-limited","notifications","calendar","location","location-always","media-library","motion","reminders","siri"];function lC(e){let t=e.trim().toLowerCase();if("grant"===t)return"grant";if("deny"===t)return"deny";if("reset"===t)return"reset";throw new D("INVALID_ARGS",`Invalid permission action: ${e}. Use grant|deny|reset.`)}function lE(e){let t=e?.trim().toLowerCase();if("camera"===t||"microphone"===t||"photos"===t||"contacts"===t||"contacts-limited"===t||"notifications"===t||"calendar"===t||"location"===t||"location-always"===t||"media-library"===t||"motion"===t||"reminders"===t||"siri"===t)return t;throw new D("INVALID_ARGS",`permission setting requires a target: ${lR.join("|")}`)}function lL(e){let t=e.trim().toLowerCase();if("light"===t)return"light";if("dark"===t)return"dark";if("toggle"===t)return"toggle";throw new D("INVALID_ARGS",`Invalid appearance state: ${e}. Use light|dark|toggle.`)}function lT(e){let t=e.toLowerCase();if("on"===t||"true"===t||"1"===t)return!0;if("off"===t||"false"===t||"0"===t)return!1;throw new D("INVALID_ARGS",`Invalid setting state: ${e}`)}let l$=["window_animation_scale","transition_animation_scale","animator_duration_scale"];async function lF(e,t,r,n,i){switch(t.toLowerCase()){case"wifi":{let t=lT(r);await Z(e,["shell","svc","wifi",t?"enable":"disable"]);return}case"airplane":{let t=lT(r);await Z(e,["shell","settings","put","global","airplane_mode_on",t?"1":"0"]),await Z(e,["shell","am","broadcast","-a","android.intent.action.AIRPLANE_MODE","--ez","state",t?"true":"false"]);return}case"location":{if("set"===r.toLowerCase()){if("emulator"!==e.kind)throw new D("UNSUPPORTED_OPERATION","Android precise location coordinates are supported only on emulators.",{deviceId:e.id,hint:"Use an Android emulator for adb emu geo fix, or configure location through device/provider tooling."});let{latitude:t,longitude:r}=ez(i);return await Z(e,["emu","geo","fix",String(r),String(t)]),{latitude:t,longitude:r}}let t=lT(r);await Z(e,["shell","settings","put","secure","location_mode",t?"3":"0"]);return}case"animations":{let t=lT(r)?"1":"0";for(let r of l$)await Z(e,["shell","settings","put","global",r,t]);return{scale:t,keys:[...l$]}}case"appearance":{let t=await lV(e,r);await Z(e,["shell","cmd","uimode","night","dark"===t?"yes":"no"]);return}case"fingerprint":{let t=function(e){let t=e.trim().toLowerCase();if("match"===t)return"match";if("nonmatch"===t)return"nonmatch";throw new D("INVALID_ARGS",`Invalid fingerprint state: ${e}. Use match|nonmatch.`)}(r);await lU(e,t);return}case"permission":{if(!n)throw new D("INVALID_ARGS","permission setting requires an active app in session");let t=lC(r),a=function(e,t){let r=lE(e);if(t?.trim())throw new D("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===r)return{kind:"pm",value:"android.permission.CAMERA",type:"camera"};if("microphone"===r)return{kind:"pm",value:"android.permission.RECORD_AUDIO",type:"microphone"};if("photos"===r)return{kind:"pm",value:"android.permission.READ_MEDIA_IMAGES",type:"photos"};if("contacts"===r)return{kind:"pm",value:"android.permission.READ_CONTACTS",type:"contacts"};if("notifications"===r)return{kind:"notifications",appOps:"POST_NOTIFICATION",permission:"android.permission.POST_NOTIFICATIONS"};throw new D("INVALID_ARGS",`Unsupported permission target on Android: ${e}. Use camera|microphone|photos|contacts|notifications.`)}(i?.permissionTarget,i?.permissionMode);if("notifications"===a.kind)return void await lq(e,n,t,a);let o="grant"===t?"grant":"revoke";if("photos"===a.type)return void await lG(e,n,o);await Z(e,["shell","pm",o,n,a.value]);return}default:throw new D("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function lU(e,t){var r;let n,i,a=(r=e,i=[["shell","cmd","fingerprint","touch",n="match"===t?"1":"9999"],["shell","cmd","fingerprint","finger",n]],"emulator"===r.kind&&i.push(["emu","finger","touch",n]),i),o=[];for(let t of a){let r=await Z(e,t,{allowFailure:!0});if(0===r.exitCode)return;o.push({args:t,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}let s=lP(o);if(o.length>0&&o.every(e=>{var t,r;let n;return t=e.stdout,r=e.stderr,(n=`${t}
19
- ${r}`.toLowerCase()).includes("unknown command")||n.includes("can't find service: fingerprint")||n.includes("service fingerprint was not found")||n.includes("fingerprint cmd unavailable")||n.includes("emu command is not supported")||n.includes("emulator console is not running")||n.includes("fingerprint")&&n.includes("not found")}))throw new D("UNSUPPORTED_OPERATION","Android fingerprint simulation is not supported on this target/runtime.",{deviceId:e.id,action:t,hint:"Use an Android emulator with biometric support, or a device/runtime that exposes cmd fingerprint.",attempts:s});throw new D("COMMAND_FAILED","Failed to simulate Android fingerprint.",{deviceId:e.id,action:t,attempts:s})}async function lV(e,t){let r=lL(t);if("toggle"!==r)return r;let n=await Z(e,["shell","cmd","uimode","night"],{allowFailure:!0});if(0!==n.exitCode)throw new D("COMMAND_FAILED","Failed to read current Android appearance",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});let i=function(e,t){let r=/night mode:\s*(yes|no|auto)\b/i.exec(`${e}
20
- ${t}`);if(!r)return null;let n=r[1]?.toLowerCase();return"yes"===n?"dark":"no"===n?"light":"auto"===n?"auto":null}(n.stdout,n.stderr);if(!i)throw new D("COMMAND_FAILED","Unable to determine current Android appearance for toggle",{stdout:n.stdout,stderr:n.stderr});return"auto"===i?"dark":"dark"===i?"light":"dark"}async function lG(e,t,r){let n=await lB(e),i=[];for(let a of null!==n&&n>=33?["android.permission.READ_MEDIA_IMAGES","android.permission.READ_EXTERNAL_STORAGE"]:["android.permission.READ_EXTERNAL_STORAGE","android.permission.READ_MEDIA_IMAGES"]){let n=await Z(e,["shell","pm",r,t,a],{allowFailure:!0});if(0===n.exitCode)return;i.push({permission:a,stderr:n.stderr,exitCode:n.exitCode})}throw new D("COMMAND_FAILED",`Failed to ${r} Android photos permission`,{appPackage:t,sdkInt:n,attempts:i})}async function lq(e,t,r,n){"grant"===r?await Z(e,["shell","pm","grant",t,n.permission],{allowFailure:!0}):(await Z(e,["shell","pm","revoke",t,n.permission],{allowFailure:!0}),"reset"===r&&(await Z(e,["shell","pm","clear-permission-flags",t,n.permission,"user-set"],{allowFailure:!0}),await Z(e,["shell","pm","clear-permission-flags",t,n.permission,"user-fixed"],{allowFailure:!0}))),await Z(e,["shell","appops","set",t,n.appOps,"grant"===r?"allow":"deny"===r?"deny":"default"])}async function lB(e){let t=await Z(e,["shell","getprop","ro.build.version.sdk"],{allowFailure:!0});if(0!==t.exitCode)return null;let r=Number.parseInt(t.stdout.trim(),10);return!Number.isFinite(r)||r<=0?null:r}let lj=Buffer.from([137,80,78,71,13,10,26,10]);async function lH(e,t,r={}){if(!1===r.stabilize)return void await lK(e,t);await lW(e);try{await e8(1e3),await lK(e,t)}finally{await lz(e).catch(()=>{})}}async function lW(e){let t=t=>Z(e,["shell",t],{allowFailure:!0});await t("settings put global sysui_demo_allowed 1");let r=e=>t(`am broadcast -a com.android.systemui.demo -e command ${e}`);await r("clock -e hhmm 0941"),await r("notifications -e visible false")}async function lz(e){await Z(e,["shell","am broadcast -a com.android.systemui.demo -e command exit"],{allowFailure:!0})}async function lK(e,t){let r=await Z(e,["exec-out","screencap","-p"],{binaryStdout:!0});if(!r.stdoutBuffer)throw new D("COMMAND_FAILED","Failed to capture screenshot");let n=r.stdoutBuffer.indexOf(lj);if(n<0)throw new D("COMMAND_FAILED","Screenshot data does not contain a valid PNG header");let i=function(e,t){let r=t+lj.length;for(;r+8<=e.length;){let t=e.readUInt32BE(r),n=r+4,i=e.toString("ascii",n,n+4),a=r+12+t;if(a>e.length)break;if("IEND"===i)return a;r=a}return null}(r.stdoutBuffer,n);if(!i)throw new D("COMMAND_FAILED","Screenshot data does not contain a complete PNG payload");await d.writeFile(t,r.stdoutBuffer.subarray(n,i))}let lJ="--launch-console is supported only for iOS simulator app launches",lX="--launch-console requires a direct app launch and cannot be used with URL opens";function lZ(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{};if(4!==t.exitCode)return!1;let r=String(t.stderr??"").toLowerCase();return r.includes("fbsopenapplicationserviceerrordomain")&&r.includes("the request to open")}async function lY(e,t){let r=await rU(rB(e,["get_app_container",e.id,t]),{allowFailure:!0});if(0!==r.exitCode)return{installed:!1};let n=r.stdout.trim();if(!n)return{installed:!1};let i=await rF("plutil",["-extract","CFBundleExecutable","raw","-o","-",`${n}/Info.plist`],{allowFailure:!0});if(0!==i.exitCode||!i.stdout.trim())return{installed:!0};let a=i.stdout.trim(),o=`${n}/${a}`,s=await rF("otool",["-l",o],{allowFailure:!0});if(0!==s.exitCode)return{installed:!0};let l=s.stdout.toLowerCase();return{installed:!0,simulatorCompatible:l.includes("iossimulator")||l.includes("platform 7")}}function lQ(e,t){if("simulator"!==e.kind)throw new D("UNSUPPORTED_OPERATION",`${t} is only supported on iOS simulators`)}async function l0(){await rF("open",["-a","Simulator"],{allowFailure:!0,timeoutMs:1e4})}async function l1(e){let t,r;if("simulator"!==e.kind||"Booted"===await l3(e))return;let n=et.fromTimeoutMs(18e4);try{await el(async({deadline:n})=>{if(n?.isExpired())throw new D("COMMAND_FAILED","iOS simulator boot deadline exceeded",{timeoutMs:18e4});let i=Math.max(1e3,n?.remainingMs()??18e4),a=await rU(rB(e,["boot",e.id]),{allowFailure:!0,timeoutMs:i});t={stdout:String(a.stdout??""),stderr:String(a.stderr??""),exitCode:a.exitCode};let o=`${t.stdout}
21
- ${t.stderr}`.toLowerCase(),s=o.includes("already booted")||o.includes("current state: booted");if(0!==t.exitCode&&!s)throw new D("COMMAND_FAILED","simctl boot failed",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let l=await rU(rB(e,["bootstatus",e.id,"-b"]),{allowFailure:!0,timeoutMs:i});if(r={stdout:String(l.stdout??""),stderr:String(l.stderr??""),exitCode:l.exitCode},0!==r.exitCode)throw new D("COMMAND_FAILED","simctl bootstatus failed",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});let u=await l3(e);if("Booted"!==u)throw new D("COMMAND_FAILED","Simulator is still booting",{state:u})},{maxAttempts:3,baseDelayMs:500,maxDelayMs:2e3,jitter:.2,shouldRetry:e=>{let n=U({error:e,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});return"IOS_BOOT_TIMEOUT"!==n&&"CI_RESOURCE_STARVATION_SUSPECTED"!==n}},{deadline:n,phase:"boot",classifyReason:e=>U({error:e,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}})})}catch(a){let i=U({error:a,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});throw new D("COMMAND_FAILED","iOS simulator failed to boot",{platform:"ios",deviceId:e.id,timeoutMs:18e4,elapsedMs:n.elapsedMs(),reason:i,hint:ei(i),boot:t,bootstatus:r})}await l0()}async function l2(e){let t=rB(e,["shutdown",e.id]),r=await rU(t,{allowFailure:!0,timeoutMs:15e3});return{success:0===r.exitCode,exitCode:r.exitCode,stdout:String(r.stdout??""),stderr:String(r.stderr??"")}}async function l3(e){let t="string"==typeof e?e:e.id,r="string"==typeof e?rq(["list","devices","-j"]):rB(e,["list","devices","-j"]),n=await rU(r,{allowFailure:!0,timeoutMs:6e4});if(0!==n.exitCode)return null;try{let e=JSON.parse(String(n.stdout??""));for(let r of Object.values(e.devices??{})){let e=r.find(e=>e.udid===t);if(e)return e.state}return null}catch{return null}}async function l5(e,t){try{let r=await rV(e),n=r?.[t];if("string"==typeof n&&n.length>0)return n}catch{}try{let r=await rF("plutil",["-extract",t,"raw","-o","-",e],{allowFailure:!0});if(0===r.exitCode){let e=String(r.stdout??"").trim();if(e.length>0)return e}}catch{}try{var r,n;let i;return r=await d.readFile(e,"utf8"),n=t,nm(nf(r),(e,t)=>{void 0===i&&e===n&&"string"===t.name&&(i=t.text??void 0)}),i}catch{return}}async function l4(e,t){let r;if("url"===e.kind&&!t0(e.url))throw new D("INVALID_ARGS","iOS install_from_source URL sources are only supported for trusted artifact services such as GitHub Actions and EAS. Use a path source for other hosts.");let n=await tQ({source:e,isInstallablePath:(e,t)=>t.isDirectory()&&e.toLowerCase().endsWith(".app")||t.isFile()&&e.toLowerCase().endsWith(".ipa"),installableLabel:"iOS installable (.app or .ipa)",allowArchiveExtraction:"url"!==e.kind||t0(e.url),signal:t?.signal});try{let e=r=await l6(n.installablePath,t),i=await l8(e.installPath);return{archivePath:n.archivePath??(n.installablePath.toLowerCase().endsWith(".ipa")?n.installablePath:void 0),installablePath:e.installPath,bundleId:i.bundleId,appName:i.appName,cleanup:async()=>{await e.cleanup(),await n.cleanup()}}}catch(e){try{await r?.cleanup()}finally{await n.cleanup()}throw e}}async function l8(e){let t=f.join(e,"Info.plist"),[r,n,i]=await Promise.all([l5(t,"CFBundleIdentifier"),l5(t,"CFBundleDisplayName"),l5(t,"CFBundleName")]);return{bundleId:r,appName:n??i}}async function l6(e,t){if(!e.toLowerCase().endsWith(".ipa"))return{installPath:e,cleanup:async()=>{}};let r=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-ipa-")),n=async()=>{await d.rm(r,{recursive:!0,force:!0})};try{await R("unzip",["-q",e,"-d",r]);let i=f.join(r,"Payload"),a=(await d.readdir(i,{withFileTypes:!0}).catch(()=>{throw new D("INVALID_ARGS","Invalid IPA: missing Payload directory")})).filter(e=>e.isDirectory()&&e.name.toLowerCase().endsWith(".app")).map(e=>({installPath:f.join(i,e.name),bundleName:e.name.replace(/\.app$/i,"")})),o=a[0];if(void 0!==o&&1===a.length)return{installPath:o.installPath,cleanup:n};if(0===a.length)throw new D("INVALID_ARGS","Invalid IPA: expected at least one .app under Payload, found 0");await l9(a);let s=t?.appIdentifierHint?.trim();if(s){let e=function(e,t){let r=t.toLowerCase(),n=e.filter(e=>e.bundleName.toLowerCase()===r);if(1===n.length)return n[0];if(n.length>1)throw new D("INVALID_ARGS",`Invalid IPA: multiple app bundles matched "${t}" by name. Use a bundle id hint instead.`);if(t.includes(".")){let t=e.filter(e=>e.bundleId?.toLowerCase()===r);if(1===t.length)return t[0]}}(a,s);if(e)return{installPath:e.installPath,cleanup:n};throw new D("INVALID_ARGS",`Invalid IPA: found ${a.length} .app bundles under Payload and none matched "${s}". Available bundles: ${a.map(l7).join(", ")}`)}throw new D("INVALID_ARGS",`Invalid IPA: found ${a.length} .app bundles under Payload. Pass an app identifier or bundle name matching one of: ${a.map(l7).join(", ")}`)}catch(e){throw await n(),e}}async function l9(e){await Promise.all(e.map(async e=>{if(e.bundleId&&e.appName)return;let t=await l8(e.installPath);e.bundleId=e.bundleId??t.bundleId,e.appName=e.appName??t.appName}))}function l7(e){let t=e.bundleId??e.appName;return t?`${e.bundleName}.app (${t})`:`${e.bundleName}.app`}let ue="agent-device-macos-helper",ut="AGENT_DEVICE_MACOS_HELPER_BIN",ur=f.join(c.homedir(),".agent-device","macos-helper","current"),un=f.join(ur,"manifest.json"),ui=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;function ua(e){let t=e.trim();if(!ui.test(t))throw new D("INVALID_ARGS","macOS bundle id must use reverse-DNS form like com.example.App",{bundleId:e});return t}function uo(e,t){t.bundleId&&e.push("--bundle-id",ua(t.bundleId)),t.surface&&e.push("--surface",t.surface)}function us(){return function(e){let t=f.dirname(e);for(;;){let e=f.join(t,"macos-helper");if(u(f.join(e,"Package.swift")))return e;let r=f.dirname(t);if(r===t)break;t=r}throw new D("COMMAND_FAILED","Unable to locate macOS helper package root",{modulePath:e})}(g(import.meta.url))}async function ul(e){let t=await d.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let r=f.join(e,t.name);return t.isDirectory()?".build"===t.name?[]:await ul(r):t.isFile()&&(t.name.endsWith(".swift")||"Package.swift"===t.name)?[r]:[]}))).flat().sort()}async function uu(e){let t=await ul(e),r=s("sha256");for(let n of t)r.update(f.relative(e,n)),r.update("\0"),r.update(await d.readFile(n)),r.update("\0");let n=await rF("swift",["--version"],{allowFailure:!0,cwd:e,timeoutMs:1e4});return r.update("swift-version"),r.update("\0"),r.update(n.stdout||n.stderr||`exit:${n.exitCode}`),r.update("\0"),r.digest("hex")}async function ud(){try{let e=JSON.parse(await d.readFile(un,"utf8"));return"string"==typeof e.fingerprint?e.fingerprint:null}catch{return null}}async function uc(){let e=await L(process.env[ut],ut);if(e)return e;let t=us(),r=await uu(t),n=f.join(ur,ue);try{if(await ud()===r)return await d.access(n),n}catch{}let i=f.join(us(),".build","release",ue);process.stderr.write("agent-device: building macOS helper (first run or helper update)\n"),await rF("swift",["build","-c","release","--package-path",t],{cwd:t,timeoutMs:12e4}),await d.mkdir(ur,{recursive:!0});let a=`${n}.tmp`;return await d.copyFile(i,a),await d.rename(a,n),await d.chmod(n,493),await d.writeFile(un,`${JSON.stringify({fingerprint:r},null,2)}
22
- `,"utf8"),n}async function up(){let e=process.env[ut]?.trim();if(e){let t=await L(e,ut);if(t)return t}if(rE.hasScope())return ue;if("darwin"!==process.platform)throw new D("UNSUPPORTED_PLATFORM","macOS helper is only available on macOS");return await uc()}async function uf(e){let t={allowFailure:!0,timeoutMs:3e4},r=rT().macosHelper,n=r?ue:await up(),i=r?await r.run(e,t):await rF(n,e,t),a=i.stdout.trim(),o=null;if(a)try{o=JSON.parse(a)}catch{o=null}if(0===i.exitCode&&o?.ok)return o.data;throw new D("COMMAND_FAILED",o&&!o.ok?o.error?.message??`macOS helper exited with code ${i.exitCode}`:a||i.stderr.trim()||`macOS helper exited with code ${i.exitCode}`,{helperPath:n,args:e,stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,...o&&!o.ok?o.error?.details:{}})}async function um(){return await uf(["app","frontmost"])}async function uh(e){return await uf(["app","quit","--bundle-id",ua(e)])}async function uw(e,t){return await uf(["permission",e,t])}async function ug(e,t={}){let r=["alert",e];return uo(r,t),await uf(r)}async function uy(e,t={}){let r=["snapshot","--surface",e];return uo(r,t),await uf(r)}async function uv(e,t,r={}){let n=["read","--x",String(e),"--y",String(t)];return uo(n,r),await uf(n)}async function uI(e,t,r={}){let n=["press","--x",String(e),"--y",String(t)];return uo(n,r),await uf(n)}async function ub(e,t={}){let r=["screenshot","--out",e];return uo(r,t),t.fullscreen&&r.push("--fullscreen"),await uf(r)}let uA={settings:"com.apple.systempreferences"},uS=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/,ux={platform:"macos",deviceId:"host",variant:"all"},u_=ef();async function uN(e){let t=e.trim(),r=uA[t.toLowerCase()];if(r)return r;if(uS.test(t))return t;let n=u_.get(ux,t);if(n)return n;let i=(await uC("all")).filter(e=>e.name.toLowerCase()===t.toLowerCase()),a=i[0];if(void 0!==a&&1===i.length)return u_.set(ux,t,a.bundleId);if(i.length>1)throw new D("INVALID_ARGS",`Multiple apps matched "${e}"`,{matches:i});throw new D("APP_NOT_INSTALLED",`No app found matching "${e}"`)}async function uM(e,t,r){let n=r?.url?.trim();if(n){if(!em(n))throw new D("INVALID_ARGS","open <app> <url> requires a valid URL target");let e=r?.appBundleId??await uN(t);await uE().openBundle(e,n);return}let i=t.trim();if(em(i))return void await uE().openTarget(i);let a=r?.appBundleId??await uN(i);await uE().openBundle(a)}async function uk(e,t){let r=await uN(t),n=await uh(r);if(n.running&&!n.terminated&&!n.forceTerminated)throw new D("COMMAND_FAILED",`Failed to close macOS app ${t}`,{bundleId:r,running:n.running,terminated:n.terminated,forceTerminated:n.forceTerminated})}async function uD(){return await uE().readClipboard()}async function uO(e){await uE().writeClipboard(e)}async function uP(){return await uE().readDarkMode()}async function uR(e){let t=lL(e),r="toggle"===t?!await uP():"dark"===t;await uE().setDarkMode(r)}async function uC(e){return await uE().listApps(e)}function uE(){let e=rT().macosHost;if(!e)throw new D("UNSUPPORTED_OPERATION","macOS host provider is not available");return e}function uL(e){if(!(e instanceof D))return{reason:e instanceof Error?e.message:String(e)};let t=e.details??{},r=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):void 0;return{errorCode:e.code,reason:e.message,timeoutMs:"number"==typeof t.timeoutMs?t.timeoutMs:void 0,exitCode:"number"==typeof t.exitCode?t.exitCode:void 0,stderr:"string"==typeof t.stderr&&t.stderr.trim()?t.stderr:void 0,stdout:"string"==typeof t.stdout&&t.stdout.trim()?t.stdout:void 0,commandArgs:r}}let uT=["--time","9:41","--dataNetwork","wifi","--wifiMode","active","--wifiBars","3","--batteryState","charged","--batteryLevel","100"],u$={0:"hide",1:"wifi",6:"3g",7:"4g",8:"lte",9:"lte-a",10:"lte+",11:"5g",12:"5g+",13:"5g-uwb",14:"5g-uc"},uF={1:"searching",2:"failed",3:"active"},uU={0:"notSupported",1:"searching",2:"failed",3:"active"};function uV(e,t,r){return rU(rB(e,t),r)}async function uG(e,t){var r,n;let i;await uB(e),t&&await uj(e,(i=[],(r=t).dataNetwork&&i.push("--dataNetwork",r.dataNetwork),r.wifiMode&&i.push("--wifiMode",r.wifiMode),void 0!==r.wifiBars&&("wifi"===r.dataNetwork||r.wifiMode)&&i.push("--wifiBars",r.wifiBars),r.cellularMode&&i.push("--cellularMode",r.cellularMode),void 0!==r.cellularBars&&(r.cellularMode||(n=r.dataNetwork)&&"hide"!==n&&"wifi"!==n||void 0!==r.operatorName)&&i.push("--cellularBars",r.cellularBars),void 0!==r.operatorName&&i.push("--operatorName",r.operatorName),i))}async function uq(e){let t=await uV(e,["status_bar",e.id,"list"],{allowFailure:!0});if(0!==t.exitCode)throw new D("COMMAND_FAILED","Failed to read simulator status bar overrides",{exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr});return function(e){let t={};for(let r of e.split("\n").map(e=>e.trim()).filter(e=>e.length>0&&"Current Status Bar Overrides:"!==e&&!/^=+$/.test(e))){let e=/^DataNetworkType:\s+(\d+)$/.exec(r);if(e){let r=Number(e[1]),n=u$[r];if(!n)throw new D("COMMAND_FAILED",`Unsupported simulator data network type: ${r}`);t.dataNetwork=n;continue}let n=/^WiFi Mode:\s+(\d+),\s+WiFi Bars:\s+(\d+)$/.exec(r);if(n){let e=uF[Number(n[1])];e&&(t.wifiMode=e),t.wifiBars=n[2];continue}let i=/^Cell Mode:\s+(\d+),\s+Cell Bars:\s+(\d+)$/.exec(r);if(i){let e=Number(i[1]),r=uU[e];if(!r)throw new D("COMMAND_FAILED",`Unsupported simulator cellular mode: ${e}`);t.cellularMode=r,t.cellularBars=i[2];continue}let a=/^Operator Name:\s*(.*)$/.exec(r);if(a){t.operatorName=a[1]??"";continue}}return 0===Object.keys(t).length?null:t}(t.stdout)}async function uB(e){await uV(e,["status_bar",e.id,"clear"])}async function uj(e,t){0!==t.length&&await uV(e,["status_bar",e.id,"override",...t])}function uH(e,t,r){eN({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...uL(r)}})}function uW(e,t,r){return rU(rB(e,t),r)}let uz={ensureBooted:l1,prepareStatusBarForScreenshot:async function e(e){let t=null,r=!1;try{t=await uq(e),r=!0}catch(t){uH(e,"snapshot_failed",t)}try{await uB(e),await uj(e,uT)}catch(t){uH(e,"prepare_failed",t)}return async()=>{await uG(e,r?t:null)}},captureWithRetry:uX,captureWithRunner:uZ,shouldFallbackToRunner:u3};async function uK(e,t,r,n,i){if("macos"===e.platform)return void await uZ(e,t,r,n,i);if("simulator"===e.kind)return void await uJ(e,t,r,n,void 0,i);try{await sa(["device","screenshot","--device",e.id,t],{action:"capture iOS screenshot",deviceId:e.id});return}catch(t){if(!function(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},r="string"==typeof t.stdout?t.stdout:"",n="string"==typeof t.stderr?t.stderr:"",i=`${e.message}
23
- ${r}
24
- ${n}`.toLowerCase();return i.includes("unknown option '--device'")||i.includes("unknown subcommand")&&i.includes("screenshot")||i.includes("unrecognized subcommand")&&i.includes("screenshot")}(t))throw t;u1(e,"devicectl_screenshot",t)}await uZ(e,t,r,n,i)}async function uJ(e,t,r,n,i=uz,a){if("simulator"!==e.kind)throw new D("UNSUPPORTED_OPERATION","Simulator screenshot fallback flow supports only iOS simulators");let o="object"==typeof n&&null!==n?n:i;await o.ensureBooted(e);let s=async()=>{};try{s=await o.prepareStatusBarForScreenshot(e)}catch(t){u2(e,"prepare_failed",t)}try{try{await o.captureWithRetry(e,t);return}catch(t){if(!o.shouldFallbackToRunner(t))throw t;u1(e,"simctl_screenshot",t)}await o.captureWithRunner(e,t,r,"boolean"==typeof n?n:void 0,a)}finally{await s().catch(t=>u2(e,"restore_failed",t))}}async function uX(e,t){let r=et.fromTimeoutMs(2e4);await el(async({deadline:r})=>{await uW(e,["io",e.id,"screenshot",t],{timeoutMs:Math.max(1e3,r?.remainingMs()??2e4)})},{maxAttempts:5,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>u3(e)},{deadline:r,phase:"ios_simulator_screenshot"})}async function uZ(e,t,r,n,i){let a=(await iP(e,{command:"screenshot",appBundleId:r,fullscreen:n},i)).message;if(!a)throw new D("COMMAND_FAILED","Failed to capture iOS screenshot: runner returned no file path");"macos"===e.platform?await d.copyFile(a,t):"simulator"===e.kind?await uQ(e,a,t):await uY(e,a,t)}async function uY(e,t,r){let n=et.fromTimeoutMs(2e4),i={exitCode:1,stdout:"",stderr:""};for(let a of nG)if(0===(i=await rU(["devicectl","device","copy","from","--device",e.id,"--source",t,"--destination",r,"--domain-type","appDataContainer","--domain-identifier",a],{allowFailure:!0,timeoutMs:u0(n,2e4,"runner screenshot copy")})).exitCode)return;let a=i.stderr.trim()||i.stdout.trim()||`devicectl exited with code ${i.exitCode}`;throw new D("COMMAND_FAILED",`Failed to capture iOS screenshot: ${a}`)}async function uQ(e,t,r){let n=et.fromTimeoutMs(2e4),i="Unable to locate runner container for simulator screenshot";for(let a of nG){let o=await uW(e,["get_app_container",e.id,a,"data"],{allowFailure:!0,timeoutMs:u0(n,2e4,"runner screenshot container lookup")});if(0!==o.exitCode){let e=o.stderr.trim();e&&(i=e);continue}let s=o.stdout.trim();if(!s){i="simctl get_app_container returned empty output";continue}for(let e of function(e,t){let r=f.resolve(e),n=t.trim();if(!n)return[];let i=[],a=new Set,o=e=>{let t=f.normalize(e);a.has(t)||(a.add(t),i.push(t))},s=n.replace(/^\/+/,""),l=s.replace(/\\/g,"/");if(s&&o(f.join(r,s)),f.isAbsolute(n)&&o(f.normalize(n)),l.startsWith("tmp/"))o(f.join(r,l));else{let e=l.lastIndexOf("/tmp/");if(e>=0){let t=l.slice(e+1);o(f.join(r,t))}}let u=f.basename(n);return u&&o(f.join(r,"tmp",u)),i}(s,t))try{await d.copyFile(e,r);return}catch(e){i=e instanceof Error?e.message:String(e)}}throw new D("COMMAND_FAILED",`Failed to capture iOS screenshot: ${i}`)}function u0(e,t,r){let n=e.remainingMs();if(n>0)return n;throw new D("COMMAND_FAILED",`iOS ${r} timed out after ${t}ms`,{timeoutMs:t,step:r})}function u1(e,t,r){let n=uL(r);eN({level:"warn",phase:"ios_screenshot_fallback",data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:t,to:"runner",...n}})}function u2(e,t,r){eN({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...uL(r)}})}function u3(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},r="string"==typeof t.stdout?t.stdout:"",n="string"==typeof t.stderr?t.stderr:"",i=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):"",a=`${e.message}
25
- ${r}
26
- ${n}
27
- ${i}`.toLowerCase();return a.includes("timeout waiting for screen surfaces")||a.includes("nsposixerrordomain")&&a.includes("code=60")&&a.includes("screenshot")||a.includes("timed out")&&a.includes("screenshot")}let u5={settings:"com.apple.Preferences"},u4=ef(),u8=null;function u6(e){return{platform:"ios",deviceId:e.id,variant:e.kind}}function u9(e,t,r){return rU(rB(e,t),r)}function u7(e){return e.includes("not installed")||e.includes("not found")||e.includes("no such file")}async function de(e,t){if("macos"===e.platform)return await uN(t);let r=t.trim();if(r.includes("."))return r;let n=u5[r.toLowerCase()];if(n)return n;let i=u6(e),a=u4.get(i,r);if(a)return a;let o=("simulator"===e.kind?await dw(e):await so(e,"all")).filter(e=>e.name.toLowerCase()===r.toLowerCase()),s=o[0];if(void 0!==s&&1===o.length)return u4.set(i,r,s.bundleId);if(o.length>1)throw new D("INVALID_ARGS",`Multiple apps matched "${t}"`,{matches:o});throw new D("APP_NOT_INSTALLED",`No app found matching "${t}"`)}async function dt(e,t){var r;let n;if("ios"!==e.platform||"simulator"!==e.kind)return;let i=(r=t,n=/^([A-Za-z][A-Za-z0-9+.-]*):/.exec(r.trim()),n?.[1]?.toLowerCase());if(!i)return;let a=await dg(e),o=[];for(let e of a)!e.bundleId.startsWith("com.callstack.agentdevice.runner")&&e.path&&(await dy(f.join(e.path,"Info.plist"))).has(i)&&o.push(e);let s=o.filter(e=>"User"===e.applicationType);return 1===s.length?s[0]?.bundleId:s.length>1?void 0:1===o.length?o[0]?.bundleId:void 0}async function dr(e,t,r){let n=r?.launchConsole?.trim();if(n&&("ios"!==e.platform||"simulator"!==e.kind))throw new D("UNSUPPORTED_OPERATION",lJ);if("macos"===e.platform)return void await uM(e,t,r);let i=r?.url?.trim();if(i){if(n)throw new D("INVALID_ARGS",lX);if(!em(i))throw new D("INVALID_ARGS","open <app> <url> requires a valid URL target");if("simulator"===e.kind){await l1(e),await u9(e,["openurl",e.id,i]);return}let a=ee(r?.appBundleId??await de(e,t),i);if(!a)throw new D("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await dk(e,a,{payloadUrl:i});return}let a=t.trim();if(em(a)){if(n)throw new D("INVALID_ARGS",lX);if("simulator"===e.kind){await l1(e),await u9(e,["openurl",e.id,a]);return}let t=ee(r?.appBundleId,a);if(!t)throw new D("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await dk(e,t,{payloadUrl:a});return}let o=r?.appBundleId??await de(e,t);"simulator"===e.kind?await d_(e,o,{...n?{launchConsole:n}:{},...r?.launchArgs?{launchArgs:r.launchArgs}:{}}):await dk(e,o)}async function dn(e){"macos"===e.platform||"simulator"!==e.kind||"Booted"!==await l3(e)&&await l1(e)}async function di(e,t){if("macos"===e.platform)return void await uk(e,t);let r=await de(e,t);if("simulator"===e.kind){await l1(e);let t=rB(e,["terminate",e.id,r]),n=await rU(t,{allowFailure:!0});if(0!==n.exitCode){if(n.stderr.toLowerCase().includes("found nothing to terminate"))return;throw new D("COMMAND_FAILED",`xcrun exited with code ${n.exitCode}`,{cmd:"xcrun",args:t,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}return}await sa(["device","process","terminate","--device",e.id,r],{action:"terminate iOS app",deviceId:e.id})}async function da(e,t){if("ios"!==e.platform||"simulator"!==e.kind)throw new D("UNSUPPORTED_OPERATION","Clearing app state is currently supported only on iOS simulators.");let r=await de(e,t);await l1(e),await di(e,r);let n=await u9(e,["get_app_container",e.id,r,"data"],{allowFailure:!0});if(0!==n.exitCode)throw new D("COMMAND_FAILED",`simctl get_app_container failed for ${r}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});let i=n.stdout.trim();if(!i)throw new D("COMMAND_FAILED",`simctl get_app_container returned an empty data container path for ${r}`);let a=await d.readdir(i);return await Promise.all(a.map(e=>d.rm(f.join(i,e),{recursive:!0,force:!0}))),{bundleId:r,containerPath:i}}async function ds(e,t){return await u4.invalidateWhile(u6(e),async()=>{let r=await de(e,t);if("simulator"!==e.kind){let t=["devicectl","device","uninstall","app","--device",e.id,r],n=await rU(t,{allowFailure:!0,timeoutMs:2e4});if(0!==n.exitCode){let i=String(n.stdout??""),a=String(n.stderr??"");if(!u7(`${i}
28
- ${a}`.toLowerCase()))throw new D("COMMAND_FAILED",`Failed to uninstall iOS app ${r}`,{cmd:"xcrun",args:t,exitCode:n.exitCode,stdout:i,stderr:a,deviceId:e.id,hint:sd(i,a)??su})}return{bundleId:r}}await l1(e);let n=await u9(e,["uninstall",e.id,r],{allowFailure:!0});if(0!==n.exitCode&&!u7(`${n.stdout}
29
- ${n.stderr}`.toLowerCase()))throw new D("COMMAND_FAILED",`simctl uninstall failed for ${r}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});return{bundleId:r}})}async function dl(e,t,r){let n=await l4({kind:"path",path:t},r);try{return await dd(e,n.installablePath),{archivePath:n.archivePath,installablePath:n.installablePath,bundleId:n.bundleId,appName:n.appName,launchTarget:n.bundleId}}finally{await n.cleanup()}}async function du(e,t,r){return await u4.invalidateWhile(u6(e),async()=>{let{bundleId:n}=await ds(e,t);return await dl(e,r,{appIdentifierHint:t}),{bundleId:n}})}async function dd(e,t){await u4.invalidateWhile(u6(e),async()=>{"simulator"!==e.kind?await sa(["device","install","app","--device",e.id,t],{action:"install iOS app",deviceId:e.id}):(await l1(e),await u9(e,["install",e.id,t]))})}async function dc(e){if("macos"===e.platform)return await uD();lQ(e,"clipboard"),await l1(e);let t=await u9(e,["pbpaste",e.id],{allowFailure:!0});if(0!==t.exitCode)throw new D("COMMAND_FAILED","Failed to read iOS simulator clipboard",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});return t.stdout.replace(/\r\n/g,"\n").replace(/\n$/,"")}async function dp(e,t){if("macos"===e.platform)return void await uO(t);lQ(e,"clipboard"),await l1(e);let r=await u9(e,["pbcopy",e.id],{allowFailure:!0,stdin:t});if(0!==r.exitCode)throw new D("COMMAND_FAILED","Failed to write iOS simulator clipboard",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}async function df(e,t,r){lQ(e,"push"),await l1(e);let n=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-push-")),i=f.join(n,"payload.apns");try{await d.writeFile(i,`${JSON.stringify(r)}
30
- `,"utf8"),await u9(e,["push",e.id,t,i])}finally{await d.rm(n,{recursive:!0,force:!0})}}async function dm(e,t,r,n,i){if("macos"===e.platform){let e=t.toLowerCase();if("appearance"===e)return void await uR(r);if("permission"===e){let e=lC(r);if("deny"===e)throw new D("INVALID_ARGS",tD("permission"));let t=function(e){let t=e?.trim().toLowerCase();if("accessibility"===t||"screen-recording"===t||"input-monitoring"===t)return t;throw new D("INVALID_ARGS","Unsupported macOS permission target. Use accessibility|screen-recording|input-monitoring.")}(i?.permissionTarget);return await uw(e,t)}throw new D("INVALID_ARGS",tD(t))}lQ(e,"settings"),await l1(e);let a=t.toLowerCase();switch(a){case"wifi":{let t=lT(r);await u9(e,["status_bar",e.id,"override","--wifiMode",t?"active":"failed"]);return}case"airplane":return void(lT(r)?await u9(e,["status_bar",e.id,"override","--dataNetwork","hide","--wifiMode","failed","--wifiBars","0","--cellularMode","failed","--cellularBars","0","--operatorName",""]):await u9(e,["status_bar",e.id,"clear"]));case"location":{if("set"===r.toLowerCase()){let{latitude:t,longitude:r}=ez(i);return await u9(e,["location",e.id,"set",`${t},${r}`]),{latitude:t,longitude:r}}let t=lT(r);if(!n)throw new D("INVALID_ARGS","location setting requires an active app in session");await u9(e,["privacy",e.id,t?"grant":"revoke","location",n]);return}case"faceid":case"touchid":{let t=dI[a],n=function(e,t){let r=e.trim().toLowerCase();if("match"===r)return"match";if("nonmatch"===r)return"nonmatch";if("enroll"===r)return"enroll";if("unenroll"===r)return"unenroll";throw new D("INVALID_ARGS",`Invalid ${t} state: ${e}. Use match|nonmatch|enroll|unenroll.`)}(r,a);await dx(e,n,{settingName:a,label:t.label,modalityAliases:t.modalityAliases});return}case"appearance":{let t=await dv(e,r);await u9(e,["ui",e.id,"appearance",t]);return}case"permission":{var o;if(!n)throw new D("INVALID_ARGS","permission setting requires an active app in session");let t="deny"===(o=lC(r))?"revoke":o,a=function(e,t){let r=lE(e);if("photos"!==r&&t?.trim())throw new D("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===r)return"camera";if("microphone"===r)return"microphone";if("contacts"===r)return"contacts";if("contacts-limited"===r)return"contacts-limited";if("notifications"===r)return"notifications";if("calendar"===r)return"calendar";if("location"===r)return"location";if("location-always"===r)return"location-always";if("media-library"===r)return"media-library";if("motion"===r)return"motion";if("reminders"===r)return"reminders";if("siri"===r)return"siri";if("photos"===r){let e=t?.trim().toLowerCase();if(!e||"full"===e)return"photos";if("limited"===e)return"photos-add";throw new D("INVALID_ARGS",`Invalid photos mode: ${t}. Use full|limited.`)}throw new D("INVALID_ARGS",`Unsupported permission target: ${e}. Use camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri.`)}(i?.permissionTarget,i?.permissionMode);await db(e,t,a,n);return}default:throw new D("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function dh(e,t){return"macos"===e.platform?await uC(t):"simulator"===e.kind?rk(await dw(e),t):await so(e,t)}async function dw(e){return(await dg(e)).map(e=>({bundleId:e.bundleId,name:e.name}))}async function dg(e){let t=(await u9(e,["listapps",e.id],{allowFailure:!0})).stdout.trim();if(!t)return[];let r=null;if(t.startsWith("{"))try{r=JSON.parse(t)}catch{r=null}if(!r&&t.startsWith("{"))try{let e=await rF("plutil",["-convert","json","-o","-","-"],{allowFailure:!0,stdin:t});0===e.exitCode&&e.stdout.trim().startsWith("{")&&(r=JSON.parse(e.stdout))}catch{r=null}return r?Object.entries(r).map(([e,t])=>{let r=function(e){if(e.Path)return e.Path;if(e.Bundle)try{return g(e.Bundle)}catch{return}}(t);return{bundleId:e,name:t.CFBundleDisplayName??t.CFBundleName??e,...r?{path:r}:{},...t.ApplicationType?{applicationType:t.ApplicationType}:{}}}):[]}async function dy(e){let t=await rF("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==t.exitCode)return new Set;try{let e=JSON.parse(t.stdout),r=new Set;for(let t of e.CFBundleURLTypes??[])if(Array.isArray(t.CFBundleURLSchemes))for(let e of t.CFBundleURLSchemes)"string"==typeof e&&e.trim()&&r.add(e.trim().toLowerCase());return r}catch{return new Set}}async function dv(e,t){let r=lL(t);if("toggle"!==r)return r;let n=await u9(e,["ui",e.id,"appearance"],{allowFailure:!0});if(0!==n.exitCode)throw new D("COMMAND_FAILED","Failed to read current iOS appearance",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});let i=function(e,t){let r=/\b(light|dark|unsupported|unknown)\b/i.exec(`${e}
31
- ${t}`);if(!r)return null;let n=r[1]?.toLowerCase();return"dark"===n?"dark":"light"===n?"light":null}(n.stdout,n.stderr);if(!i)throw new D("COMMAND_FAILED","Unable to determine current iOS appearance for toggle",{stdout:n.stdout,stderr:n.stderr});return"dark"===i?"light":"dark"}let dI={faceid:{label:"Face ID",modalityAliases:["face"]},touchid:{label:"Touch ID",modalityAliases:["finger","touch"]}};async function db(e,t,r,n){let i=await dS(e);if(!i.has(r))throw new D("UNSUPPORTED_OPERATION",`iOS simctl privacy does not support service "${r}" on this runtime.`,{deviceId:e.id,appBundleId:n,hint:`Supported services: ${Array.from(i).sort().join(", ")}`});let a=["privacy",e.id,t,r,n],o="notifications"===r;if(!("reset"===t&&o))try{await u9(e,a);return}catch(t){if(!(o&&dA(t)))throw t;throw new D("UNSUPPORTED_OPERATION","iOS simulator does not support setting notifications permission via simctl privacy on this runtime.",{deviceId:e.id,appBundleId:n,hint:"Use reset notifications for reprompt behavior, or toggle notifications manually in Settings."})}try{await u9(e,a);return}catch(e){if(!dA(e))throw e}try{await u9(e,["privacy",e.id,"reset","all",n])}catch(t){throw new D("COMMAND_FAILED","iOS simulator blocked direct notifications reset. Fallback reset-all also failed.",{deviceId:e.id,appBundleId:n,hint:"Use reinstall to force a fresh notifications prompt, or reset simulator content and settings."},t instanceof Error?t:void 0)}}function dA(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=String(e.details?.stderr??"").toLowerCase();return(t.includes("failed to grant access")||t.includes("failed to revoke access")||t.includes("failed to reset access"))&&t.includes("operation not permitted")}async function dS(t){let r=Y(t.simulatorSetPath),n=`${process.env.PATH??""}::${r??""}`;if(u8&&e===n)return u8;let i=await u9(t,["privacy","help"],{allowFailure:!0}),a=function(e){let t=new Set,r=!1;for(let n of e.split("\n")){let e=n.trim();if(!e)continue;if("service"===e){r=!0;continue}if(!r)continue;if(e.startsWith("bundle identifier"))break;let i=/^([a-z-]+)\s+-\s+/.exec(e),a=i?.[1];void 0!==a&&t.add(a)}return t}(`${i.stdout}
32
- ${i.stderr}`);if(0===a.size)throw new D("COMMAND_FAILED","Unable to determine supported simctl privacy services",{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,hint:"Run `xcrun simctl privacy help` manually to verify available services for this runtime."});return u8=a,e=n,a}async function dx(e,t,r){let n=function(e,t,r){let n=r.length>0?r:["face"];switch(t){case"match":return n.flatMap(t=>[["biometric",e,"match",t],["biometric","match",e,t]]);case"nonmatch":return n.flatMap(t=>[["biometric",e,"nonmatch",t],["biometric",e,"nomatch",t],["biometric","nonmatch",e,t],["biometric","nomatch",e,t]]);case"enroll":return[["biometric",e,"enroll","yes"],["biometric",e,"enroll","1"],["biometric","enroll",e,"yes"],["biometric","enroll",e,"1"]];case"unenroll":return[["biometric",e,"enroll","no"],["biometric",e,"enroll","0"],["biometric","enroll",e,"no"],["biometric","enroll",e,"0"]]}}(e.id,t,r.modalityAliases),i=[];for(let t of n){let r=rB(e,t),n=await rU(r,{allowFailure:!0});if(0===n.exitCode)return;i.push({args:r,stderr:n.stderr,stdout:n.stdout,exitCode:n.exitCode})}let a=lP(i);if(i.length>0&&i.every(e=>{var t,r;let n;return t=e.stdout,r=e.stderr,(n=`${t}
33
- ${r}`.toLowerCase()).includes("unrecognized subcommand")||n.includes("unknown subcommand")||n.includes("not supported")||n.includes("unavailable")||n.includes("biometric")&&n.includes("invalid")}))throw new D("UNSUPPORTED_OPERATION",`${r.label} simulation is not supported on this simulator runtime.`,{deviceId:e.id,action:t,setting:r.settingName,attempts:a});throw new D("COMMAND_FAILED",`Failed to simulate ${r.settingName}.`,{deviceId:e.id,action:t,setting:r.settingName,attempts:a})}async function d_(e,t,r){await l1(e);let n=0,i=et.fromTimeoutMs(6e4);try{await el(async({deadline:n})=>{var i,a,o,s;let l;if(n?.isExpired())throw new D("COMMAND_FAILED","App launch deadline exceeded",{timeoutMs:6e4});let u=(a=e.id,o=t,s=r,l=["launch"],s?.launchConsole&&l.push("--console-pty"),l.push(a,o),s?.launchArgs&&l.push(...s.launchArgs),i=l,rB(e,i)),d=r?.launchConsole?await dN(u,r.launchConsole):await rU(u,{allowFailure:!0});if(0!==d.exitCode)throw new D("COMMAND_FAILED",`xcrun exited with code ${d.exitCode}`,{cmd:"xcrun",args:u,stdout:d.stdout,stderr:d.stderr,exitCode:d.exitCode})},{maxAttempts:10,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>!!lZ(e)&&(n+=1)<3},{deadline:i})}catch(r){if(lZ(r)){var a;let n=(a=await lY(e,t)).installed?!1===a.simulatorCompatible?"ARCH_MISMATCH":"PERSISTENT_LAUNCH_FAIL":"APP_NOT_INSTALLED";r.details={...r.details,hint:function(e){switch(e){case"ARCH_MISMATCH":return"The app binary was not built for the simulator platform. Rebuild with a simulator destination or use a physical device.";case"APP_NOT_INSTALLED":return"The app bundle is not installed on this simulator. Run install before open.";case"PERSISTENT_LAUNCH_FAIL":return"The simulator repeatedly refused to launch the app. Inspect crash logs in Console.app or ~/Library/Logs/DiagnosticReports/ and consider reinstalling the app.";default:return"The simulator failed to launch the app. Retry with --debug and inspect diagnostics log for details."}}(n)}}throw r}}async function dN(e,t){await d.mkdir(f.dirname(t),{recursive:!0});try{let r=await rU(e,{allowFailure:!0,timeoutMs:25e3});return await dM(t,r.stdout,r.stderr),r}catch(n){let e=n instanceof D?n:void 0,r=e?.details;if(r?.timeoutMs===25e3){let e="string"==typeof r.stdout?r.stdout:"",n="string"==typeof r.stderr?r.stderr:"";return await dM(t,e,n),eN({level:"warn",phase:"ios_simulator_launch_console_capture_timeout",data:{timeoutMs:25e3,logPath:t,stdoutBytes:Buffer.byteLength(e),stderrBytes:Buffer.byteLength(n)}}),{stdout:e,stderr:n,exitCode:0}}throw n}}async function dM(e,t,r){var n,i;await d.writeFile(e,(n=t,i=r,!n||!i||n.endsWith("\n")||n.endsWith("\r")?`${n}${i}`:`${n}
34
- ${i}`),"utf8")}async function dk(e,t,r){let n=["device","process","launch","--device",e.id,t];r?.payloadUrl&&n.push("--payload-url",r.payloadUrl),await sa(n,{action:"launch iOS app",deviceId:e.id})}function dD(e,t,r){return{command:"remotePress",remoteButton:e,...void 0!==r?{durationMs:r}:{},...void 0!==t?{appBundleId:t}:{}}}async function dO(e,t,r,n,i,a,o){if("tv"===t.target)return dC(await e(t,dD(i,r.appBundleId),n),a);let s=o??await dP(e,t,r,n),l=sg({direction:i,amount:a?.amount,pixels:a?.pixels,referenceWidth:s.referenceWidth,referenceHeight:s.referenceHeight});return dC(await e(t,{command:"drag",x:s.originX+l.x1,y:s.originY+l.y1,x2:s.originX+l.x2,y2:s.originY+l.y2,appBundleId:r.appBundleId},n),{amount:l.amount,pixels:l.pixels,preferProvidedPixels:!0})}async function dP(e,t,r,n){let i=await e(t,{command:"interactionFrame",appBundleId:r.appBundleId},n),a=dR(i.x),o=dR(i.y),s=dR(i.referenceWidth),l=dR(i.referenceHeight);if(void 0===a||void 0===o||void 0===s||void 0===l)throw new D("COMMAND_FAILED","interactionFrame did not return a usable frame");return{originX:a,originY:o,referenceWidth:s,referenceHeight:l}}function dR(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function dC(e,t){var r;let{x1:n,y1:i,x2:a,y2:o}={x1:dR((r=e).x),y1:dR(r.y),x2:dR(r.x2),y2:dR(r.y2)},s=dR(e.referenceWidth),l=dR(e.referenceHeight),u=void 0!==n&&void 0!==a?Math.round(Math.abs(a-n)):void 0,d=void 0!==i&&void 0!==o?Math.round(Math.abs(o-i)):void 0,c=t?.preferProvidedPixels&&void 0!==t.pixels?t.pixels:u&&u>0?u:d&&d>0?d:void 0;return{...void 0!==n?{x1:n}:{},...void 0!==i?{y1:i}:{},...void 0!==a?{x2:a}:{},...void 0!==o?{y2:o}:{},...void 0!==s?{referenceWidth:s}:{},...void 0!==l?{referenceHeight:l}:{},...t?.amount!==void 0?{amount:t.amount}:{},...void 0!==c?{pixels:c}:{}}}let dE=null;async function dL(){let e=o3();if(dE?.provider===e)return dE;let t=process.env.WAYLAND_DISPLAY||"wayland"===process.env.XDG_SESSION_TYPE?"wayland":"x11";if("wayland"===t){if(await e.whichCommand("ydotool"))return dE={tool:"ydotool",display:t,provider:e};throw new D("TOOL_MISSING","ydotool is required for input synthesis on Wayland (xdotool does not work on Wayland). Install it via your package manager.")}if(await e.whichCommand("xdotool"))return dE={tool:"xdotool",display:t,provider:e};throw new D("TOOL_MISSING","xdotool is required for input synthesis on X11. Install it via your package manager.")}async function dT(...e){await o3().runCommand("xdotool",e,{allowFailure:!1,timeoutMs:1e4})}async function d$(...e){await o3().runCommand("ydotool",e,{allowFailure:!1,timeoutMs:1e4})}function dF(){return o3().input}async function dU(e,t){let{tool:r}=await dL();"xdotool"===r?await dT("mousemove","--sync",String(e),String(t)):await d$("mousemove","--absolute","-x",String(e),"-y",String(t))}async function dV(e,t){let r=dF();if(r)return void await r.key(e,t);let{tool:n}=await dL();"xdotool"===n?await dT("key","--clearmodifiers",e):await d$("key",...t)}async function dG(e,t,r,n){await dU(e,t);let{tool:i}=await dL();"xdotool"===i?await dT("click",r):await d$("click",n)}async function dq(e,t,r,n,i){let a=dF();a?await a.click(e,t,r):await dG(e,t,n,i)}async function dB(e,t){await dq(e,t,"primary","1","0xC0")}async function dj(e,t){await dq(e,t,"secondary","3","0xC1")}async function dH(e,t){await dq(e,t,"middle","2","0xC2")}async function dW(e,t){let r=dF();if(r)return void await r.doubleClick(e,t);let{tool:n}=await dL();await dU(e,t),"xdotool"===n?await dT("click","--repeat","2","1"):(await d$("click","0xC0"),await d$("click","0xC0"))}async function dz(e,t,r=800){let n=dF();if(n)return void await n.longPress(e,t,r);let{tool:i}=await dL();await dU(e,t),"xdotool"===i?(await dT("mousedown","1"),await e8(r),await dT("mouseup","1")):(await d$("click","--down","0xC0"),await e8(r),await d$("click","--up","0xC0"))}async function dK(e,t){await dB(e,t)}async function dJ(e,t,r,n,i=300){let a=dF();if(a)return void await a.drag(e,t,r,n,i);let{tool:o}=await dL();await dU(e,t),"xdotool"===o?(await dT("mousedown","1"),await dT("mousemove","--sync",String(r),String(n)),await e8(i),await dT("mouseup","1")):(await d$("click","--down","0xC0"),await d$("mousemove","--absolute","-x",String(r),"-y",String(n)),await e8(i),await d$("click","--up","0xC0"))}async function dX(e,t){let r=dF();if(r)return void await r.scroll(e,t);let{tool:n}=await dL(),i=5;if(t?.pixels!=null?i="xdotool"===n?Math.max(1,Math.round(t.pixels/15)):Math.max(1,Math.round(t.pixels/40)):t?.amount!=null&&(i=Math.max(1,Math.round(5*(t.amount/.6)))),"xdotool"===n)await dT("click","--repeat",String(i),"up"===e?"4":"down"===e?"5":"left"===e?"6":"7");else if("up"===e||"down"===e){let t="up"===e?String(-i):String(i);await d$("mousemove","--wheel","-y",t)}else{let t="left"===e?String(-i):String(i);await d$("mousemove","--wheel","-x",t)}}async function dZ(e,t=0){let r=dF();if(r)return void await r.typeText(e,{delayMs:t});let{tool:n}=await dL();if("xdotool"===n){let r=["type"];t>0&&r.push("--delay",String(t)),r.push("--clearmodifiers","--",e),await dT(...r)}else await d$("type","--",e)}async function dY(e,t,r,n=0){await dB(e,t),await e8(100),await dV("ctrl+a",["29:1","30:1","30:0","29:0"]),await e8(50),await dZ(r,n)}async function dQ(e){await o3().desktop.openTarget(e)}async function d0(e){await o3().desktop.closeApp(e)}async function d1(){await dV("alt+Left",["56:1","105:1","105:0","56:0"])}async function d2(){await dV("super+d",["125:1","32:1","32:0","125:0"])}async function d3(){return await o3().clipboard.readText()}async function d5(e){await o3().clipboard.writeText(e)}async function d4(e,t){await o3().screenshot.capture(e,t)}let d8={"push button":"Button","toggle button":"Button","push button menu":"Button",label:"StaticText",static:"StaticText",caption:"StaticText",text:"TextField",entry:"TextField","password text":"TextField","spin button":"TextField",terminal:"TextArea","document text":"TextArea",paragraph:"TextArea",frame:"Window",window:"Window",dialog:"Dialog",alert:"Alert","file chooser":"Dialog","color chooser":"Dialog","font chooser":"Dialog",panel:"Group",filler:"Group",section:"Group",form:"Group",grouping:"Group","layered pane":"Group","glass pane":"Group","root pane":"Group","option pane":"Group","internal frame":"Group","desktop frame":"Group","block quote":"Group",article:"Group",comment:"Group",landmark:"Group",log:"Group",marquee:"Group",math:"Group",notification:"Group","content deletion":"Group","content insertion":"Group",mark:"Group",suggestion:"Group","scroll pane":"ScrollArea","scroll bar":"ScrollBar","menu bar":"MenuBar",menu:"Menu","popup menu":"Menu","menu item":"MenuItem","check menu item":"MenuItem","radio menu item":"MenuItem","tearoff menu item":"MenuItem","check box":"CheckBox","radio button":"RadioButton",switch:"Switch","combo box":"ComboBox","page tab":"Tab","page tab list":"TabList",table:"Table","tree table":"Table","table cell":"Cell","table row":"Row","table column header":"Cell","table row header":"Cell","column header":"Cell","row header":"Cell",list:"List","list item":"ListItem","list box":"List",tree:"Tree","tree item":"TreeItem","description list":"List","description term":"ListItem","description value":"ListItem","tool bar":"Toolbar","status bar":"StatusBar","info bar":"StatusBar",slider:"Slider","progress bar":"ProgressBar","level bar":"ProgressBar",image:"Image",icon:"Image",animation:"Image",canvas:"Image","drawing area":"Image",video:"Video",audio:"Audio",link:"Link",hyperlink:"Link",separator:"Separator",application:"Application","tool tip":"Tooltip",timer:"Timer",heading:"Heading",footnote:"Footnote","title bar":"TitleBar","date editor":"DateEditor",rating:"Slider"},d6="atspi-dump.py",d9=null;async function d7(e,t={}){let r,n=o3().accessibility;if(n)return await n.captureTree(e,t);if("linux"!==process.platform)throw new D("UNSUPPORTED_PLATFORM","AT-SPI2 bridge is only available on Linux");if(!await o3().whichCommand("python3"))throw new D("TOOL_MISSING","python3 is required for AT-SPI2 accessibility snapshots on Linux.");let i=t.maxNodes??1500,a=t.maxDepth??12,o=t.maxApps??24,s=[function(){if(d9)return d9;let e=f.dirname(g(import.meta.url));for(let t=0;t<5;t++){let r=f.join(e,"src","platforms","linux",d6);if(l.existsSync(r))return d9=r,r;if(0===t){let t=f.join(e,d6);if(l.existsSync(t))return d9=t,t}e=f.dirname(e)}throw new D("TOOL_MISSING",`Cannot find ${d6}. Ensure the agent-device package is installed correctly.`)}(),"--surface",e,"--max-nodes",String(i),"--max-depth",String(a),"--max-apps",String(o)],u=await o4("python3",s,{allowFailure:!0,timeoutMs:3e4});if(0!==u.exitCode){let e=u.stderr.trim();if(e.includes("No module named")||e.includes("gi.require_version"))throw new D("TOOL_MISSING","AT-SPI2 Python bindings not found. Install python3-gi and gir1.2-atspi-2.0.",{cause:e});throw new D("COMMAND_FAILED",`AT-SPI2 snapshot failed (exit ${u.exitCode}): ${e||u.stdout}`)}try{r=JSON.parse(u.stdout)}catch{throw new D("COMMAND_FAILED",`AT-SPI2 snapshot returned invalid JSON: ${u.stdout.slice(0,200)}`)}if(r.error)throw new D("COMMAND_FAILED",`AT-SPI2: ${r.error}`);return{nodes:(r.nodes??[]).map(e=>{let t,r;return{index:e.index,type:(r=d8[t=e.role.toLowerCase().trim()])||t.split(/[\s_-]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),role:e.role,label:e.label??void 0,value:e.value??void 0,rect:e.rect??void 0,enabled:e.enabled??void 0,selected:e.selected??void 0,hittable:e.hittable??void 0,depth:e.depth,parentIndex:e.parentIndex??void 0,pid:e.pid??void 0,appName:e.appName??void 0,windowTitle:e.windowTitle??void 0}}),truncated:r.truncated,surface:e}}async function ce(e){let t="desktop"===e?"desktop":"frontmost-app"===e||"app"===e?"frontmost-app":("menubar"===e&&eN({level:"warn",phase:"linux_snapshot",data:{message:"menubar surface is not supported on Linux, falling back to desktop"}}),"desktop"),r=await d7(t);return{nodes:r.nodes,truncated:r.truncated}}async function ct(e,t,r){let{nodes:n}=await ce(r);for(let r of n.filter(r=>{let n=r.rect;return!!n&&e>=n.x&&t>=n.y&&e<=n.x+n.width&&t<=n.y+n.height}).sort((e,t)=>{let r=e.depth??0,n=t.depth??0;return r!==n?n-r:cr(e.rect)-cr(t.rect)})){let e=function(e){for(let t of[e.value,e.label,e.identifier])if("string"==typeof t&&t.length>0)return t;return""}(r);if(e.trim())return e}return""}function cr(e){return(e?.width??0)*(e?.height??0)}let cn=/^[A-Za-z0-9_.:-]{1,64}$/;function ci(e){return e?.clickButton??"primary"}function ca(e){return"primary"===e.button?null:"click"!==e.commandLabel?new D("INVALID_ARGS","--button is supported only for click"):"macos"!==e.platform&&"linux"!==e.platform?new D("UNSUPPORTED_OPERATION",`click --button ${e.button} is supported only on macOS and Linux`):"macos"===e.platform&&"middle"===e.button?new D("UNSUPPORTED_OPERATION","click --button middle is not supported by the macOS runner yet"):"number"==typeof e.count||"number"==typeof e.intervalMs||"number"==typeof e.holdMs||"number"==typeof e.jitterPx||!0===e.doubleTap?new D("INVALID_ARGS",`click --button ${e.button} does not support repeat or gesture modifier flags`):null}let co=[[0,0],[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];async function cs(e,t,r){for(let n=0;n<e;n+=1)await r(n),n<e-1&&t>0&&await e8(t)}async function cl(e,t){let{x:r,y:n}=ch(t,"longpress requires x y [durationMs]",{hint:"Direct platform longpress requires coordinates. In an open daemon session, use agent-device longpress @ref|selector [durationMs]; otherwise run snapshot -i -c, use the target rect center as x y, then retry longpress x y durationMs."}),i=t[2]?Number(t[2]):void 0;return await e.longPress(r,n,i),{x:r,y:n,durationMs:i,...eJ(`Long pressed (${r}, ${n})`)}}async function cu(e,t){let{x:r,y:n}=ch(t,"focus requires x y");return await e.focus(r,n),{x:r,y:n,...eJ(`Focused (${r}, ${n})`)}}async function cd(e,t,r){let n=tC(t[0]);if(n)throw new D("INVALID_ARGS",`type does not accept a target ref like "${n}"`,{hint:`Use fill ${n} "text" to target that field, or press ${n} then type "text" to append.`});let i=t.join(" ");if(!i)throw new D("INVALID_ARGS","type requires text");let a=tB(r?.delayMs??0,"delay-ms",0,1e4);return await e.type(i,a),{text:i,delayMs:a,...eJ(cE("Typed",i))}}async function cc(e,t,r){if(r?.directElementSelector)return await cp(e,r.directElementSelector,t,r);let n=Number(t[0]),i=Number(t[1]),a=t.slice(2).join(" ");if(Number.isNaN(n)||Number.isNaN(i)||!a)throw new D("INVALID_ARGS","fill requires x y text");let o=tB(r?.delayMs??0,"delay-ms",0,1e4);return await e.fill(n,i,a,o),{x:n,y:i,text:a,delayMs:o,...eJ(cE("Filled",a))}}async function cp(e,t,r,n){if(!e.fillElementSelector)throw new D("UNSUPPORTED_OPERATION","direct element selector fill is not supported");let i=r.join(" ");if(!i)throw new D("INVALID_ARGS","fill requires text");let a=tB(n.delayMs??0,"delay-ms",0,1e4),o=await e.fillElementSelector(t,i,a);return{selector:t.raw,text:i,delayMs:a,...o??{},...eJ(cE("Filled",i))}}async function cf(e,t,r,n){var i,a,o,s;if(n?.directElementSelector&&"ios"===e.platform)return await cm(t,n.directElementSelector);let{x:l,y:u}=ch(r,"press requires x y");if("macos"===e.platform&&n?.surface&&"app"!==n.surface)return await cw(l,u,n);let d=ci(n);if("primary"!==d)return await cg(e,l,u,d,n);let c=(s=n,{count:cv(s?.count,1,"count",1,200),intervalMs:cv(s?.intervalMs,0,"interval-ms",0,1e4),holdMs:cv(s?.holdMs,0,"hold-ms",0,1e4),jitterPx:cv(s?.jitterPx,0,"jitter-px",0,100),doubleTap:!!s?.doubleTap});return(function({doubleTap:e,holdMs:t,jitterPx:r}){if(e&&t>0)throw new D("INVALID_ARGS","double-tap cannot be combined with hold-ms");if(e&&r>0)throw new D("INVALID_ARGS","double-tap cannot be combined with jitter-px")}(c),i=c.count,a=c.holdMs,o=c.jitterPx,nn(e.platform)&&i>1&&0===a&&0===o)?await cI(e,l,u,c,n):await cb(t,l,u,c)}async function cm(e,t){if(!e.tapElementSelector)throw new D("UNSUPPORTED_OPERATION","direct element selector tap is not supported");let r=await e.tapElementSelector(t);return{selector:t.raw,...r??{},...eJ(`Tapped ${t.raw}`)}}function ch(e,t,r){let n=Number(e[0]),i=Number(e[1]);if(Number.isNaN(n)||Number.isNaN(i))throw new D("INVALID_ARGS",t,r);return{x:n,y:i}}async function cw(e,t,r){let n=ci(r);if("primary"!==n)throw new D("UNSUPPORTED_OPERATION",`${n} click is not supported on macOS ${r.surface} sessions.`);return await uI(e,t,{bundleId:r.appBundleId,surface:r.surface}),{x:e,y:t,...eJ(cR({x:e,y:t}))}}async function cg(e,t,r,n,i){return(function(e,t,r){let n=ca({commandLabel:"click",platform:e.platform,button:t,count:r?.count,intervalMs:r?.intervalMs,holdMs:r?.holdMs,jitterPx:r?.jitterPx,doubleTap:r?.doubleTap});if(n)throw n}(e,n,i),"linux"===e.platform)?await cy(t,r,n):(await iP(e,{command:"mouseClick",x:t,y:r,button:n,appBundleId:i?.appBundleId},cA(i)),{x:t,y:r,button:n,...eJ(cR({x:t,y:r,button:n}))})}async function cy(e,t,r){return"secondary"===r?await dj(e,t):await dH(e,t),{x:e,y:t,button:r,...eJ(cR({x:e,y:t,button:r}))}}function cv(e,t,r,n,i){return tB(void 0===e?t:e,r,n,i)}async function cI(e,t,r,n,i){let a=await iP(e,{command:"tapSeries",x:t,y:r,count:n.count,intervalMs:n.intervalMs,doubleTap:n.doubleTap,appBundleId:i?.appBundleId},cA(i));return{x:t,y:r,count:n.count,intervalMs:n.intervalMs,holdMs:n.holdMs,jitterPx:n.jitterPx,doubleTap:n.doubleTap,timingMode:"runner-series",...a,...eJ(cR({x:t,y:r}))}}async function cb(e,t,r,n){let i;return await cs(n.count,n.intervalMs,async a=>{let[o,s]=function(e,t){if(t<=0)return[0,0];let[r,n]=co[e%co.length];return[r*t,n*t]}(a,n.jitterPx),l=t+o,u=r+s;if(n.doubleTap){i??=await e.doubleTap(l,u)??void 0;return}n.holdMs>0?i??=await e.longPress(l,u,n.holdMs)??void 0:i??=await e.tap(l,u)??void 0}),eV({x:t,y:r,count:n.count,intervalMs:n.intervalMs,holdMs:n.holdMs,jitterPx:n.jitterPx,doubleTap:n.doubleTap,...i},cR({x:t,y:r}))}function cA(e){return{verbose:e?.verbose,logPath:e?.logPath,traceLogPath:e?.traceLogPath,requestId:e?.requestId}}async function cS(e,t,r,n){let i=Number(r[0]),a=Number(r[1]),o=Number(r[2]),s=Number(r[3]);if([i,a,o,s].some(Number.isNaN))throw new D("INVALID_ARGS","swipe requires x1 y1 x2 y2 [durationMs]");let l=tB(r[4]?Number(r[4]):250,"durationMs",16,1e4),u="ios"===e.platform?Math.min(60,Math.max(16,Math.round(l))):l,d=tB(n?.count??1,"count",1,200),c=tB(n?.pauseMs??0,"pause-ms",0,1e4),p=n?.pattern??"one-way";if("one-way"!==p&&"ping-pong"!==p)throw new D("INVALID_ARGS",`Invalid pattern: ${p}`);if(nn(e.platform)&&d>1){let t=await iP(e,{command:"dragSeries",x:i,y:a,x2:o,y2:s,durationMs:u,count:d,pauseMs:c,pattern:p,appBundleId:n?.appBundleId},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId});return{x1:i,y1:a,x2:o,y2:s,durationMs:l,effectiveDurationMs:u,timingMode:"runner-series",count:d,pauseMs:c,pattern:p,...t,...eJ(cC(d,p))}}return await cs(d,c,async e=>{"ping-pong"===p&&e%2==1?await t.swipe(o,s,i,a,u):await t.swipe(i,a,o,s,u)}),eV({x1:i,y1:a,x2:o,y2:s,durationMs:l,effectiveDurationMs:u,timingMode:"ios"===e.platform?"safe-normalized":"direct",count:d,pauseMs:c,pattern:p},cC(d,p))}async function cx(e,t){let r=Number(t[0]),n=Number(t[1]),i=Number(t[2]),a=Number(t[3]);if([r,n,i,a].some(e=>!Number.isFinite(e)))throw new D("INVALID_ARGS","gesture pan requires x y dx dy [durationMs]");let o=tB(t[4]?Number(t[4]):500,"durationMs",16,1e4),s=r+i,l=n+a;return await e.pan(r,n,s,l,o),{x:r,y:n,dx:i,dy:a,x2:s,y2:l,durationMs:o,...eJ(`Panned (${r}, ${n}) by (${i}, ${a})`)}}async function c_(e,t){let r=function(e,t){if("up"===e||"down"===e||"left"===e||"right"===e)return e;throw new D("INVALID_ARGS",`${t} must be up, down, left, or right`)}(t[0],"fling direction"),n=Number(t[1]),i=Number(t[2]);if(![n,i].every(Number.isFinite))throw new D("INVALID_ARGS","gesture fling requires direction x y [distance] [durationMs]");let a=function(e,t){if(!Number.isFinite(e)||e<=0)throw new D("INVALID_ARGS",`${t} must be a positive number`);return e}(t[3]?Number(t[3]):180,"distance"),o=tB(t[4]?Number(t[4]):50,"durationMs",16,1e3),{x2:s,y2:l}=function(e,t,r,n){switch(r){case"up":return{x2:e,y2:t-n};case"down":return{x2:e,y2:t+n};case"left":return{x2:e-n,y2:t};case"right":return{x2:e+n,y2:t}}}(n,i,r,a);return await e.fling(n,i,s,l,o),{direction:r,x:n,y:i,x2:s,y2:l,distance:a,durationMs:o,...eJ(`Flung ${r}`)}}async function cN(e,t,r){var n;let i=t[0],a=t[1]?Number(t[1]):void 0,o=r?.pixels;if(!i)throw new D("INVALID_ARGS","scroll requires direction");if(void 0!==a&&!Number.isFinite(a))throw new D("INVALID_ARGS","scroll amount must be a number");if(void 0!==a&&void 0!==o)throw new D("INVALID_ARGS","scroll accepts either a relative amount or --pixels, not both");let s="bottom"===(n=i)?{direction:"down",edge:"bottom"}:"top"===n?{direction:"up",edge:"top"}:{direction:function(e){switch(e){case"up":case"down":case"left":case"right":return e;default:throw new D("INVALID_ARGS",`Unknown direction: ${e}`)}}(n)},l={},u=0;if(s.edge){let t=s.edge,n=await tk({edge:t,captureState:async n=>await cM(e,r,t,n),scroll:async()=>await e.scroll(s.direction,{amount:a,pixels:o})});l=n.result??{},u=n.passes}else l=await e.scroll(s.direction,{amount:a,pixels:o}),u=1;return eV({direction:s.direction,...s.edge?{edge:s.edge,passes:u}:{},...void 0!==a?{amount:a}:{},...void 0!==o?{pixels:o}:{},...l},tT(s.direction,s.edge,u,a,o))}async function cM(e,t,r,n){if("function"!=typeof e.snapshot)throw new D("UNSUPPORTED_OPERATION",`scroll ${r} requires snapshot support to verify hidden content before scrolling`);let i=e.snapshot;return await tF({edge:r,scope:n,captureNodes:async e=>(await i({appBundleId:t?.appBundleId,compact:!0,scope:e})).nodes??[]})}async function ck(e,t,r,n){if("tv"===e.target)throw new D("UNSUPPORTED_OPERATION","gesture pinch is not supported on tvOS");if("macos"===e.platform&&n?.surface&&"app"!==n.surface)throw new D("UNSUPPORTED_OPERATION","gesture pinch is only supported in macOS app sessions. Re-open the target app without --surface desktop|menubar|frontmost-app first.");let i=Number(r[0]),a=r[1]?Number(r[1]):void 0,o=r[2]?Number(r[2]):void 0;if(Number.isNaN(i)||i<=0)throw new D("INVALID_ARGS","gesture pinch requires scale > 0");let s=await t.pinch(i,a,o);return{scale:i,x:a,y:o,...s,...eJ(`Pinched to scale ${i}`)}}async function cD(e,t,r){if("tv"===e.target)throw new D("UNSUPPORTED_OPERATION","gesture rotate is not supported on tvOS");if("macos"===e.platform)throw new D("UNSUPPORTED_OPERATION","gesture rotate is not supported on macOS; XCTest rotation gestures are available only for iOS app sessions.");let{degrees:n,x:i,y:a,velocity:o}=function(e){let t=Number(e[0]);if(!Number.isFinite(t))throw new D("INVALID_ARGS","gesture rotate requires degrees [x] [y] [velocity]");let r=function(e,t){if(void 0===e&&void 0===t)return{};if(void 0===e||void 0===t)throw new D("INVALID_ARGS","gesture rotate center requires both x and y");let r=Number(e),n=Number(t);if(!Number.isFinite(r)||!Number.isFinite(n))throw new D("INVALID_ARGS","gesture rotate center requires finite x and y");return{x:r,y:n}}(e[1],e[2]),n=Number(e[3]??(t>=0?1:-1));if(!Number.isFinite(n)||0===n)throw new D("INVALID_ARGS","gesture rotate velocity must be a non-zero number");return{degrees:t,...r,velocity:Math.abs(n)*(t>=0?1:-1)}}(r),s=await t.rotateGesture(n,i,a,o);return{degrees:n,...void 0!==i&&void 0!==a?{x:i,y:a}:{},velocity:o,...s,...eJ(`Rotated gesture ${n} degrees`)}}async function cO(e,t,r){if("tv"===e.target)throw new D("UNSUPPORTED_OPERATION","gesture transform is not supported on tvOS");let n="ios"===e.platform&&"simulator"===e.kind;if("android"!==e.platform&&!n)throw new D("UNSUPPORTED_OPERATION","gesture transform is currently supported on Android and iOS simulators");let i=function(e){let t=Number(e[0]),r=Number(e[1]),n=Number(e[2]),i=Number(e[3]),a=Number(e[4]),o=Number(e[5]);if(![t,r,n,i,a,o].every(Number.isFinite))throw new D("INVALID_ARGS","gesture transform requires x y dx dy scale degrees [durationMs]");if(a<=0)throw new D("INVALID_ARGS","gesture transform scale must be > 0");return{x:t,y:r,dx:n,dy:i,scale:a,degrees:o,durationMs:void 0===e[6]?void 0:tB(Number(e[6]),"durationMs",16,1e4)}}(r),a=await t.transformGesture(i);return{...i,...a,...eJ(`Requested transform gesture by (${i.dx}, ${i.dy}), scale ${i.scale}, rotate ${i.degrees} degrees`)}}async function cP(e,t,r){let{x:n,y:i}=ch(t,"read requires x y");if("android"===e.platform)return{action:"read",text:await sz(e,n,i)??""};if("linux"===e.platform)return{action:"read",text:await ct(n,i,r?.surface)};if("macos"===e.platform&&r?.surface&&"app"!==r.surface)return{action:"read",text:(await uv(n,i,{bundleId:r.appBundleId,surface:r.surface})).text};let a=await iP(e,{command:"readText",x:n,y:i,appBundleId:r?.appBundleId},{verbose:r?.verbose,logPath:r?.logPath,traceLogPath:r?.traceLogPath,requestId:r?.requestId});return{action:"read",text:"string"==typeof a.text?a.text:"string"==typeof a.message?a.message:""}}function cR(e){return e.button&&"primary"!==e.button?`Clicked ${e.button} (${e.x}, ${e.y})`:`Tapped (${e.x}, ${e.y})`}function cC(e,t){return e<=1?"Swiped":"ping-pong"===t?`Swiped ${e} times (ping-pong)`:`Swiped ${e} times`}function cE(e,t){return`${e} ${Array.from(t).length} chars`}function cL(e,t){let r,n=t?.subject??"Payload",i=e.trim();if(!i)throw new D("INVALID_ARGS",`${n} cannot be empty`);let a=t?.expandPath?t.expandPath(i,t.cwd):i;try{if(!l.statSync(a).isFile())throw new D("INVALID_ARGS",`${n} path is not a file: ${a}`);return{kind:"file",path:a}}catch(t){if(t instanceof D)throw t;let e=t.code;if("EACCES"===e||"EPERM"===e)throw new D("INVALID_ARGS",`${n} file is not readable: ${a}`);if(e&&"ENOENT"!==e)throw new D("COMMAND_FAILED",`Unable to read ${n} file: ${a}`,{cause:String(t)})}if((r=i.trim()).startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))return{kind:"inline",text:i};throw new D("INVALID_ARGS",`${n} file not found: ${a}`)}async function cT(e){let t=cL(e,{subject:"Push payload"}),r="inline"===t.kind?t.text:await c$(t.path);try{let e=JSON.parse(r);if(!e||"object"!=typeof e||Array.isArray(e))throw new D("INVALID_ARGS","push payload must be a JSON object");return e}catch(t){if(t instanceof D)throw t;throw new D("INVALID_ARGS",`Invalid push payload JSON: ${e}`)}}async function c$(e){try{return await d.readFile(e,"utf8")}catch(r){let t=r.code;if("ENOENT"===t)throw new D("INVALID_ARGS",`Push payload file not found: ${e}`);if("EISDIR"===t)throw new D("INVALID_ARGS",`Push payload path is not a file: ${e}`);if("EACCES"===t||"EPERM"===t)throw new D("INVALID_ARGS",`Push payload file is not readable: ${e}`);throw new D("COMMAND_FAILED",`Unable to read push payload file: ${e}`,{cause:String(r)})}}async function cF(e,t,r,n,i){let a={requestId:i?.requestId,appBundleId:i?.appBundleId,verbose:i?.verbose,logPath:i?.logPath,traceLogPath:i?.traceLogPath},o=function(e,t){switch(e.platform){case"android":return{open:(t,r)=>B(e,t,{activity:r?.activity,appBundleId:r?.appBundleId,url:r?.url}),openDevice:()=>W(e),close:t=>j(e,t),tap:(t,r)=>sQ(e,t,r),doubleTap:async(t,r)=>{await sQ(e,t,r),await sQ(e,t,r)},swipe:(t,r,n,i,a)=>s0(e,t,r,n,i,a),pan:(t,r,n,i,a)=>s0(e,t,r,n,i,a),fling:(t,r,n,i,a)=>s0(e,t,r,n,i,a),longPress:(t,r,n)=>s8(e,t,r,n),focus:(t,r)=>s9(e,t,r),type:(t,r)=>s6(e,t,r),fill:(t,r,n,i)=>s7(e,t,r,n,i),scroll:(t,r)=>lt(e,t,r),pinch:(t,r,n)=>lw(e,{scale:t,x:r,y:n}),screenshot:(t,r)=>lH(e,t,r),snapshot:async t=>{let r=await e_("snapshot_capture",async()=>await sS(e,{interactiveOnly:t?.interactiveOnly,compact:t?.compact,depth:t?.depth,scope:t?.scope,raw:t?.raw}),{backend:"android"});return{nodes:r.nodes??[],truncated:r.truncated??!1,backend:"android",analysis:r.analysis,androidSnapshot:r.androidSnapshot}},back:t=>s1(e),home:()=>s2(e),rotate:t=>s5(e,t),rotateGesture:(t,r,n,i)=>lg(e,{degrees:t,x:r,y:n,velocity:i}),transformGesture:t=>ly(e,t),appSwitcher:()=>s4(e),readClipboard:()=>J(e),writeClipboard:t=>q(e,t),setSetting:(t,r,n,i)=>lF(e,t,r,n,i)};case"linux":return{open:e=>dQ(e),openDevice:()=>Promise.resolve(),close:e=>d0(e),tap:(e,t)=>dB(e,t),doubleTap:(e,t)=>dW(e,t),swipe:(e,t,r,n,i)=>dJ(e,t,r,n,i),pan:(e,t,r,n,i)=>dJ(e,t,r,n,i),fling:()=>{throw new D("UNSUPPORTED_OPERATION","gesture fling not supported on Linux")},longPress:(e,t,r)=>dz(e,t,r),focus:(e,t)=>dK(e,t),type:(e,t)=>dZ(e,t),fill:(e,t,r,n)=>dY(e,t,r,n),scroll:(e,t)=>dX(e,t),pinch:()=>{throw new D("UNSUPPORTED_OPERATION","gesture pinch not supported on Linux")},screenshot:(e,t)=>d4(e,t),snapshot:async e=>{let t=await e_("snapshot_capture",async()=>await ce(e?.surface),{backend:"linux-atspi"});return{nodes:t.nodes??[],truncated:t.truncated??!1,backend:"linux-atspi"}},back:()=>d1(),home:()=>d2(),rotate:()=>{throw new D("UNSUPPORTED_OPERATION","rotate not supported on Linux")},rotateGesture:()=>{throw new D("UNSUPPORTED_OPERATION","gesture rotate not supported on Linux")},transformGesture:()=>{throw new D("UNSUPPORTED_OPERATION","gesture transform not supported on Linux")},appSwitcher:()=>{throw new D("UNSUPPORTED_OPERATION","appSwitcher not yet supported on Linux")},readClipboard:()=>d3(),writeClipboard:e=>d5(e),setSetting:()=>{throw new D("UNSUPPORTED_OPERATION","setSetting not supported on Linux")}};case"ios":case"macos":return function(e,t){let r,{overrides:n,runnerOpts:i}={runnerOpts:r={verbose:t.verbose,logPath:t.logPath,traceLogPath:t.traceLogPath,requestId:t.requestId},overrides:{tap:async(n,i)=>await iP(e,{command:"tap",x:n,y:i,appBundleId:t.appBundleId},r),tapElementSelector:async n=>await iP(e,{command:"tap",selectorKey:n.key,selectorValue:n.value,allowNonHittableCoordinateFallback:n.allowNonHittableCoordinateFallback,appBundleId:t.appBundleId},r),doubleTap:async(n,i)=>await iP(e,{command:"tapSeries",x:n,y:i,count:1,intervalMs:0,doubleTap:!0,appBundleId:t.appBundleId},r),swipe:async(n,i,a,o,s)=>await iP(e,{command:"drag",x:n,y:i,x2:a,y2:o,durationMs:s,appBundleId:t.appBundleId},r),pan:async(n,i,a,o,s)=>await iP(e,{command:"drag",x:n,y:i,x2:a,y2:o,durationMs:s??500,appBundleId:t.appBundleId},r),fling:async(n,i,a,o,s)=>await iP(e,{command:"drag",x:n,y:i,x2:a,y2:o,durationMs:s??16,appBundleId:t.appBundleId},r),longPress:async(n,i,a)=>await iP(e,{command:"longPress",x:n,y:i,durationMs:a,appBundleId:t.appBundleId},r),focus:async(n,i)=>await iP(e,{command:"tap",x:n,y:i,appBundleId:t.appBundleId},r),type:async(n,i)=>{await iP(e,{command:"type",text:n,delayMs:i,textEntryMode:"\n"===n?void 0:"append",appBundleId:t.appBundleId},r)},fillElementSelector:async(n,i,a)=>await iP(e,{command:"type",selectorKey:n.key,selectorValue:n.value,allowNonHittableCoordinateFallback:n.allowNonHittableCoordinateFallback,text:i,delayMs:a,textEntryMode:"replace",appBundleId:t.appBundleId},r),fill:async(n,i,a,o)=>await iP(e,{command:"type",x:n,y:i,text:a,delayMs:o,textEntryMode:"replace",appBundleId:t.appBundleId},r),scroll:async(n,i)=>await dO(iP,e,t,r,n,i),pinch:async(n,i,a)=>{await iP(e,{command:"pinch",scale:n,x:i,y:a,appBundleId:t.appBundleId},r)},rotateGesture:async(n,i,a,o)=>{await iP(e,{command:"rotateGesture",degrees:n,x:i,y:a,velocity:o,appBundleId:t.appBundleId},r)},transformGesture:async n=>await iP(e,{command:"transformGesture",x:n.x,y:n.y,dx:n.dx,dy:n.dy,scale:n.scale,degrees:n.degrees,durationMs:n.durationMs,appBundleId:t.appBundleId},r)}};return{open:(t,r)=>dr(e,t,{appBundleId:r?.appBundleId,launchConsole:r?.launchConsole,launchArgs:r?.launchArgs,url:r?.url}),openDevice:()=>dn(e),close:t=>di(e,t),screenshot:async(t,r)=>{"macos"===e.platform&&r?.surface&&"app"!==r.surface?await ub(t,{surface:r.surface,fullscreen:r.fullscreen}):await uK(e,t,r?.appBundleId,r?.fullscreen,i)},snapshot:async t=>{var r;let n={nodes:Array.isArray((r=await e_("snapshot_capture",async()=>await iP(e,{command:"snapshot",appBundleId:t?.appBundleId,interactiveOnly:t?.interactiveOnly,compact:t?.compact,depth:t?.depth,scope:t?.scope,raw:t?.raw},i),{backend:"xctest"})).nodes)?r.nodes:void 0,truncated:"boolean"==typeof r.truncated?r.truncated:void 0},a=n.nodes??[];if(0===a.length&&"simulator"===e.kind)throw new D("COMMAND_FAILED","XCTest snapshot returned 0 nodes on iOS simulator.");return{nodes:a,truncated:n.truncated??!1,backend:"xctest"}},back:async r=>{"tv"===e.target?await iP(e,dD("menu",t.appBundleId),i):await iP(e,{command:"system"===r?"backSystem":"backInApp",appBundleId:t.appBundleId},i)},home:async()=>{"tv"===e.target?await iP(e,dD("home",t.appBundleId),i):await iP(e,{command:"home",appBundleId:t.appBundleId},i)},rotate:async r=>{await iP(e,{command:"rotate",orientation:r,appBundleId:t.appBundleId},i)},appSwitcher:async()=>{await iP(e,{command:"appSwitcher",appBundleId:t.appBundleId},i)},readClipboard:()=>dc(e),writeClipboard:t=>dp(e,t),setSetting:(t,r,n,i)=>dm(e,t,r,n,i),...n}}(e,t);default:throw new D("UNSUPPORTED_PLATFORM",`Unsupported platform: ${e.platform}`)}}(e,a);return eN({level:"debug",phase:"platform_command_prepare",data:{command:t,platform:e.platform,kind:e.kind}}),await e_("platform_command",async()=>await cU(e,o,t,r,n,i,a),{command:t,platform:e.platform})}async function cU(e,t,r,n,i,a,o){switch(r){case"open":return await cV(e,t,n,a);case"close":{let e=n[0];if(!e)return{closed:"session",...eJ("Closed session")};return await t.close(e),{app:e,...eJ(`Closed: ${e}`)}}case"press":return await cf(e,t,n,a);case"swipe":return await cS(e,t,n,a);case"pan":return await cx(t,n);case"fling":return await c_(t,n);case"longpress":return await cl(t,n);case"focus":return await cu(t,n);case"type":return await cd(t,n,a);case"fill":return await cc(t,n,a);case"scroll":return await cN(t,n,a);case"pinch":return await ck(e,t,n,a);case"rotate-gesture":return await cD(e,t,n);case"transform-gesture":return await cO(e,t,n);case"trigger-app-event":return await cG(e,t,n,a);case"screenshot":return await cq(t,n,i,a);case"back":return await t.back(a?.backMode),{action:"back",mode:a?.backMode??"in-app",...eJ("Back")};case"home":return await t.home(),{action:"home",...eJ("Home")};case"rotate":{let e=e1(n[0]);return await t.rotate(e),{action:"rotate",orientation:e,...eJ(`Rotated to ${e}`)}}case"app-switcher":return await t.appSwitcher(),{action:"app-switcher",...eJ("Opened app switcher")};case"clipboard":return await cB(t,n);case"keyboard":return await cj(e,n,a,o);case"settings":return await cz(e,t,n,a);case"push":return await cK(e,n,a);case"snapshot":return await cJ(t,a);case"read":return await cP(e,n,a);default:throw new D("INVALID_ARGS",`Unknown command: ${r}`)}}async function cV(e,t,r,n){let i=r[0],a=r[1],o=n?.launchConsole;if(r.length>2)throw new D("INVALID_ARGS","open accepts at most two arguments: <app|url> [url]");if(!i){if(o)throw new D("INVALID_ARGS","--launch-console requires an app target");return await t.openDevice(),{app:null,...eJ("Opened device")}}if(o&&("ios"!==e.platform||"simulator"!==e.kind))throw new D("UNSUPPORTED_OPERATION",lJ);if(void 0!==a){if(em(i))throw new D("INVALID_ARGS","open <app> <url> requires an app target as the first argument");if(!em(a))throw new D("INVALID_ARGS","open <app> <url> requires a valid URL target");if(o)throw new D("INVALID_ARGS",lX);return await t.open(i,{activity:n?.activity,appBundleId:n?.appBundleId,launchArgs:n?.launchArgs,url:a}),{app:i,url:a,...eJ(`Opened: ${i}`)}}if(o&&em(i))throw new D("INVALID_ARGS",lX);if("android"===e.platform&&n?.launchArgs&&n.launchArgs.length>0)throw new D("UNSUPPORTED_OPERATION","Launch arguments are currently supported only on Apple platforms.");if(n?.clearAppState){if(em(i))throw new D("INVALID_ARGS","Clearing app state requires an app target, not a deep link.");if("ios"!==e.platform||"simulator"!==e.kind)throw new D("UNSUPPORTED_OPERATION","Clearing app state is currently supported only on iOS simulators.");await da(e,i)}return await t.open(i,{activity:n?.activity,appBundleId:n?.appBundleId,launchConsole:o,launchArgs:n?.launchArgs}),{app:i,...o?{launchConsole:o}:{},...eJ(`Opened: ${i}`)}}async function cG(e,t,r,n){let{eventName:i,payload:a}=function(e){let t=e[0]?.trim(),r=e[1]?.trim();if(!t)throw new D("INVALID_ARGS","trigger-app-event requires <event> [payloadJson]");if(!cn.test(t))throw new D("INVALID_ARGS",`Invalid trigger-app-event event name: ${t}`,{hint:"Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash."});if(e.length>2)throw new D("INVALID_ARGS","trigger-app-event accepts at most two arguments: <event> [payloadJson]");let n=function(e,t){if(e)try{let r=JSON.parse(e);if(!r||"object"!=typeof r||Array.isArray(r))throw new D("INVALID_ARGS",`trigger-app-event payload for "${t}" must be a JSON object`);let n=JSON.stringify(r);if(Buffer.byteLength(n,"utf8")>8192)throw new D("INVALID_ARGS",`trigger-app-event payload for "${t}" exceeds 8192 bytes`);return r}catch(t){if(t instanceof D)throw t;throw new D("INVALID_ARGS",`Invalid trigger-app-event payload JSON: ${e}`)}}(r,t);return{eventName:t,payload:n}}(r),o=function(e,t,r){var n;let i,a=(i=("ios"===(n=e)?process.env.AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE:"macos"===n?process.env.AGENT_DEVICE_MACOS_APP_EVENT_URL_TEMPLATE:process.env.AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE)??process.env.AGENT_DEVICE_APP_EVENT_URL_TEMPLATE,i?.trim()||void 0);if(!a)throw new D("UNSUPPORTED_OPERATION",`No app event URL template configured for ${e}.`,{hint:`Set AGENT_DEVICE_${e.toUpperCase()}_APP_EVENT_URL_TEMPLATE or AGENT_DEVICE_APP_EVENT_URL_TEMPLATE, for example "myapp://agent-device/event?name={event}&payload={payload}".`});let o=r?JSON.stringify(r):"",s=a.replaceAll("{event}",encodeURIComponent(t)).replaceAll("{payload}",encodeURIComponent(o)).replaceAll("{platform}",encodeURIComponent(e));if(s.length>4096)throw new D("INVALID_ARGS","trigger-app-event URL exceeds maximum supported length",{hint:"Reduce payload size or shorten AGENT_DEVICE_*_APP_EVENT_URL_TEMPLATE.",length:s.length,maxLength:4096});return s}(e.platform,i,a);return await t.open(o,{appBundleId:n?.appBundleId}),{event:i,eventUrl:o,transport:"deep-link",...eJ(`Triggered app event: ${i}`)}}async function cq(e,t,r,n){let i=t[0]??r??`./screenshot-${Date.now()}.png`;await d.mkdir(f.dirname(i),{recursive:!0});let a=eX(n);return await e.screenshot(i,{appBundleId:n?.appBundleId,fullscreen:a.fullscreen,stabilize:a.stabilize,surface:n?.surface}),{path:i,...eJ(`Saved screenshot: ${i}`)}}async function cB(e,t){let r=(t[0]??"").toLowerCase();if("read"!==r&&"write"!==r)throw new D("INVALID_ARGS","clipboard requires a subcommand: read or write");if("read"===r){if(1!==t.length)throw new D("INVALID_ARGS","clipboard read does not accept additional arguments");return{action:r,text:await e.readClipboard()}}if(t.length<2)throw new D("INVALID_ARGS",'clipboard write requires text (use "" to clear clipboard)');let n=t.slice(1).join(" ");return await e.writeClipboard(n),{action:r,textLength:Array.from(n).length,...eJ("Clipboard updated")}}async function cj(e,t,r,n){let i=(t[0]??"status").toLowerCase();if(!tw(i))throw new D("INVALID_ARGS","keyboard requires a subcommand: status, get, dismiss, enter, or return");if(t.length>1)throw new D("INVALID_ARGS","keyboard accepts at most one subcommand argument");if("android"===e.platform)return await cH(e,i);if("ios"===e.platform)return await cW(e,i,r,n);throw new D("UNSUPPORTED_OPERATION","keyboard is supported only on Android and iOS")}async function cH(e,t){if("enter"===t||"return"===t)return await s3(e),{platform:"android",action:"enter",...eJ("Keyboard enter pressed")};if("dismiss"===t){let t=await Q(e);return{platform:"android",action:"dismiss",attempts:t.attempts,wasVisible:t.wasVisible,dismissed:t.dismissed,visible:t.visible,inputType:t.inputType,type:t.type,inputMethodPackage:t.inputMethodPackage,focusedPackage:t.focusedPackage,focusedResourceId:t.focusedResourceId,inputOwner:t.inputOwner}}let r=await ea(e);return{platform:"android",action:"status",visible:r.visible,inputType:r.inputType,type:r.type,inputMethodPackage:r.inputMethodPackage,focusedPackage:r.focusedPackage,focusedResourceId:r.focusedResourceId,inputOwner:r.inputOwner}}async function cW(e,t,r,n){if("dismiss"!==t&&"enter"!==t&&"return"!==t)throw new D("UNSUPPORTED_OPERATION","keyboard status/get is currently supported only on Android; use keyboard dismiss or enter on iOS");if("enter"===t||"return"===t){let t=await iP(e,{command:"keyboardReturn",appBundleId:r?.appBundleId},n);return{platform:"ios",action:"enter",visible:t.visible,wasVisible:t.wasVisible,...eJ("Keyboard enter pressed")}}let i=await iP(e,{command:"keyboardDismiss",appBundleId:r?.appBundleId},n);return{platform:"ios",action:"dismiss",wasVisible:i.wasVisible,dismissed:i.dismissed,visible:i.visible,...eJ(i.dismissed?"Keyboard dismissed":"Keyboard already hidden")}}async function cz(e,t,r,n){var i;let[a,o,s,l]=r;if(!a||!o)throw new D("INVALID_ARGS","settings requires setting state");let u="location"===a&&"set"===o,d=("permission"===a||u?r[4]:r[2])??n?.appBundleId,c="permission"===a?{permissionTarget:s,permissionMode:l}:u?{latitude:eB(s,"latitude"),longitude:eB(l,"longitude")}:void 0;eN({level:"debug",phase:"settings_apply",data:u?{setting:a,state:o,latitude:s,longitude:l,platform:e.platform}:"permission"===a?{setting:a,state:o,permissionTarget:s,permissionMode:l,platform:e.platform}:{setting:a,state:o,appBundleId:d,platform:e.platform}});let p=await t.setSetting(a,o,d,c);return p&&"object"==typeof p?eV({setting:a,state:o,...p},("string"==typeof(i=p).message&&i.message.length>0?i.message:void 0)??`Updated setting: ${a}`):{setting:a,state:o,...eJ(`Updated setting: ${a}`)}}async function cK(e,t,r){let n=t[0]?.trim(),i=t[1]?.trim();if(!n||!i)throw new D("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>");let a=await cT(i);if("ios"===e.platform)return await df(e,n,a),{platform:"ios",bundleId:n,...eJ(`Pushed notification to ${n}`)};let o=await lp(e,n,a);return{platform:"android",package:n,action:o.action,extrasCount:o.extrasCount,...eJ(`Pushed notification to ${n}`)}}async function cJ(e,t){return await e.snapshot({appBundleId:t?.appBundleId,interactiveOnly:t?.snapshotInteractiveOnly,compact:t?.snapshotCompact,depth:t?.snapshotDepth,scope:t?.snapshotScope,raw:t?.snapshotRaw,surface:t?.surface})}function cX(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}function cZ(e,t,r){return t||cY(r)?null:cX("INVALID_ARGS",`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}function cY(e){return!!(e?.platform||e?.target||e?.device||e?.udid||e?.serial)}function cQ(e){return"ios"===e.platform&&"simulator"===e.kind}async function c0(e,t){cQ(e)&&!(t<=0)&&await new Promise(e=>setTimeout(e,t))}async function c1(e){let t=cY(e.flags)||!e.session?await oW(e.flags??{}):await c2(e.session.device);return!1!==e.ensureReady&&await sp(t),t}async function c2(e){if("ios"!==e.platform||"simulator"!==e.kind||"darwin"!==process.platform)return e;let t={platform:"ios",target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await oW(t)}catch(e){if(!(e instanceof D)||"DEVICE_NOT_FOUND"!==e.code)throw e}return await oW({platform:"ios",target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function c3(e){let t=e.flags?.device?.trim();return t||(e.resolvedDevice?.platform==="android"&&"emulator"===e.resolvedDevice.kind?e.resolvedDevice.name:e.sessionDevice?.platform==="android"&&"emulator"===e.sessionDevice.kind?e.sessionDevice.name:void 0)}let c5={startIosSimulatorRecording:({device:e,outPath:t})=>O("xcrun",rB(e,["io",e.id,"recordVideo",t]),{allowFailure:!0})},c4=rM(c5,function(e={}){return{...c5,...e}});async function c8(e,t){return await c4.run(e,t)}let c6=[{resolverKey:"androidAdbProvider",resolve(e,t){let r=e.androidAdbProvider;if(!r||"android"!==t.device.platform)return{};let n=r(t),i="function"==typeof n?n:n?.exec;return{androidAdb:{provider:n,executor:i,serial:t.device.id}}},appendWrapper(e,t){pt(t,e.androidAdb,(t,r)=>e9(t,{serial:e.androidAdb?.serial??""},r))}},{resolverKey:"appleRunnerProvider",resolve(e,t){let r=e.appleRunnerProvider;return r&&nn(t.device.platform)?{appleRunner:{provider:r(t),deviceId:t.device.id,requestId:t.req.meta?.requestId}}:{}},appendWrapper(e,t){pt(t,e.appleRunner,(t,r)=>iD(t,{deviceId:e.appleRunner?.deviceId??"",requestId:e.appleRunner?.requestId},r))}},{resolverKey:"appleToolProvider",resolve(e,t){let r=e.appleToolProvider;return r&&nn(t.device.platform)?{appleTool:{provider:r(t)}}:{}},appendWrapper(e,t){pt(t,e.appleTool,r$)}},{resolverKey:"linuxToolProvider",resolve(e,t){let r=e.linuxToolProvider;return r&&"linux"===t.device.platform?{linuxTool:{provider:r(t)}}:{}},appendWrapper(e,t){pt(t,e.linuxTool,o5)}},{resolverKey:"appLogProvider",resolve(e,t){let r=e.appLogProvider;return r?{appLog:{provider:r(t)}}:{}},appendWrapper(e,t){pt(t,e.appLog,aC)}},{resolverKey:"recordingProvider",resolve(e,t){let r=e.recordingProvider;return r?{recording:{provider:r(t)}}:{}},appendWrapper(e,t){pt(t,e.recording,c8)}}];async function c9(e,t){let r=await c7(e),n={androidAdbExecutor:r.androidAdb?.executor},i=function(e){let t=[];for(let r of c6)r.appendWrapper(e,t);return t}(r);return await pr(i,async()=>await t(n))}async function c7(e){var t,r,n;if(t=e.providers,!c6.some(e=>!!t[e.resolverKey]))return{};let i=await pe(e.req,e.existingSession);if(!i)return{};let a=(r=e,n=i,{req:r.req,device:n,session:r.existingSession});return c6.reduce((t,r)=>({...t,...r.resolve(e.providers,a)}),{})}async function pe(e,t){var r;return t?e.command===eD.apps&&cY(e.flags)?await oW(e.flags??{}):t.device:e.command===eD.open||cY(e.flags)||(r=e).command===eD.record&&"start"===(r.positionals?.[0]??"").toLowerCase()?await oW(e.flags??{}):void 0}function pt(e,t,r){let n=t?.provider;n&&e.push(async e=>await r(n,e))}async function pr(e,t){let r=t;for(let t of[...e].reverse()){let e=r;r=async()=>await t(e)}return await r()}let pn=e=>"macos"!==e.platform,pi=e=>"ios"===e.platform&&"simulator"===e.kind&&"tv"!==e.target,pa={device:!0},po={},ps={apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa},pl={apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po,supports:pn},pu={alert:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po,supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind},pinch:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po,supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind&&"tv"!==e.target},"rotate-gesture":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po,supports:e=>"android"===e.platform||pi(e)},"transform-gesture":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po,supports:e=>"android"===e.platform||pi(e)},"app-switcher":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po,supports:pn},open:ps,close:ps,reinstall:pl,install:pl,"install-from-source":pl,apps:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po},back:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa},boot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po,supports:pn},click:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa},clipboard:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa,supports:e=>"android"===e.platform||"linux"===e.platform||"macos"===e.platform||"simulator"===e.kind},keyboard:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po,supports:e=>"android"===e.platform||"ios"===e.platform&&"tv"!==e.target},fill:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa},fling:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po},snapshot:ps,diff:ps,screenshot:ps,wait:ps,get:ps,find:ps,is:ps,focus:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa},home:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa,supports:pn},logs:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po},network:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po},longpress:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa},perf:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po},pan:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa},press:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa},push:{apple:{simulator:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po,supports:pn},record:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po},"react-native":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po},rotate:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po,supports:e=>"android"===e.platform||"ios"===e.platform&&"tv"!==e.target},scroll:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa},swipe:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:pa},settings:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po,supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind},"trigger-app-event":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:po},type:ps};function pd(e,t){let r=pu[e];if(!r)return!0;let n=nn(t.platform)?r.apple:"linux"===t.platform?r.linux:r.android;return!!n&&(!r.supports||!!r.supports(t))&&!0===n[t.kind??"unknown"]}let pc=[250,400,600];function pp(e,t,r=e.snapshot){if("android"!==e.device.platform)return;let n=r?.comparisonSafe===!0;e.androidSnapshotFreshness={action:t,markedAt:Date.now(),baselineCount:r?.nodes.length??0,baselineSignatures:n?pw(r?.nodes??[]):void 0,routeComparable:n}}function pf(e){if(!e||"android"!==e.device.platform)return;let t=e.androidSnapshotFreshness;if(t)return Date.now()-t.markedAt>2500?void delete e.androidSnapshotFreshness:t}function pm(e){e&&"android"===e.device.platform&&delete e.androidSnapshotFreshness}function ph(e){return"press"===e||"click"===e||"back"===e||"open"===e}function pw(e){return e.map(e=>[e.depth??0,e.type??"",e.role??"",e.label??"",e.value??"",e.identifier??"",!1===e.enabled?"disabled":"enabled",!0===e.selected?"selected":"unselected",!0===e.hittable?"hittable":"not-hittable"].join("|"))}function pg(e,t,r,n,i){return{requestId:i??eS().requestId,appBundleId:r,activity:t?.activity,launchConsole:t?.launchConsole,launchArgs:t?.launchArgs,clearAppState:t?.clearAppState,verbose:t?.verbose,logPath:e,traceLogPath:n,snapshotInteractiveOnly:t?.snapshotInteractiveOnly,snapshotCompact:t?.snapshotCompact,snapshotDepth:t?.snapshotDepth,snapshotScope:t?.snapshotScope,snapshotRaw:t?.snapshotRaw,...eY(t),count:t?.count,intervalMs:t?.intervalMs,delayMs:t?.delayMs,holdMs:t?.holdMs,jitterPx:t?.jitterPx,pixels:t?.pixels,doubleTap:t?.doubleTap,clickButton:ci(t),backMode:t?.backMode,pauseMs:t?.pauseMs,pattern:t?.pattern}}function py(e){e?.postGestureStabilization&&(e.postGestureStabilization=void 0)}async function pv(e){let{session:t,capture:r}=e,n=t?.postGestureStabilization;if(!t||!pI(t.device.platform)||!n)return await r();let i=Date.now(),a=1,o=await r(),s=pb(o.nodes);for(;Date.now()-i<1500;){await e8(200),a+=1;let e=await r(),l=pb(e.nodes);if(function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=e[r],i=t[r];if(!n||!i||n.key!==i.key||Math.abs(n.x-i.x)>1||Math.abs(n.y-i.y)>1||Math.abs(n.width-i.width)>1||Math.abs(n.height-i.height)>1)return!1}return!0}(s,l))return py(t),eN({level:a>2?"info":"debug",phase:"post_gesture_snapshot_stabilized",data:{action:n.action,attempts:a,durationMs:Date.now()-i}}),e;o=e,s=l}return py(t),eN({level:"warn",phase:"post_gesture_snapshot_stabilization_timeout",data:{action:n.action,attempts:a,durationMs:Date.now()-i}}),o}function pI(e){return"ios"===e||"android"===e}function pb(e){let t=new Map,r=[];for(let a of e){var n,i;if(!a.rect||!([(n=a.rect).x,n.y,n.width,n.height].every(e=>Number.isFinite(e))&&n.width>0&&n.height>0)||(i=a,`${i.label??""} ${i.identifier??""}`.toLowerCase().includes("scroll bar")))continue;let e=[a.identifier,a.label,a.value,a.type].map(e=>"string"==typeof e?e.trim():"").join("|");if(!e.replaceAll("|",""))continue;let o=t.get(e)??0;t.set(e,o+1),r.push({key:`${e}|#${o}`,x:a.rect.x,y:a.rect.y,width:a.rect.width,height:a.rect.height})}return r}let pA=["x","y","width","height"];function pS(e,t){let r=e[t]?.depth??0,n=[];for(let i=t+1;i<e.length;i+=1){let t=e[i];if(t){if((t.depth??0)<=r)break;n.push(t)}}return n}function px(e,t,r){for(let n of function(e,t){let r=[],n="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0,i=new Set;for(;n&&!i.has(n.index);)i.add(n.index),r.push(n),n="number"==typeof n.parentIndex?t.get(n.parentIndex):void 0;return r}(e,t))if(r(n))return n;return null}function p_(e,t){let r=rr(e.type??""),n=e.label?.trim();return!!(pN(e)||"other"===r&&!n&&!e.value||("other"===r||"statictext"===r)&&n&&t.includes(n))||"image"===r}function pN(e){return"button"===rr(e.type??"")&&e.label?.trim()==="chevron"&&!1===e.enabled}function pM(e){let t=rr(e??"");return"collectionview"===t||"table"===t||"scrollview"===t||"scrollarea"===t}function pk(e,t,r){e.set(t.index,{...t,...e.get(t.index),...r})}function pD(e,t){return!!e&&!!t&&pA.every(r=>.5>=Math.abs(e[r]-t[r]))}function pO(e){let t;for(let i of e){var r,n;let e=rr(i.type??"");("application"===e||"window"===e)&&(r=i.rect,n=t,r&&(!n||pP(r)>pP(n)))&&(t=i.rect)}return t}function pP(e){return e?e.width*e.height:0}function pR(e){let t=rr(e.type??"");return"scrollview"===t||"scrollarea"===t}function pC(e,t){return!0===e||!!t||void 0}function pE(e,t,r){for(let n of e)(function(e,t){let r=e.label?.trim();if(!r||r!==t)return!1;let n=rr(e.type??"");return"other"===n||"statictext"===n||"link"===n})(n,t)&&r.add(n.index)}function pL(e,t,r,n){for(let i of pS(e,t))i.index!==r&&function(e){let t=rr(e.type??"");return"button"!==t&&("image"===t||"Search"===e.label)}(i)&&n.add(i.index)}function pT(e,t){for(let r=0;r<e.length;r+=1){let n=e[r],i=n?.label?.trim();n&&i&&"other"===rr(n.type??"")&&t(n,i,r)}}function p$(e,t,r,n){for(let i of e)(p_(i,t)||n&&pU(i,n))&&r.add(i.index)}function pF(e,t,r){if("button"!==rr(e.type??""))return!1;let n=t.identifier?.trim(),i=e.identifier?.trim();return!!n&&!!i&&n===i||e.label?.trim()===r&&pD(e.rect,t.rect)}function pU(e,t){return"button"===rr(e.type??"")&&!e.label?.trim()&&!e.value?.trim()&&pD(e.rect,t.rect)}let pV=[function(e,t){var r,n,i,a;let{suppressedIndexes:o}=t;(function(e,t){let r=pO(e),n=r?r.y+r.height:null;if(null!==n)for(let r=0;r<e.length;r+=1){var i,a;let o=e[r];if(o&&(i=o,a=n,i.rect&&"keyboard"===rr(i.type??"")&&i.rect.y>=a))for(let i of(t.add(o.index),function(e,t,r,n){let i=new Map(t.map(e=>[e.index,e])),a="number"==typeof e.parentIndex?i.get(e.parentIndex):void 0;for(;a?.rect&&a.rect.y>=n;)r.add(a.index),a="number"==typeof a.parentIndex?i.get(a.parentIndex):void 0}(o,e,t,n),pS(e,r)))t.add(i.index)}})(e,o),function(e,t){for(let r of e)!("other"!==rr(r.type??"")||!0===r.hittable||r.label?.trim()||r.value?.trim())&&r.identifier?.trim()&&t.add(r.index)}(e,o);let s=new Map(e.map(e=>[e.index,e]));for(let r of e)(function(e){let t=e.label?.trim();return!!(t&&tL(t))})(r)&&function(e,t,r){var n,i,a,o;pM(e.type)||r.suppressedIndexes.add(e.index);let s=tx(e.label?.trim()??"",e.value);if(!s)return;let l=function(e,t,r={}){return(!0===r.includeSelf&&pM(e.type)?e:null)??px(e,t,e=>pM(e.type))}(e,t,{includeSelf:!0});l&&(n=r,i=l,a=e,o=s,pk(n.replacements,i,{rect:function(e,t){if(e&&t&&!(t.height<=0)&&!(t.height>=e.height)&&!(t.y<e.y)&&!(t.y>e.y+e.height))return{...e,y:t.y,height:Math.min(t.height,e.y+e.height-t.y)}}(i.rect,a.rect)??i.rect,hiddenContentAbove:pC(i.hiddenContentAbove,o.above),hiddenContentBelow:pC(i.hiddenContentBelow,o.below)}))}(r,s,t);(function(e,t){for(let r=0;r<e.length;r+=1){let n=e[r];if(!n||"searchfield"!==rr(n.type??""))continue;if("Search"===n.label){pL(e,r,null,t);continue}if("Toolbar"!==n.label)continue;let i=pS(e,r).find(e=>"searchfield"===rr(e.type??"")&&"Search"===e.label);i&&(t.add(n.index),function(e,t,r){let n=new Map(t.map(e=>[e.index,e])),i=e;for(;"number"==typeof i.parentIndex;){let e=n.get(i.parentIndex);if(!e||"Toolbar"!==e.label)return;r.add(e.index),i=e}}(n,e,t),pL(e,r,i.index,t))}})(e,o),r=e,n=o,pT(r,(e,t,i)=>{pS(r,i).find(r=>{let n;return("button"===(n=rr(r.type??""))||"link"===n||"switch"===n||"searchfield"===n||"textfield"===n)&&r.label?.trim()===t&&(pD(r.rect,e.rect)||function(e,t){var r,n,i,a,o;let s;if(t.label?.trim()!==e.label?.trim())return!1;let l=rr(t.type??"");return r=e,n=l,s=r.label?.trim(),"button"===n&&("Dismiss"===s||"Back"===s)||"textfield"===l||(i=e,a=l,o=t,"button"===a&&!!i.rect&&!!o.rect&&0===i.rect.x&&0===i.rect.y&&i.rect.width>=300&&i.rect.height>=600&&o.rect.width<i.rect.width)}(e,r))})&&n.add(e.index)}),i=e,a=o,pT(i,(e,t,r)=>{var n;ty(t)&&(n=e.rect)&&n.x<=1&&n.y<=1&&n.width>=300&&n.height>=600&&pS(i,r).some(e=>{var r;return e.label?.trim()===t&&!!(r=e).rect&&r.rect.width>=120&&r.rect.height>=36&&r.rect.height<=180})&&a.add(e.index)}),function(e,t){for(let r=0;r<e.length;r+=1){let n=e[r],i=n?.label?.trim();!(!n||t.has(n.index))&&i&&function(e,t,r,n,i){let a=pS(e,t),o=rr(r.type??"");if("statictext"===o||"link"===o)return pE(a,n,i);if("other"===o){if(function(e,t){return e.some(e=>{let r=rr(e.type??"");return("link"===r||"searchfield"===r||pM(e.type))&&e.label?.trim()===t})}(a,n))return i.add(r.index);pE(a,n,i)}}(e,r,n,i,t)}}(e,o)},function(e,t){let r=new Map(e.map(e=>[e.index,e])),n=pO(r.values());for(let i of e)(function(e,t,r){var n;return!("other"!==rr(e.type??"")||!1===e.enabled||!e.rect||!function(e){let t=e?.trim();return!(!t||/^(toolbar|window|application)$/i.test(t)||t.startsWith("!,")||/debugger|fast refresh/i.test(t))}(e.label)||!px(e,t,pR)||!((n=e).rect&&n.rect.height>=44&&n.rect.height<=160&&n.rect.width>=120)||function(e,t,r=.8){let n=pP(e),i=pP(t);return n>0&&i>0&&n/i>=r}(e.rect,r))})(i,r,n)&&pk(t.replacements,i,{type:"Cell"})},function(e,t){for(let r=0;r<e.length;r+=1){let n=e[r],i=n?.label?.trim();n?.rect&&i&&function(e,t,r,n,i){let a=pS(e,t),o=rr(r.type??"");"button"===o?p$(a,n,i.suppressedIndexes,r):"cell"!==o||!function(e,t,r,n){let i=e.find(e=>(function(e,t,r){if("switch"!==rr(e.type??""))return!1;let n=t.identifier?.trim(),i=e.identifier?.trim();return!!n&&!!i&&n===i||e.label?.trim()===r})(e,t,r));if(!i)return!1;let a=e.find(e=>pF(e,t,r)),o=i.identifier?void 0:a?.identifier??t.identifier;return o&&pk(n.replacements,i,{identifier:o}),n.suppressedIndexes.add(t.index),function(e,t,r,n,i){for(let a of e)a.index!==n.index&&(pF(a,t,r)||pU(a,t)||function(e,t){if("switch"!==rr(e.type??"")||e.index===t.index)return!1;let r=e.label?.trim();return r===t.value?.trim()||"0"===r||"1"===r}(a,n)||p_(a,r))&&i.add(a.index)}(e,t,r,i,n.suppressedIndexes),!0}(a,r,n,i)&&function(e,t,r,n){let i=e.find(e=>pF(e,t,r));if(!i){e.some(pN)&&p$(e,r,n.suppressedIndexes,t);return}!t.identifier&&i.identifier&&pk(n.replacements,t,{identifier:i.identifier}),n.suppressedIndexes.add(i.index),p$(e.filter(e=>e.index!==i.index),r,n.suppressedIndexes,t)}(a,r,n,i)}(e,r,n,i,t)}}];async function pG(e){if(("ios"===e.device.platform||"android"===e.device.platform)&&e.session?.postGestureStabilization)return{snapshot:await pv({session:e.session,capture:async()=>(await pj(e)).snapshot})};let t=pf(e.session);if(t&&"android"===e.device.platform)return await pB(e,t);let r=await pq(e);return pm(e.session),{snapshot:pz(r,pH(e)),analysis:r.analysis,androidSnapshot:r.androidSnapshot}}async function pq(e){let{device:t,session:r,flags:n,outPath:i,logPath:a,snapshotScope:o}=e;if("linux"===t.platform){let e=await ce(r?.surface);return pK({nodes:e.nodes,truncated:e.truncated,backend:"linux-atspi"},{snapshotDepth:n?.snapshotDepth,snapshotInteractiveOnly:n?.snapshotInteractiveOnly,snapshotScope:o})}return"macos"===t.platform&&r?.surface&&"app"!==r.surface?pK(await uy(r.surface,{bundleId:"menubar"===r.surface?r.appBundleId:void 0}),{snapshotDepth:n?.snapshotDepth,snapshotInteractiveOnly:n?.snapshotInteractiveOnly,snapshotScope:o}):await cF(t,"snapshot",[],i,{...pg(a,{...n,snapshotScope:o},r?.appBundleId,r?.trace?.outPath)})}async function pB(e,t){let r=await pj(e),n=pW(r,t,e),i=0,a=t.markedAt+1500;for(let o of pc){if(!n)break;let s=a-Date.now();if(s<=0)break;await e8(Math.min(o,s)),r=await pj(e),i+=1,n=pW(r,t,e)}return n||pm(e.session),{snapshot:r.snapshot,analysis:r.data.analysis,androidSnapshot:r.data.androidSnapshot,freshness:i>0||n?{action:t.action,retryCount:i,staleAfterRetries:!!n,reason:n??void 0}:void 0}}async function pj(e){let t=await pq(e);return{data:t,snapshot:pz(t,pH(e))}}function pH(e){return void 0===e.snapshotScope?e.flags:{...e.flags,snapshotScope:e.snapshotScope}}function pW(e,t,r){var n,i;let a=r.flags?.snapshotInteractiveOnly===!0,o=e.data.analysis;if(a&&0===e.snapshot.nodes.length&&o&&o.rawNodeCount>=12)return"empty-interactive";if("ref-refresh"===r.androidFreshnessMode)return null;return(n=t.baselineCount,i=e.snapshot.nodes.length,!(n<12)&&i<=Math.floor(.2*n))?e.snapshot.nodes.some(e=>!0===e.hittable||!!e.label?.trim()||!!e.value?.trim()||!!e.identifier?.trim())?null:"sharp-drop":t.routeComparable&&ph(t.action)&&function(e,t){if(!e||0===e.length)return!1;let r=Math.max(e.length,t.length);if(r<12)return!1;let n=pw(t),i=Math.min(e.length,n.length),a=0;for(let t=0;t<i;t+=1)e[t]===n[t]&&(a+=1);let o=Math.max(0,n.length-e.length),s=Math.max(0,e.length-n.length),l=Math.max(3,Math.floor(.15*r));return a>=Math.floor(.9*r)&&o<=l&&s<=l}(t.baselineSignatures,e.snapshot.nodes)?"stuck-route":null}function pz(e,t){var r,n,i,a;let o=e?.nodes??[],s=tU(t?.snapshotRaw?o:ri(o)),l=t?.snapshotScope&&e?.backend!=="macos-helper"?pJ(s,t.snapshotScope):s;return{nodes:tY((r=e?.backend,n=t,"xctest"===r&&n?.snapshotInteractiveOnly===!0&&!0!==n.snapshotRaw)?function(e){if(0===e.length)return e;let t=new Map,r=new Set;for(let n of pV)n(e,{replacements:t,suppressedIndexes:r});if(0===r.size&&0===t.size)return e;var n=e.filter(e=>!r.has(e.index)).map(e=>t.get(e.index)??e);let i=new Map(e.map(e=>[e.index,e])),a=new Map;for(let[e,t]of n.entries())a.set(t.index,e);return n.map((e,t)=>{let n="number"==typeof e.parentIndex?a.get(e.parentIndex):void 0;return void 0===n&&"number"==typeof e.parentIndex&&(n=function(e,t,r,n){let i=e,a=new Set;for(;"number"==typeof i&&!a.has(i);){if(a.add(i),!t.has(i))return n.get(i);i=r.get(i)?.parentIndex}}(e.parentIndex,r,i,a)),{...e,index:t,parentIndex:n}})}(l):l),truncated:e?.truncated,createdAt:Date.now(),backend:e?.backend,presentationKey:tX(tz(t)),comparisonSafe:(i=e?.backend,a=t,"android"===i&&a?.snapshotInteractiveOnly!==!0&&a?.snapshotCompact!==!0&&"number"!=typeof a?.snapshotDepth&&!a?.snapshotScope)}}function pK(e,t){var r,n;let i=e.nodes??[];return t.snapshotScope&&(i=pJ(i,t.snapshotScope)),t.snapshotInteractiveOnly&&(i=function(e){if(0===e.length)return e;let t=new Map;for(let r of e)t.set(r.index,r);let r=new Set;for(let n of e){if(!function(e){if(e.focused||e.hittable||e.rect)return!0;let t=`${e.type??""} ${e.role??""} ${e.subrole??""}`.toLowerCase();return t.includes("button")||t.includes("menu")||t.includes("textfield")||t.includes("searchfield")||t.includes("checkbox")||t.includes("radio")||t.includes("switch")}(n))continue;let e=n;for(;e&&!r.has(e.index);)r.add(e.index),e="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0}return 0===r.size?e:pX(e.filter(e=>r.has(e.index)))}(i)),"number"==typeof t.snapshotDepth&&(r=i,n=t.snapshotDepth,i=pX(r.filter(e=>(e.depth??0)<=n))),{...e,nodes:i}}function pJ(e,t){let r=t8(tY(e),t);if(!r)return[];let n=e.findIndex(e=>e.index===r.index);if(-1===n)return[];let i=e[n]?.depth??0,a=[];for(let t=n;t<e.length;t+=1){let r=e[t];if(!r)continue;let o=r.depth??0;if(t>n&&o<=i)break;a.push(r)}return pX(a,i)}function pX(e,t=0){let r=new Map;for(let[t,n]of e.entries())r.set(n.index,t);return e.map((e,n)=>({...e,index:n,depth:Math.max(0,(e.depth??0)-t),parentIndex:"number"==typeof e.parentIndex?r.get(e.parentIndex):void 0}))}function pZ(e,t){e.snapshot=t,e.snapshotScopeSource=void 0}function pY(e){return{get:t=>t===e.sessionName?function(e,t,r={}){if(e)return{name:t,appBundleId:e.appBundleId,appName:e.appName,...!0===r.includeSnapshot?{snapshot:e.snapshot}:{},metadata:{surface:e.surface,...r.metadata??{}}}}(e.getSession(),e.sessionName,e.recordOptions):void 0,set:t=>{t.name!==e.sessionName?eN({level:"warn",phase:"runtime_session_write_skipped",data:{expected:e.sessionName,received:t.name}}):e.setRecord(t)}}}async function pQ(e){let{session:t,sessionName:r,outPath:n,outputPlacement:i,dispatchContext:a}=e,o=tG({backend:function(e){let{session:t,outputPlacement:r,dispatchContext:n}=e;return{platform:t.device.platform,captureScreenshot:async(e,i,a)=>{let o={...n,...eY(a),surface:a?.surface};return"out"===r?p0(await cF(t.device,"screenshot",[],i,o)):p0(await cF(t.device,"screenshot",[i],void 0,o))}}}({session:t,outputPlacement:i,dispatchContext:a}),artifacts:{resolveInput:async()=>{throw new D("UNSUPPORTED_OPERATION","screenshot does not resolve input artifacts")},reserveOutput:async e=>{let t,r;return e?.kind==="path"?r=e.path:(t=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-screenshot-")),r=f.join(t,"screenshot.png")),await d.mkdir(f.dirname(r),{recursive:!0}),{path:r,visibility:"client-visible",publish:async()=>void 0,...t?{cleanup:async()=>{await d.rm(t,{recursive:!0,force:!0})}}:{}}},createTempFile:async e=>{let t=await d.mkdtemp(f.join(c.tmpdir(),`${e.prefix}-`));return{path:f.join(t,`file${e.ext}`),visibility:"internal",cleanup:async()=>{await d.rm(t,{recursive:!0,force:!0})}}}},sessions:pY({sessionName:r,getSession:()=>t,recordOptions:{includeSnapshot:!1},setRecord:()=>{}}),policy:tO()});return await o.capture.screenshot({session:r,requestId:a.requestId,appBundleId:t.appBundleId,...eX(a),surface:t.surface,...n?{out:{kind:"path",path:n}}:{}})}function p0(e){if("object"==typeof e&&null!==e)return{..."string"==typeof e.path?{path:e.path}:{},...Array.isArray(e.overlayRefs)?{overlayRefs:e.overlayRefs}:{}}}let p1=/\bis(?:n(?:'|&apos;|&#39;)?t| not)\s+responding\b/i,p2=/^close app$/i,p3="Wait for Android to recover, close the dialog, restart the app, or reboot the emulator, then retry.";async function p5(e){let{session:t}=e;if("android"!==t.device.platform||!t.recording)return"absent";try{let e=await fe(t),r=fr(e);if(!r?.rect)return"absent";let n=await ft(t,r);if(!n.ok)return eN({level:"warn",phase:"android_blocking_dialog_tap_failed",data:{session:t.name,deviceId:t.device.id,exitCode:n.exitCode,stdout:n.stdout.trim(),stderr:n.stderr.trim()}}),"failed";if(!await fn(t))return eN({level:"warn",phase:"android_blocking_dialog_still_present",data:{session:t.name,deviceId:t.device.id}}),"failed";if(t.appBundleId&&(await B(t.device,t.appBundleId),!await fi(t,t.appBundleId)))return eN({level:"warn",phase:"android_blocking_dialog_relaunch_unfocused",data:{session:t.name,deviceId:t.device.id,appBundleId:t.appBundleId}}),"failed";return eN({level:"warn",phase:"android_blocking_dialog_recovered",data:{session:t.name,deviceId:t.device.id,appBundleId:t.appBundleId,x:n.x,y:n.y}}),"recovered"}catch(e){return eN({level:"warn",phase:"android_blocking_dialog_recovery_failed",data:{session:t.name,deviceId:t.device.id,error:e instanceof Error?e.message:String(e)}}),"failed"}}async function p4(e){var t,r;let{session:n,command:i}=e;if("android"!==n.device.platform)return{status:"clear"};let a=await T(n.device);if(!a)return{status:"clear"};if(t=n,r=a,t.appBundleId&&r.package===t.appBundleId){if(await p8(n)){let t=`Recovered Android app ANR before ${i}: closed and relaunched ${n.appBundleId}.`;if("before-command"===e.phase)return{status:"recovered",warning:t};throw p9({session:n,command:i,focus:a,message:`Android app ANR appeared after ${i}; ${n.appBundleId} was closed and relaunched. Retry the command against the fresh app session.`,hint:"Retry the command. If the ANR returns, inspect app logs or restart the emulator."})}throw p9({session:n,command:i,focus:a,message:`Android app ANR blocked ${i}: ${p7(a)}. Automatic recovery failed.`,hint:p3})}throw p9({session:n,command:i,focus:a,message:`Android system dialog is blocking ${i}: ${p7(a)}.`,hint:p3})}async function p8(e){try{return await p6(e)}catch(t){return eN({level:"warn",phase:"android_app_anr_recovery_failed",data:{session:e.name,deviceId:e.device.id,appBundleId:e.appBundleId,error:t instanceof Error?t.message:String(t)}}),!1}}async function p6(e){if(!e.appBundleId)return!1;let t=fr(await fe(e),{requireDialogSignal:!1});if(!t?.rect)return!1;let r=await ft(e,t);if(!r.ok)return!1;await B(e.device,e.appBundleId);let n=await fi(e,e.appBundleId,{requireNoBlockingDialog:!0});return n&&eN({level:"warn",phase:"android_app_anr_recovered",data:{session:e.name,deviceId:e.device.id,appBundleId:e.appBundleId,x:r.x,y:r.y}}),n}function p9(e){let{session:t,command:r,focus:n,message:i,hint:a}=e;return new D("COMMAND_FAILED",i,{command:r,expectedPackage:t.appBundleId,focusedPackage:n.package,focusedWindow:n.focusedWindow,rawFocus:n.raw,hint:a})}function p7(e){return e.package?`${e.focusedWindow} (package ${e.package})`:e.focusedWindow}async function fe(e){return tY(ri((await sS(e.device,{interactiveOnly:!1,compact:!1})).nodes))}async function ft(e,t){if(!t.rect)return{ok:!1,exitCode:1,stdout:"",stderr:"button has no rect"};let{x:r,y:n}=tZ(t.rect),i=await Z(e.device,["shell","input","tap",String(Math.round(r)),String(Math.round(n))],{allowFailure:!0});return 0!==i.exitCode?{ok:!1,exitCode:i.exitCode,stdout:i.stdout.trim(),stderr:i.stderr.trim()}:{ok:!0,x:r,y:n}}function fr(e,t={}){if(!1===t.requireDialogSignal||fs(e))return e.find(e=>fo(e).some(e=>p2.test(e))&&e.rect)}async function fn(e){for(let t=0;t<12;t+=1){if(!fs(await fe(e)))return!0;await e8(500)}return!fs(await fe(e))}async function fi(e,t,r={}){for(let n=0;n<12;n+=1){if(await fa(e,t,r))return!0;await e8(500)}return await fa(e,t,r)}async function fa(e,t,r){return!(r.requireNoBlockingDialog&&await T(e.device))&&(await eu(e.device)).package===t}function fo(e){let t=[e.label,e.identifier];return"string"==typeof e.value&&e.value.trim().length>0&&t.push(e.value),t.filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim())}function fs(e){return e.some(e=>{let t=fo(e).join(" ").trim();return t.length>0&&p1.test(t)})}function fl(e){return!!(e&&e.width>0&&e.height>0)}function fu(e){return e.width*e.height}function fd(e,t){return t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height}let fc=[255,59,48,255],fp=[255,214,10,255],ff=[0,0,0,255],fm=["scroll","list","recyclerview","edittext","textfield"],fh=["button","link","menu","tab","textfield","searchfield","securetextfield","checkbox","radio","switch","cell"],fw={e:["01110","10000","11110","10000","10000","10001","01110"],0:["01110","10001","10011","10101","11001","10001","01110"],1:["00100","01100","00100","00100","00100","00100","01110"],2:["01110","10001","00001","00010","00100","01000","11111"],3:["11110","00001","00001","01110","00001","00001","11110"],4:["00010","00110","01010","10010","11111","00010","00010"],5:["11111","10000","10000","11110","00001","00001","11110"],6:["01110","10000","10000","11110","10001","10001","01110"],7:["11111","00001","00010","00100","01000","01000","01000"],8:["01110","10001","10001","01110","10001","10001","01110"],9:["01110","10001","10001","01111","00001","00001","01110"]};async function fg(e){let t=tH(await d.readFile(e.screenshotPath),"screenshot"),r=function(e,t,r,n={}){let i=function(e){let t=null;for(let r of e)fv(r)&&fl(r.rect)&&(!t||fu(r.rect)>fu(t))&&(t=r.rect);return t||function(e){let t=1/0,r=1/0,n=-1/0,i=-1/0;for(let a of e)a.rect&&fl(a.rect)&&(t=Math.min(t,a.rect.x),r=Math.min(r,a.rect.y),n=Math.max(n,a.rect.x+a.rect.width),i=Math.max(i,a.rect.y+a.rect.height));return!Number.isFinite(t)||!Number.isFinite(r)||n<=t||i<=r?null:{x:t,y:r,width:n-t,height:i-r}}(e.filter(e=>{var t;return fl(e.rect)&&!("image"===rr((t=e).type??"")&&!fb(t.label))}))}(e.nodes),a=new Map;for(let n of e.nodes){var o,s;if(!function(e,t,r){let n=[r.label,r.value].some(fA)||fS(r.identifier);return!!function(e,t,r){if("android"!==e.backend||!r.hittable||!fl(r.rect)||fv(r))return!1;let n=rr(r.type??"");return!(fm.some(e=>n.includes(e))||t&&fu(r.rect)>.25*fu(t))}(e,t,r)||(fy(r)?n:n&&function(e){let t=rr(e.type??"");return t.includes("statictext")||t.includes("image")||t.includes("text")||t.includes("other")}(r))}(e,i,n))continue;let l=(o=e.nodes,[function(e){return fy(e)&&!fv(e)}(s=n)?s:null,t7(o,s,e=>(function(e){return fy(e)&&!fv(e)})(e)),s.hittable?s:null,t7(o,s,e=>!0===e.hittable)].find(fI)??null);if(!l?.rect||!fl(l.rect))continue;let u=function(e,t,r){let n=fx(e);if(e.ref!==t.ref&&n)return n;let i=function(e,t){let r=null;for(let n of t){if(n.ref===e.ref||!function(e,t,r){let n=e;for(;void 0!==n.parentIndex;){let e=r[n.parentIndex];if(!e)break;if(e.ref===t.ref)return!0;n=e}return!1}(n,e,t))continue;let i=fx(n);if(!i)continue;let a=function(e){let t=0;return rr(e.type??"").includes("text")&&(t+=2),fA(e.label)&&(t+=2),fA(e.value)&&(t+=1),t}(n);(!r||a>r.score)&&(r={label:i,score:a})}return r?.label}(t,r);return i||fx(t)}(n,l,e.nodes),d=function(e,t,r){let n=0;return e.ref===t.ref&&(n+=4),t.hittable&&(n+=3),fy(t)&&(n+=3),fy(e)&&(n+=2),r&&(n+=2),fS(t.identifier)&&(n+=1),fb(t.value)&&(n+=1),n}(n,l,u),c=function(e,t,r){var n,i;return"android"!==e.backend?t.rect:(n=fy,i=e=>!!fx(e),(!t.rect||!0!==t.hittable||n(t)||i(t)?null:function(e,t,r){let n=e.rect,i=function(e,t,r){let n=e.rect,i=new Map(t.map(e=>[e.index,e])),a=t.filter(t=>t.ref!==e.ref&&function(e,t,r){let n=e;for(;void 0!==n.parentIndex;){let e=r.get(n.parentIndex);if(!e)break;if(e.ref===t.ref)return!0;n=e}return!1}(t,e,i)&&function(e,t){let r=rr(e.type??"");return r.includes("text")||r.includes("image")&&t(e)}(t,r)&&fl(t.rect)&&fd(n,t.rect)).map(e=>e.rect);return a.length<2?null:function(e){let t=e[0];if(void 0===t)throw Error("unionRects requires at least one rect");let r=t.x,n=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))r=Math.min(r,t.x),n=Math.min(n,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:r,y:n,width:i-r,height:a-n}}(a)}(e,t,r);if(!i)return null;let a=i.y-n.y,o=n.y+n.height-(i.y+i.height);if(a<0||o<0||16>Math.abs(o-a))return null;let s=Math.min(a,o),l=Math.round(i.y-s),u=Math.round(i.height+2*s);return u<=0||u>=n.height?null:{x:n.x,y:l,width:n.width,height:u}}(t,r,i))??t.rect)}(e,l,e.nodes),p=function(e,t,r,n,i){if("android"===e.backend||!t)return f_(function(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}(r),n,i);let a=n/t.width,o=i/t.height;return f_({x:Math.round((r.x-t.x)*a),y:Math.round((r.y-t.y)*o),width:Math.max(1,Math.round(r.width*a)),height:Math.max(1,Math.round(r.height*o))},n,i)}(e,i,c,t,r);if(!fl(p))continue;let f=a.get(l.ref);(!f||d>f.score)&&a.set(l.ref,{ref:l.ref,label:u,rect:l.rect,overlayRect:p,score:d})}return(function(e){let t=[];for(let r of e.sort((e,t)=>fu(e.overlayRect)-fu(t.overlayRect))){let e=t.findIndex(e=>void 0!==e.label&&e.label===r.label&&(fd(e.overlayRect,r.overlayRect)||fd(r.overlayRect,e.overlayRect)));if(-1===e){t.push(r);continue}fu(r.overlayRect)<fu(t[e].overlayRect)&&(t[e]=r)}return t})([...a.values()]).sort(fP).slice(0,n.maxRefs??24).sort(fO).map(e=>({ref:e.ref,label:e.label,rect:e.rect,overlayRect:e.overlayRect,center:tZ(e.overlayRect)}))}(e.snapshot,t.width,t.height,{maxRefs:e.maxRefs});for(let e of r){var n,i;(function(e,t,r){for(let n=0;n<2;n+=1)fM(e,t.x,t.x+t.width-1,t.y+n,r),fM(e,t.x,t.x+t.width-1,t.y+t.height-1-n,r),fk(e,t.x+n,t.y,t.y+t.height-1,r),fk(e,t.x+t.width-1-n,t.y,t.y+t.height-1,r)})(n=t,(i=e).overlayRect,fc),function(e,t,r){let n=6+5*r.length+ +Math.max(0,r.length-1),i=fN(t.x,0,Math.max(0,e.width-n)),a=t.y-11-2,o=a>=0?a:fN(t.y+2,0,Math.max(0,e.height-11));(function(e,t,r,n,i){for(let a=0;a<11;a+=1)for(let o=0;o<n;o+=1)fD(e,t+o,r+a,i)})(e,i,o,n,fp),function(e,t,r,n,i){let a=t;for(let t of n.toLowerCase()){let n=fw[t];if(n)for(let t=0;t<n.length;t+=1)for(let o=0;o<n[t].length;o+=1)"1"===n[t][o]&&fD(e,a+o,r+t,i);a+=6}}(e,i+3,o+2,r,ff)}(n,i.overlayRect,i.ref)}return await d.writeFile(e.screenshotPath,tN.sync.write(t)),r}function fy(e){let t=[e.type,e.role,e.subrole].map(e=>rr(e??"")).join(" ");return fh.some(e=>t.includes(e))}function fv(e){let t=[e.type,e.role,e.subrole].map(e=>rr(e??"")).join(" ");return t.includes("application")||t.includes("window")}function fI(e){return!!(e?.rect&&fl(e.rect)&&!fv(e))}function fb(e){if("string"!=typeof e)return!1;let t=e.trim();return!(!t||/^(true|false)$/i.test(t))}function fA(e){var t;let r;return!!fb(e)&&(t=e,"toolbar"!==(r=t?.trim().toLowerCase())&&"window"!==r&&"application"!==r&&r?.startsWith("vertical scroll bar")!==!0)}function fS(e){var t;return"string"==typeof e&&!!fA(e)&&(t=e,!/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(t.trim()))}function fx(e){let t=[e.label,e.value].find(fA);return t?t.trim():fS(e.identifier)?e.identifier.trim():void 0}function f_(e,t,r){let n=fN(e.x,0,Math.max(0,t-1)),i=fN(e.y,0,Math.max(0,r-1)),a=Math.max(1,t-n),o=Math.max(1,r-i);return{x:n,y:i,width:fN(e.width,1,a),height:fN(e.height,1,o)}}function fN(e,t,r){return Number.isFinite(e)?Math.max(t,Math.min(r,e)):t}function fM(e,t,r,n,i){for(let a=t;a<=r;a+=1)fD(e,a,n,i)}function fk(e,t,r,n,i){for(let a=r;a<=n;a+=1)fD(e,t,a,i)}function fD(e,t,r,n){if(t<0||r<0||t>=e.width||r>=e.height)return;let i=(e.width*r+t)*4;e.data[i]=n[0],e.data[i+1]=n[1],e.data[i+2]=n[2],e.data[i+3]=n[3]}function fO(e,t){var r,n;let i=e.overlayRect.y-t.overlayRect.y;if(0!==i)return i;let a=e.overlayRect.x-t.overlayRect.x;return 0!==a?a:(r=e.ref,n=t.ref,Number.parseInt(r.replace(/^\D+/,""),10)-Number.parseInt(n.replace(/^\D+/,""),10))}function fP(e,t){return t.score!==e.score?t.score-e.score:fO(e,t)}function fR(e){return"number"==typeof e.gestureClockOriginAtMs&&"number"==typeof e.gestureClockOriginUptimeMs&&"number"==typeof e.gestureStartUptimeMs?Math.max(0,e.gestureClockOriginAtMs+(e.gestureStartUptimeMs-e.gestureClockOriginUptimeMs)-e.recordingStartedAt):"number"==typeof e.runnerStartedAtUptimeMs&&"number"==typeof e.gestureStartUptimeMs?Math.max(0,e.gestureStartUptimeMs-e.runnerStartedAtUptimeMs):"number"==typeof e.gestureStartUptimeMs&&"number"==typeof e.gestureEndUptimeMs?Math.max(0,e.fallbackFinishedAtMs-(e.gestureEndUptimeMs-e.gestureStartUptimeMs)-e.recordingStartedAt):Math.max(0,e.fallbackStartedAtMs-e.recordingStartedAt)}let fC=new WeakMap;function fE(e){if(!e)return;let t=fC.get(e);if(t)return t;let r=function(e){let t=function(e){let t=e.filter(e=>(function(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("application")||t.includes("window")})(e.type)&&fL(e.rect)).map(e=>e.rect).sort((e,t)=>(t?.width??0)*(t?.height??0)-(e?.width??0)*(e?.height??0))[0];if(t)return t;let r=e.map(e=>e.rect).filter(fL);if(0===r.length)return;let n=Math.max(...r.map(e=>e.x+e.width)),i=Math.max(...r.map(e=>e.y+e.height));if(!(n<=0)&&!(i<=0))return{x:0,y:0,width:n,height:i}}(e);if(t)return{referenceWidth:t.width,referenceHeight:t.height}}(e.nodes??[]);if(r)return fC.set(e,r),r}function fL(e){return!!e&&e.width>0&&e.height>0}let fT={referenceWidth:1e3,referenceHeight:1e3};function f$(e,t,r,n,i={},a=Date.now(),o=Date.now()){var s,l,u,d,c,p,f,m,h;let w,g,y,v=e.recording;if(!v)return;let I={...i,...n??{}},b=fH(I.effectiveDurationMs)??fH(I.durationMs),A={recordingStartedAt:v.startedAt,gestureClockOriginAtMs:v.gestureClockOriginAtMs,gestureClockOriginUptimeMs:v.gestureClockOriginUptimeMs,runnerStartedAtUptimeMs:"ios-device-runner"===v.platform?v.runnerStartedAtUptimeMs:void 0,gestureStartUptimeMs:fH(I.gestureStartUptimeMs),gestureEndUptimeMs:fH(I.gestureEndUptimeMs),fallbackStartedAtMs:a,fallbackFinishedAtMs:o},S="number"==typeof(s={gestureStartUptimeMs:fH(I.gestureStartUptimeMs),gestureEndUptimeMs:fH(I.gestureEndUptimeMs),reportedDurationMs:b,fallbackStartedAtMs:a,fallbackFinishedAtMs:o}).gestureStartUptimeMs&&"number"==typeof s.gestureEndUptimeMs?Math.max(0,s.gestureEndUptimeMs-s.gestureStartUptimeMs):"number"==typeof s.reportedDurationMs?Math.max(0,s.reportedDurationMs):Math.max(0,s.fallbackFinishedAtMs-s.fallbackStartedAtMs),x="ios"===e.device.platform&&void 0===fH(I.gestureStartUptimeMs)&&function(e,t){switch(e){case"click":case"fill":case"focus":return!0;case"press":{let e=fW(fH(t.count),1)??1,r=!0===t.doubleTap,n=fW(fH(t.holdMs),1);return 1===e&&!r&&void 0===n}case"react-native":return"dismiss-overlay"===t.action;default:return!1}}(t,I)?function(e){let t=Math.max(0,e.gestureDurationMs);if(t<600)return fR(e);let r=Math.min(Math.max(.15*t,120),260);return Math.max(0,e.fallbackFinishedAtMs-r-e.recordingStartedAt)}({...A,gestureDurationMs:S}):fR(A),_=(l=e.snapshot,w=fH((u=I).referenceWidth),g=fH(u.referenceHeight),void 0!==w&&w>0&&void 0!==g&&g>0?{referenceWidth:w,referenceHeight:g}:fE(l)),N=(d=t,c=r,p=I,f=x,m=S,h=_,y=fF[d],y?.(c,p,f,m,h)??[]);0!==N.length&&(v.gestureEvents.push(...N),eN({level:"debug",phase:"record_touch_visualization_event",data:{session:e.name,command:t,count:N.length,tMs:x,gestureDurationMs:S,kinds:N.map(e=>e.kind)}}))}let fF={click:(e,t,r,n,i)=>fU(e,t,r,i),press:(e,t,r,n,i)=>fU(e,t,r,i),"react-native":(e,t,r,n,i)=>"dismiss-overlay"===e[0]?fU(e,t,r,i):[],fill:(e,t,r,n,i)=>fV(e,t,r,i),focus:(e,t,r,n,i)=>fV(e,t,r,i),longpress:function(e,t,r,n,i){let a=fz(t,e);if(!a)return[];let{x:o,y:s}=a;return[fB(r,o,s,fX(n,[fH(t.durationMs),fH(e[2])],800),i)]},scroll:function(e,t,r,n,i){let a=fK(t,e),o=fj(t.contentDirection)??fj(t.direction);if(!a||!o)return[];let{x1:s,y1:l,x2:u,y2:d}=a,c=fX(n,[],250),p=fH(t.amount)??fH(e[1]),f=fH(t.pixels);return[{kind:"scroll",tMs:r,x:s,y:l,x2:u,y2:d,...i,durationMs:c,contentDirection:o,...void 0!==p?{amount:p}:{},...void 0!==f?{pixels:f}:{}}]},pan:fG,fling:fG,swipe:fG,pinch:function(e,t,r,n,i){let a=fz(t,e,1),o=fH(t.scale)??fH(e[0]);if(!a||void 0===o||o<=0)return[];let{x:s,y:l}=a;return[{kind:"pinch",tMs:r,x:s,y:l,...i,scale:o,durationMs:fX(n,[],280)}]}};function fU(e,t,r,n){let i=fz(t,e);if(!i)return[];let{x:a,y:o}=i,s=fW(fH(t.count),1)??1,l=fW(fH(t.intervalMs),0)??0,u=!0===t.doubleTap,d=fW(fH(t.holdMs),1),c=[];for(let e=0;e<s;e+=1){let t=r+e*l;if(void 0!==d&&d>0){c.push(fB(t,a,o,d,n));continue}c.push(fq(t,a,o,n)),u&&c.push(fq(t+90,a,o,n))}return c}function fV(e,t,r,n){let i=fz(t,e);if(!i)return[];let{x:a,y:o}=i;return[fq(r,a,o,n)]}function fG(e,t,r,n,i){let a=fK(t,e);if(!a)return[];let{x1:o,y1:s,x2:l,y2:u}=a,d=fX(n,[fH(t.effectiveDurationMs),fH(t.durationMs),fH(e[4])],250),c=fW(fH(t.count),1)??1,p=fW(fH(t.pauseMs),0)??0,f="ping-pong"===t.pattern?"ping-pong":"one-way";return Array.from({length:c},(e,t)=>{var n,a,c,m,h,w,g,y,v,I,b,A,S;let x,{startX:_,startY:N,endX:M,endY:k}=(n=t,a=f,c=o,m=s,h=l,w=u,"ping-pong"===a&&n%2==1?{startX:h,startY:w,endX:c,endY:m}:{startX:c,startY:m,endX:h,endY:w});return g=r+t*(d+p),y=_,v=N,I=M,b=k,A=d,"back-swipe"===(x=function(e,t,r,n,i){if(!i||Math.abs(r-e)<=1.25*Math.abs(n-t))return"swipe";let a=.08*i.referenceWidth;return e<=a&&r>e||e>=i.referenceWidth-a&&r<e?"back-swipe":"swipe"}(y,v,I,b,S=i))?{kind:x,tMs:g,x:y,y:v,x2:I,y2:b,...S,durationMs:A,edge:function(e,t,r){if(r){let t=.08*r.referenceWidth;if(e<=t)return"left";if(e>=r.referenceWidth-t)return"right"}return t>=e?"left":"right"}(y,I,S)}:{kind:x,tMs:g,x:y,y:v,x2:I,y2:b,...S,durationMs:A}})}function fq(e,t,r,n){return{kind:"tap",tMs:e,x:t,y:r,...n}}function fB(e,t,r,n,i){return{kind:"longpress",tMs:e,x:t,y:r,...i,durationMs:n}}function fj(e){if("string"!=typeof e)return;let t=e.trim().toLowerCase();switch(t){case"up":case"down":case"left":case"right":return t;default:return}}function fH(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"!=typeof e||0===e.trim().length)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function fW(e,t){if(void 0===e)return;let r=Math.floor(e);return r>=t?r:void 0}function fz(e,t,r=0){let n=fH(e.x)??fH(t[r]),i=fH(e.y)??fH(t[r+1]);if(void 0!==n&&void 0!==i)return{x:n,y:i}}function fK(e,t){let r=fJ(e.x1,e.x,t[0]),n=fJ(e.y1,e.y,t[1]),i=fJ(e.x2,t[2]),a=fJ(e.y2,t[3]);if(void 0!==r&&void 0!==n&&void 0!==i&&void 0!==a)return{x1:r,y1:n,x2:i,y2:a}}function fJ(...e){return e.map(fH).find(e=>void 0!==e)}function fX(e,t,r){return fW(e,1)??t.map(e=>fW(e,1)).find(e=>void 0!==e)??r}let fZ={pan:"pan",fling:"fling",pinch:"pinch",rotate:"rotate-gesture",transform:"transform-gesture"};async function fY(e){var t,r,n,i,a,o,s,l;let u,d,c,p,f,{req:m,session:h,logPath:w,sessionStore:g,contextFromFlags:y}=e,v=function(e){if("pan"===e.command||"fling"===e.command||"rotate-gesture"===e.command||"transform-gesture"===e.command)return{ok:!1,message:"Use gesture pan, gesture fling, gesture rotate, or gesture transform."};if("gesture"!==e.command)return{ok:!0,platformCommand:e.command,dispatchRequest:e,recordedCommand:e.command};let[t,...r]=e.positionals??[],n=t?fZ[t]:void 0;return n?{ok:!0,platformCommand:n,dispatchRequest:{...e,command:n,positionals:r},recordedCommand:e.command}:{ok:!1,message:e$}}(m);if(!v.ok)return{ok:!1,error:{code:"INVALID_ARGS",message:v.message}};let{platformCommand:I,dispatchRequest:b,recordedCommand:A}=v,S=await f0(h,I);if(S)return S;let x=await fQ(h,I);if("response"in x)return x.response;let{resolvedPositionals:_,resolvedOut:N,recordedPositionals:M,recordedFlags:k}="screenshot"===(t=b).command?(d=(n=(r=t).positionals??[],i=r.meta?.cwd,(u=n[0])?[i4.expandHome(u,i),...n.slice(1)]:n),p=(c=(a=r.flags?.out,o=r.meta?.cwd,a?i4.expandHome(a,o):a))?{...r.flags??{},out:c}:r.flags??{},{resolvedPositionals:d,resolvedOut:c,recordedPositionals:d,recordedFlags:p}):{resolvedPositionals:f=(s=t).positionals??[],resolvedOut:s.flags?.out,recordedPositionals:f,recordedFlags:s.flags??{}},D=Date.now(),O={...y(m.flags,h.appBundleId,h.trace?.outPath),surface:h.surface},P=await f1({session:h,sessionName:e.sessionName,logPath:w,command:I,request:b,positionals:_,out:N,dispatchContext:O}),R=await fQ(h,I,"after-command");if("response"in R)return R.response;"status"in x&&"recovered"===x.status&&(!P||"object"==typeof P)&&((P??={}).warning=x.warning);let C=Date.now(),E=A===I?M:m.positionals??[],L=A===I?k:m.flags??{};return function(e){let{session:t,sessionStore:r,command:n,recordedCommand:i,resolvedPositionals:a,recordedPositionals:o,recordedFlags:s,data:l,actionStartedAt:u,actionFinishedAt:d,flags:c}=e,p=function(e,t,r,n){if("scroll"!==t)return n;let i=fE(e.snapshot),a={...n??{}},o=fj(a.direction)??fj(r[0]);if(!o)return n;let s=fH(a.amount)??fH(r[1]),l=fH(a.pixels),u=fK(a,[]),d=fH(a.referenceWidth),c=fH(a.referenceHeight),p=void 0!==d&&d>0&&void 0!==c&&c>0?{referenceWidth:d,referenceHeight:c}:i??fT;if(u&&(u.x1!==u.x2||u.y1!==u.y2))return{...a,x1:u.x1,y1:u.y1,x2:u.x2,y2:u.y2,contentDirection:o,...void 0!==s?{amount:s}:{},...void 0!==l?{pixels:l}:{},referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight,durationMs:250};let f=sg({direction:o,amount:s,pixels:l,referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight});return{...a,x1:f.x1,y1:f.y1,x2:f.x2,y2:f.y2,contentDirection:o,...void 0!==s?{amount:s}:{},...void 0!==f.pixels?{pixels:f.pixels}:{},referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight,durationMs:250}}(t,n,a,l);f$(t,n,a,p,c,u,d),r.recordAction(t,{command:i,positionals:o,flags:s,result:l??{}})}({session:h,sessionStore:g,command:I,recordedCommand:A,resolvedPositionals:_,recordedPositionals:E,recordedFlags:L,data:P,actionStartedAt:D,actionFinishedAt:C,flags:m.flags??{}}),ph(I)&&pp(h,I),pI(h.device.platform)&&("swipe"===(l=I)||"scroll"===l)&&(h.postGestureStabilization={action:I,markedAt:Date.now()}),{ok:!0,data:P??{}}}async function fQ(e,t,r="before-command"){if("android"!==e.device.platform||!ek.androidBlockingDialogGuardedAction.has(t))return{status:"clear"};try{return await p4({session:e,command:t,phase:r})}catch(e){return{response:{ok:!1,error:k(e)}}}}async function f0(e,t){return pd(t,e.device)?"android"===e.device.platform&&e.recording&&"record"!==t&&await p5({session:e})==="failed"?{ok:!1,error:{code:"COMMAND_FAILED",message:"Android system dialog blocked the recording session"}}:null:{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:`${t} is not supported on this device`}}}async function f1(e){var t;let{session:r,command:n,request:i,positionals:a,out:o,dispatchContext:s}=e;if("screenshot"!==n)return await cF(r.device,n,a,o,{...s});let l=await pQ({session:r,sessionName:e.sessionName,outPath:a[0]??o,outputPlacement:"screenshot"!==(t=i).command?"default":(t.positionals??[])[0]?"positional":t.flags?.out?"out":"default",dispatchContext:s});return i.flags?.overlayRefs&&"string"==typeof l?.path&&await f2(r,l,e.logPath),l}async function f2(e,t,r){let n={snapshotInteractiveOnly:!0,snapshotCompact:!0},i=pz(await pq({device:e.device,session:e,flags:n,logPath:r,snapshotScope:void 0}),n);pZ(e,i);let a=await fg({screenshotPath:t.path,snapshot:i});t.overlayRefs=a}async function f3(e){let{device:t,node:r,flags:n,appBundleId:i,traceOutPath:a,surface:o,contextFromFlags:s}=e,l=t5(r),u=tv(r.rect);if(!u)return l;try{let e=await cF(t,"read",[String(u.x),String(u.y)],void 0,{...s(n,i,a),surface:o}),d=e&&"object"==typeof e?e:void 0,c="string"==typeof d?.text?d.text:"";if(c.trim())return c;return eN({level:"warn",phase:"interaction_read_fallback",data:{reason:"empty_backend_text",nodeRef:r.ref,surface:o,platform:t.platform}}),l}catch(e){return eN({level:"warn",phase:"interaction_read_fallback",data:{reason:"backend_read_failed",nodeRef:r.ref,surface:o,platform:t.platform,error:e instanceof Error?e.message:String(e)}}),l}}async function f5(e,t,r){let n=e.get(t),i=n?.device??await oW(r??{});return n||await sp(i),{session:n,device:i}}async function f4(e,t,r){let n=!e&&"ios"===t.platform;try{return await r()}finally{n&&await iy(t.id)}}function f8(e,t,r,n){t&&e.recordAction(t,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:n})}let f6=[["snapshotDepth","--depth"],["snapshotScope","--scope"],["snapshotRaw","--raw"]];function f9(e,t){let r=function(e){if(!e)return[];let t=[];for(let[r,n]of f6)void 0!==e[r]&&t.push(n);return t}(t);return 0===r.length?null:cX("INVALID_ARGS",`${e} @ref does not support ${r.join(", ")}.`)}async function f7(e,t){let r=await me(e);if(r)throw new D("COMMAND_FAILED",`press ${t} left ${e.appBundleId} and foregrounded ${r.foregroundPackage}. The tap likely escaped the app.`,r)}async function me(e){var t;if("android"!==e.device.platform||!e.appBundleId)return null;let r=await eu(e.device),n=r.package?.trim();return n&&n!==e.appBundleId&&("com.android.settings"===(t=n)||"com.android.systemui"===t||"com.google.android.permissioncontroller"===t||t.includes("launcher"))?{expectedPackage:e.appBundleId,foregroundPackage:n,activity:r.activity,hint:"com.google.android.permissioncontroller"===n?"Dismiss or allow the permission prompt, then retry the smoke assertion.":"Use screenshot as visual truth, then take a fresh snapshot -i before retrying."}:null}function mt(e,t){let r=Array.isArray(e.selectorChain)?e.selectorChain:void 0,n=ma(e),i=n?.kind==="ref"?mo(n.ref):void 0,a=n?.kind==="selector"?n.selector:void 0,o={...i?{ref:i}:{},...a?{selector:a}:{},...r?{selectorChain:r}:{}};if("attrs"===t)return o;let s="string"==typeof e.text?e.text:"";return{...o,text:s,refLabel:function(e){let t=e.trim();if(!(!t||t.length>80||/[\r\n]/.test(t)))return t}(s)}}function mr(e){let t=ma(e);return{...t?.kind==="ref"?{ref:mo(t.ref)}:{},...t?.kind==="selector"?{selector:t.selector}:{},..."string"==typeof e.text?{text:e.text}:{},...e.node&&"object"==typeof e.node?{node:e.node}:{}}}function mn(e){let{selectorChain:t,...r}=e;return r}function mi(e,t,r,n){let i=e.get(t);i&&e.recordAction(i,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:n})}function ma(e){let t=e.target;return t&&"object"==typeof t?"ref"===t.kind&&"string"==typeof t.ref?{kind:"ref",ref:t.ref}:"selector"===t.kind&&"string"==typeof t.selector?{kind:"selector",selector:t.selector}:void 0:void 0}function mo(e){return e.startsWith("@")?e.slice(1):e}function ms(e,t={}){return{artifacts:function(e,t={}){let r=!0===t.plural?"do":"does";return{resolveInput:async()=>{throw new D("UNSUPPORTED_OPERATION",`${e} ${r} not resolve input artifacts`)},reserveOutput:async()=>{throw new D("UNSUPPORTED_OPERATION",`${e} ${r} not reserve output artifacts`)},createTempFile:async()=>{throw new D("UNSUPPORTED_OPERATION",`${e} ${r} not create temporary files`)}}}(e,t),policy:tO()}}let ml=["application","window","tabbar","scrollbar","image"],mu=new Set(["tab bar"]);async function md(e,t){var r;if(t.ok||(r=t.error.message,!/^wait timed out for (?:selector|text): /i.test(r)))return t;let n=await mc(e).catch(()=>null);return n?cX(t.error.code,`${t.error.message}. Current surface: ${n.summary}.`,{...t.error.details??{},currentSurface:n.details}):t}async function mc(e){let t=[...(await pG({device:e.device,session:e.session,flags:{...e.req.flags,snapshotInteractiveOnly:!0,snapshotCompact:!0},logPath:e.logPath??""})).snapshot.nodes].sort(mf),r=mp(t,6,{includeIdentifiers:!0});if(0===r.length)return null;let n=mp(t.filter(e=>!mw(e)),4,{includeIdentifiers:!1}),i=mp(t.filter(mg),4,{includeIdentifiers:!0});return{summary:(n.length>0?n:r.slice(0,4)).join(", "),details:{labels:r,...i.length>0?{buttons:i}:{}}}}function mp(e,t,r){let n=new Set,i=[];for(let a of e){let e=mh(a,r);if(!(!e||n.has(e))&&(n.add(e),i.push(e),i.length>=t))break}return i}function mf(e,t){var r,n;return mm(e)-mm(t)||(r=e,n=t,r.rect&&n.rect?r.rect.y-n.rect.y||r.rect.x-n.rect.x:r.rect?-1:n.rect?1:(r.depth??0)-(n.depth??0)||r.index-n.index)}function mm(e){let t=!!mh(e,{includeIdentifiers:!1});return 2*!!mw(e)+ +!t}function mh(e,t){let r=(t.includeIdentifiers?[e.label,e.value,e.identifier]:[e.label,e.value]).map(e=>"string"==typeof e?e.trim():"").find(e=>e.length>0);return r?r.replace(/\s+/g," ").slice(0,80):""}function mw(e){let t=rr(`${e.type??""} ${e.role??""} ${e.subrole??""}`),r=`${e.label??""} ${e.value??""}`.trim().toLowerCase();return ml.some(e=>t.includes(e))||mu.has(r)||r.endsWith(".fill")}function mg(e){return rr(`${e.type??""} ${e.role??""} ${e.subrole??""}`).includes("button")}function my(e){var t;let{session:r,selectorExpression:n}=e;if(!r||"ios"!==r.device.platform||r.postGestureStabilization)return null;let i=t3(n);if(!i||1!==i.selectors.length)return null;let a=i.selectors[0];if(!a||1!==a.terms.length)return null;let o=a.terms[0];return o&&"string"==typeof o.value&&("id"===(t=o.key)||"label"===t||"text"===t||"value"===t)?{key:o.key,value:o.value,raw:a.raw}:null}function mv(e){let t=M(e);if("COMMAND_FAILED"!==t.code)return!1;let r=t.message.toLowerCase();return r.includes("fetch failed")||r.includes("timed out")||r.includes("timeout")||r.includes("runner did not accept connection")||r.includes("invalid runner response")}async function mI(e){var t;let{req:r}=e;if("find"!==r.command)return null;let n=r.positionals??[];if(0===n.length)return cX("INVALID_ARGS","find requires a locator or text");let i=rs(n);if(!i.query)return cX("INVALID_ARGS","find requires a value");if(r.flags?.findFirst&&r.flags?.findLast)return cX("INVALID_ARGS","find accepts only one of --first or --last");let a=i.action;if("exists"!==(t=a)&&"wait"!==t&&"get_text"!==t&&"get_attrs"!==t)return null;let o=await mR(e,{requireSession:!1,capability:"find"});return o.ok?await mL(async()=>{let t=await o.runtime.selectors.find({session:e.sessionName,requestId:r.meta?.requestId,locator:i.locator,query:i.query,action:a,timeoutMs:i.timeoutMs});return mi(e.sessionStore,e.sessionName,r,function(e,t){if("exists"===t)return{found:!0};if("wait"===t)return{found:!0,waitedMs:e.waitedMs};let r="string"==typeof e.ref?e.ref:void 0;return"get_attrs"===t?{ref:r,action:"get attrs"}:{ref:r,action:"get text",text:"string"==typeof e.text?e.text:""}}(t,a)),"found"===t.kind?{found:!0,..."number"==typeof t.waitedMs?{waitedMs:t.waitedMs}:{}}:{..."string"==typeof t.ref?{ref:t.ref}:{},..."string"==typeof t.text?{text:t.text}:{},...t.node&&"object"==typeof t.node?{node:t.node}:{}}}):o.response}async function mb(e){let{req:t}=e;if("get"!==t.command)return null;let r=t.positionals?.[0];if("text"!==r&&"attrs"!==r)return cX("INVALID_ARGS","get only supports text or attrs");let n=function(e){let t=e.positionals?.[1]??"";if(t.startsWith("@"))return{ok:!0,target:{kind:"ref",ref:t,fallbackLabel:e.positionals.length>2?e.positionals.slice(2).join(" ").trim():""}};let r=e.positionals?.slice(1).join(" ").trim()??"";return r?{ok:!0,target:{kind:"selector",selector:r}}:{ok:!1,response:cX("INVALID_ARGS","get requires @ref or selector expression")}}(t);if(!n.ok)return n.response;if("ref"===n.target.kind){let e=f9("get",t.flags);if(e)return e}if("selector"===n.target.kind){let t=await mx(e,r,n.target.selector);if(t)return t}let i=await mR(e,{requireSession:!0,capability:"get"});return i.ok?await mL(async()=>{let a=await i.runtime.selectors.get({session:e.sessionName,requestId:t.meta?.requestId,property:r,target:n.target});return mi(e.sessionStore,e.sessionName,t,mt(a,r)),mr(a)}):i.response}async function mA(e){let{req:t}=e;if("is"!==t.command)return null;let r=(t.positionals?.[0]??"").toLowerCase();if(!tP(r))return cX("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text");let{split:n}=t4(t.positionals??[]);if(!n)return cX("INVALID_ARGS","is requires a selector expression");let i=n.rest.join(" ").trim();if("text"===r&&!i)return cX("INVALID_ARGS","is text requires expected text value");if("text"!==r&&n.rest.length>0)return cX("INVALID_ARGS",`is ${r} does not accept trailing values`);let a=await m_(e,r,n.selectorExpression,i);if(a)return a;let o=await mR(e,{requireSession:!0,capability:"is"});if(!o.ok)return o.response;let s=await mL(async()=>{let a=await o.runtime.selectors.is({session:e.sessionName,requestId:t.meta?.requestId,predicate:r,selector:n.selectorExpression,expectedText:i});return mi(e.sessionStore,e.sessionName,t,a),mn(a)});return await mT(e,s,`is ${r}`)}async function mS(e){let{req:t,sessionName:r,sessionStore:n}=e,i=eZ(t.positionals??[]);if(!i)return cX("INVALID_ARGS","wait requires a duration or text");let{session:a,device:o}=await f5(n,r,t.flags);if("sleep"!==i.kind&&!pd("wait",o))return cX("UNSUPPORTED_OPERATION","wait is not supported on this device");if("selector"===i.kind){let t=await mN({...e,session:a,device:o,selectorExpression:i.selectorExpression,timeoutMs:i.timeoutMs});if(t)return t}let s=async()=>{let s=mP({...e,session:a,device:o}),l=await mL(async()=>{let e=await s.selectors.wait({session:r,requestId:t.meta?.requestId,target:function(e,t){if("sleep"===e.kind)return{kind:"sleep",durationMs:e.durationMs};if("selector"===e.kind)return{kind:"selector",selector:e.selectorExpression,timeoutMs:e.timeoutMs};if("ref"===e.kind){if(!t?.snapshot)throw new D("INVALID_ARGS","Ref wait requires an existing snapshot in session.");return{kind:"ref",ref:e.rawRef,timeoutMs:e.timeoutMs}}if(!e.text)throw new D("INVALID_ARGS","wait requires text");return{kind:"text",text:e.text,timeoutMs:e.timeoutMs}}(i,a)});return mi(n,r,t,e),{waitedMs:e.waitedMs,..."string"==typeof e.text?{text:e.text}:{},..."string"==typeof e.selector?{selector:e.selector}:{}}}),u=await md({req:t,logPath:e.logPath,session:a,device:o},l);return await mT(e,u,"wait")};return"sleep"===i.kind?await s():await f4(a,o,s)}async function mx(e,t,r){let n=await mM(e,r);if(mO(n))return n.response;if(!n)return null;let i=function(e,t,r){if(!r.found||!r.node)return null;let n={target:{kind:"selector",selector:t},node:r.node,selectorChain:[t]};return"attrs"===e?{kind:"attrs",...n}:"string"!=typeof r.text?null:{kind:"text",...n,text:r.text}}(t,n.selector.raw,n.result);return i?(mi(e.sessionStore,e.sessionName,e.req,mt(i,t)),{ok:!0,data:mr(i)}):null}async function m_(e,t,r,n){var i,a,o,s,l;let u;if("hidden"===t)return null;let d=await mM(e,r);if(mO(d))return d.response;if(!d?.result.found||!d.result.node)return null;let c="exists"===t?{predicate:t,pass:!0,selector:d.selector.raw,matches:1,selectorChain:[d.selector.raw]}:(i=t,a=n,o=d.selector.raw,s=d.session,u=tM({predicate:i,node:l=d.result.node,nodes:[l],expectedText:a,platform:s.device.platform}),{predicate:i,pass:u.pass,selector:o,..."text"===i?{text:u.actualText}:{},selectorChain:[o]});return c?(mi(e.sessionStore,e.sessionName,e.req,c),{ok:!0,data:mn(c)}):null}async function mN(e){let t=my({session:e.session,selectorExpression:e.selectorExpression});if(!e.session||!t)return null;let r=Date.now(),n=await mD(e,e.session,t);if(mO(n))return n.response;if(!n?.found)return null;let i={kind:"selector",selector:t.raw,waitedMs:Date.now()-r,selectorChain:[t.raw]};return mi(e.sessionStore,e.sessionName,e.req,i),await md({req:e.req,logPath:e.logPath,session:e.session,device:e.device},{ok:!0,data:i})}async function mM(e,t){let r=e.sessionStore.get(e.sessionName),n=my({session:r,selectorExpression:t});if(!r||!n)return null;let i=await mD(e,r,n);return mO(i)?i:i?{session:r,selector:n,result:i}:null}async function mk(e,t,r){let n=await iP(t.device,{command:"querySelector",selectorKey:r.key,selectorValue:r.value,appBundleId:t.appBundleId},{verbose:!!e.req.flags?.verbose,logPath:e.logPath,traceLogPath:t.trace?.outPath,requestId:e.req.meta?.requestId}),i=!0===n.found,a=function(e){let t=e.nodes;if(!Array.isArray(t))return;let r=t[0];if(r&&"object"==typeof r)return r}(n);return{found:i,..."string"==typeof n.text?{text:n.text}:{},...a?{node:a}:{}}}async function mD(e,t,r){try{return await mk(e,t,r)}catch(e){if(mv(e))return null;return{kind:"error",response:{ok:!1,error:k(e)}}}}function mO(e){return null!==e&&"kind"in e&&"error"===e.kind}function mP(e){return tG({backend:function(e){let t,{req:r,session:n,device:i,logPath:a,sessionName:o,sessionStore:s}=e,l=0;return{platform:i.platform,captureSnapshot:async(e,u)=>{var d;let c,p={...r.flags,...(d=u,c={},d?.interactiveOnly!==void 0&&(c.snapshotInteractiveOnly=d.interactiveOnly),d?.compact!==void 0&&(c.snapshotCompact=d.compact),d?.scope!==void 0&&(c.snapshotScope=d.scope),d?.depth!==void 0&&(c.snapshotDepth=d.depth),d?.raw!==void 0&&(c.snapshotRaw=d.raw),c)},f=u?.scope??r.flags?.snapshotScope,m=Date.now(),h=tX(tz(p)),w="wait"===r.command||"find"===r.command;if(!w&&t&&m-l<750&&!pf(n)&&!n?.postGestureStabilization)return t;if(!w&&n?.snapshot&&m-n.snapshot.createdAt<750&&n.snapshot.presentationKey===h&&!pf(n)&&!n.postGestureStabilization)return l=n.snapshot.createdAt,t={snapshot:n.snapshot};let g=await pG({device:i,session:n,flags:p,outPath:r.flags?.out,logPath:a??"",snapshotScope:f});return n&&(pZ(n,g.snapshot),s.set(o,n)),l=m,t={snapshot:g.snapshot}},readText:async(t,o)=>({text:await f3({device:i,node:o,flags:r.flags,appBundleId:n?.appBundleId,traceOutPath:n?.trace?.outPath,surface:n?.surface,contextFromFlags:e.contextFromFlags??((e,t,r)=>pg(a??"",e,t,r))})}),findText:async(t,r)=>({found:await mC(e,r)})}}(e),...ms("selector commands",{plural:!0}),sessions:pY({sessionName:e.sessionName,getSession:()=>e.session,recordOptions:{includeSnapshot:!0},setRecord:t=>{e.session&&t.snapshot&&(pZ(e.session,t.snapshot),e.sessionStore.set(e.sessionName,e.session))}})})}async function mR(e,t){let r=e.sessionStore.get(e.sessionName);if(!r&&t.requireSession)return{ok:!1,response:cX("SESSION_NOT_FOUND","No active session. Run open first.")};let n=r?.device??await oW(e.req.flags??{});return(r||await sp(n),pd(t.capability,n))?{ok:!0,runtime:mP({...e,session:r,device:n})}:{ok:!1,response:cX("UNSUPPORTED_OPERATION",`${t.capability} is not supported on this device`)}}async function mC(e,t){let{device:r,session:n,req:i,logPath:a}=e;if("macos"===r.platform&&n?.surface&&"app"!==n.surface)return!!t8((await mE(e)).nodes,t);if(nn(r.platform)&&n?.appBundleId){let e=await iP(r,{command:"findText",text:t,appBundleId:n?.appBundleId},{verbose:i.flags?.verbose,logPath:a,traceLogPath:n?.trace?.outPath,requestId:i.meta?.requestId});return e?.found===!0}return!!t8((await mE(e)).nodes,t)}async function mE(e){let t=await pG({device:e.device,session:e.session,flags:{...e.req.flags,snapshotInteractiveOnly:!1,snapshotCompact:!1},outPath:e.req.flags?.out,logPath:e.logPath??""});return e.session&&(pZ(e.session,t.snapshot),e.sessionStore.set(e.sessionName,e.session)),t.snapshot}async function mL(e){try{return{ok:!0,data:await e()}}catch(t){let e=M(t);return cX(e.code,e.message,e.details)}}async function mT(e,t,r){var n;let i;if(t.ok)return t;let a=e.sessionStore.get(e.sessionName);if(!a)return t;try{i=await me(a)}catch{return t}return i?cX(t.error.code,`${r} failed because ${"com.google.android.permissioncontroller"===(n=i).foregroundPackage?`Android permission dialog is blocking ${n.expectedPackage}`:`${n.foregroundPackage} is foreground instead of ${n.expectedPackage}`}.`,{...t.error.details??{},...i,blockedBy:"android_foreground_surface",originalMessage:t.error.message}):t}async function m$(e){var t,r;let{req:n,sessionName:i,logPath:a,sessionStore:o,invoke:s}=e,l=n.command;if("find"!==l)return null;let u=n.positionals??[];if(0===u.length)return cX("INVALID_ARGS","find requires a locator or text");let{locator:d,query:c,action:p,value:f,timeoutMs:m}=rs(u);if(!c)return cX("INVALID_ARGS","find requires a value");if(n.flags?.findFirst&&n.flags?.findLast)return cX("INVALID_ARGS","find accepts only one of --first or --last");let h=await mI({req:n,sessionName:i,logPath:a,sessionStore:o});if(h)return h;let w=o.get(i),g="exists"===(t=p)||"wait"===t||"get_text"===t||"get_attrs"===t;if(!w&&!g)return cX("SESSION_NOT_FOUND","No active session. Run open first.");let y=w?.device??await oW(n.flags??{});w||await sp(y);let v="click"===(r=p)||"focus"===r||"fill"===r||"type"===r,I="role"===d||v?void 0:c,b=0,A=null,S=async()=>{let e=Date.now();if(A&&e-b<750&&!pf(w))return{nodes:A};let{snapshot:t}=await pG({device:y,session:w,flags:{...n.flags,snapshotInteractiveOnly:v,snapshotCompact:v},outPath:n.flags?.out,logPath:a,snapshotScope:I}),r=t.nodes;return b=e,A=r,w&&(pZ(w,t),o.set(i,w)),{nodes:r,truncated:t.truncated,backend:t.backend}},x={req:n,sessionName:i,logPath:a,sessionStore:o,invoke:s,session:w,device:y,command:l,locator:d,query:c};if("wait"===p)return mV(x,S,d,c,m);let{nodes:_}=await S(),N=function(e){let{nodes:t,locator:r,query:n,requiresRect:i,flags:a}=e,o=ra(t,r,n,{requireRect:i});if(i&&(o.matches=function(e,t){var r,n;let i=t[0]?.rect;if(!i)return e;let a=e.filter(e=>{if(!e.rect)return!1;let t=tZ(e.rect);return t.x>=i.x&&t.x<=i.x+i.width&&t.y>=i.y&&t.y<=i.y+i.height});return r=a.length>0?a:e,n=t,r.length<2?r:r.map((e,t)=>{var r,i;let a;return{node:e,index:t,score:(r=e,"semantic-target"===(a=t_(i=n,r)).reason&&a.node.rect||"same-rect-descendant"===a.reason&&a.node.rect?4:"hittable-ancestor"===a.reason&&a.node.rect&&!mU(a.node,i[0])?2:r.hittable&&r.rect&&!mU(r,i[0])?3:+!!r.rect)}}).sort((e,t)=>t.score!==e.score?t.score-e.score:mF(e.node)-mF(t.node)||e.index-t.index).map(e=>e.node)}(o.matches,t)),i&&o.matches.length>1)if(a?.findFirst)o.matches=[o.matches[0]];else{if(!a?.findLast){var s,l,u;let e;return{ok:!1,response:(s=o.matches,l=r,u=n,e=s.slice(0,8).map(e=>{let t=t2(e)||e.label||e.identifier||e.type||"";return`@${e.ref}${t?`(${t})`:""}`}),cX("AMBIGUOUS_MATCH",`find matched ${s.length} elements for ${l} "${u}". Use a more specific locator or selector.`,{locator:l,query:u,matches:s.length,candidates:e}))}}o.matches=[o.matches[o.matches.length-1]]}let d=o.matches[0]??null;return d?{ok:!0,node:d}:{ok:!1,response:cX("COMMAND_FAILED","find did not match any element")}}({nodes:_,locator:d,query:c,requiresRect:v,flags:n.flags});if(!N.ok)return N.response;let M=N.node,k=v?tE(_,M):M,D=`@${k.ref}`,O={node:M,resolvedNode:k,ref:D,nodes:_,actionFlags:{...n.flags??{},noRecord:!0}},P={exists:()=>mG(x),get_text:()=>mq(x,O),get_attrs:()=>mB(x,O),click:()=>mj(x,O),fill:()=>mH(x,O,f),focus:()=>mW(x,O),type:()=>mz(x,O,f)}[p];return P?P():null}function mF(e){return e.rect?e.rect.width*e.rect.height:1/0}function mU(e,t){if(!t?.rect||!e.rect)return!1;let r=e.type?.toLowerCase()??"";return(!!r.includes("application")||!!r.includes("window"))&&e.rect.x===t.rect.x&&e.rect.y===t.rect.y&&e.rect.width===t.rect.width&&e.rect.height===t.rect.height}async function mV(e,t,r,n,i){let{req:a,sessionStore:o,session:s,command:l}=e,u=i??1e4,d=Date.now();for(;Date.now()-d<u;){let{nodes:e}=await t();if(ra(e,r,n,{requireRect:!1}).matches[0])return s&&o.recordAction(s,{command:l,positionals:a.positionals??[],flags:a.flags??{},result:{found:!0,waitedMs:Date.now()-d}}),{ok:!0,data:{found:!0,waitedMs:Date.now()-d}};await e8(300)}return cX("COMMAND_FAILED","find wait timed out")}async function mG(e){let{req:t,sessionStore:r,session:n,command:i}=e;return n&&r.recordAction(n,{command:i,positionals:t.positionals??[],flags:t.flags??{},result:{found:!0}}),{ok:!0,data:{found:!0}}}async function mq(e,t){let{req:r,sessionStore:n,session:i,command:a,device:o,logPath:s}=e,l=await f3({device:o,node:t.node,flags:r.flags,appBundleId:i?.appBundleId,traceOutPath:i?.trace?.outPath,surface:i?.surface,contextFromFlags:(e,t,r)=>pg(s,e,t,r)});return i&&n.recordAction(i,{command:a,positionals:r.positionals??[],flags:r.flags??{},result:{ref:t.ref,action:"get text",text:l}}),{ok:!0,data:{ref:t.ref,text:l,node:t.node}}}async function mB(e,t){let{req:r,sessionStore:n,session:i,command:a}=e;return i&&n.recordAction(i,{command:a,positionals:r.positionals??[],flags:r.flags??{},result:{ref:t.ref,action:"get attrs"}}),{ok:!0,data:{ref:t.ref,node:t.node}}}async function mj(e,t){let{req:r,sessionName:n,sessionStore:i,session:a,invoke:o,command:s,locator:l,query:u}=e,d=await o({token:r.token,session:n,command:"click",positionals:[t.ref],flags:t.actionFlags});if(!d.ok)return d;let c=t.resolvedNode.rect?tZ(t.resolvedNode.rect):t.node.rect?tZ(t.node.rect):null,p={ref:t.ref,locator:l,query:u};return c&&(p.x=c.x,p.y=c.y),a&&i.recordAction(a,{command:s,positionals:r.positionals??[],flags:r.flags??{},result:{ref:t.ref,action:"click",locator:l,query:u}}),{ok:!0,data:p}}async function mH(e,t,r){let{req:n,sessionName:i,sessionStore:a,session:o,invoke:s,command:l}=e;if(!r)return cX("INVALID_ARGS","find fill requires text");let u=await s({token:n.token,session:i,command:"fill",positionals:[t.ref,r],flags:t.actionFlags});return u.ok&&o&&a.recordAction(o,{command:l,positionals:n.positionals??[],flags:n.flags??{},result:{ref:t.ref,action:"fill"}}),u}async function mW(e,t){let r=await mK(e,t);return r.ok&&mJ(e,t,"focus"),r}async function mz(e,t,r){let{req:n,device:i,logPath:a,session:o}=e;if(!r)return cX("INVALID_ARGS","find type requires text");let s=await mK(e,t);if(!s.ok)return s;let l=await cF(i,"type",[r],n.flags?.out,{...pg(a,n.flags,o?.appBundleId,o?.trace?.outPath)});return mJ(e,t,"type"),{ok:!0,data:l??{ref:t.ref}}}async function mK(e,t){let{req:r,device:n,logPath:i,session:a}=e,o=t.node.rect?tZ(t.node.rect):null;return o?{ok:!0,data:await cF(n,"focus",[String(o.x),String(o.y)],r.flags?.out,{...pg(i,r.flags,a?.appBundleId,a?.trace?.outPath)})??{ref:t.ref}}:cX("COMMAND_FAILED","matched element has no bounds")}function mJ(e,t,r){let{req:n,sessionStore:i,session:a,command:o}=e;a&&i.recordAction(a,{command:o,positionals:n.positionals??[],flags:n.flags??{},result:{ref:t.ref,action:r}})}function mX(e){var t,r,n;let i,a,o,{data:s,fallbackX:l,fallbackY:u,referenceFrame:d,extra:c}=e,p=(t=c,r=l,n=u,i="string"==typeof t?.ref?t.ref:void 0,a="string"==typeof t?.button?t.button:void 0,o="string"==typeof t?.gesture?t.gesture:void 0,("string"==typeof t?.text?`Filled ${Array.from(t.text).length} chars`:i?"longpress"===o?`Long pressed @${i} (${r}, ${n})`:a&&"primary"!==a?`Clicked ${a} @${i} (${r}, ${n})`:`Tapped @${i} (${r}, ${n})`:void 0)??("string"==typeof s?.message?s.message:void 0));return{x:l,y:u,...d??{},...c??{},...s??{},...eJ(p)}}function mZ(e){let{session:t,sessionStore:r,command:n,positionals:i,flags:a,result:o,responseData:s,actionStartedAt:l,actionFinishedAt:u,androidFreshnessBaseline:d}=e;return r.recordAction(t,{command:n,positionals:i,flags:a??{},result:o}),ph(n)&&pp(t,n,d??t.snapshot),f$(t,n,i,o,a??{},l,u),{ok:!0,data:s}}async function mY(e){let{session:t,flags:r,sessionStore:n,contextFromFlags:i,captureSnapshotForSession:a}=e;if(!t.recording)return;if(t.recording.touchReferenceFrame)return t.recording.touchReferenceFrame;if("android"===t.device.platform){let e=await ln(t.device),r={referenceWidth:e.width,referenceHeight:e.height};return t.recording&&(t.recording.touchReferenceFrame=r),r}let o=fE(t.snapshot);if(o)return t.recording&&(t.recording.touchReferenceFrame=o),o;if(!t.recording)return;let s=fE(await a(t,r,n,i,{interactiveOnly:!0}));return s&&t.recording&&(t.recording.touchReferenceFrame=s),s}async function mQ(e){try{return await mY(e)}catch(t){eN({level:"warn",phase:"touch_reference_frame_resolve_failed",data:{platform:e.session.device.platform,error:t instanceof Error?t.message:String(t)}});return}}function m0(e){return fE({nodes:e,createdAt:0})}function m1(e,t){return"macos"!==e.device.platform||"desktop"!==e.surface&&"menubar"!==e.surface||"menubar"===e.surface&&("click"===t||"press"===t)?null:cX("UNSUPPORTED_OPERATION",`${t} is not supported on macOS ${e.surface} sessions yet. Open an app session to act, or use the ${e.surface} surface to inspect.`)}function m2(e){let t=e.sessionStore.get(e.sessionName);if(!t)throw new D("SESSION_NOT_FOUND","No active session. Run open first.");return tG({backend:function(e){let{req:t,session:r}=e;return{platform:r.device.platform,captureSnapshot:async(n,i)=>({snapshot:await e.captureSnapshotForSession(r,t.flags,e.sessionStore,e.contextFromFlags,{interactiveOnly:i?.interactiveOnly===!0})}),tap:async(n,i)=>m3(await cF(r.device,"press",[String(i.x),String(i.y)],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath))),fill:async(n,i,a)=>m3(await cF(r.device,"fill",[String(i.x),String(i.y),a],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath))),longPress:async(n,i,a)=>m3(await cF(r.device,"longpress",[String(i.x),String(i.y),...a?.durationMs===void 0?[]:[String(a.durationMs)]],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath))),typeText:async(n,i)=>m3(await cF(r.device,"type",[i],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath)))}}({...e,session:t}),...ms("interaction commands",{plural:!0}),sessions:pY({sessionName:e.sessionName,getSession:()=>t,recordOptions:{includeSnapshot:!0},setRecord:r=>{r.snapshot&&(pZ(t,r.snapshot),e.sessionStore.set(e.sessionName,t))}})})}function m3(e){return e&&"object"==typeof e?e:void 0}function m5(e){if(e.length<2)return null;let t=Number(e[0]),r=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(r)?{x:t,y:r}:null}function m4(e,t){let r=m5(e);if(r)return{ok:!0,target:{kind:"point",x:r.x,y:r.y}};let n=e[0]??"";if(n.startsWith("@"))return{ok:!0,target:{kind:"ref",ref:n,fallbackLabel:eO(e).label??""}};let i=e.join(" ").trim();return i?{ok:!0,target:{kind:"selector",selector:i}}:{ok:!1,response:cX("INVALID_ARGS",`${t} requires @ref, selector expression, or x y coordinates`)}}function m8(e){return"ref"===e.kind?{ref:m6(e.target?.kind==="ref"?e.target.ref:void 0),refLabel:e.refLabel,selectorChain:e.selectorChain}:"selector"===e.kind?{selector:e.target?.kind==="selector"?e.target.selector:void 0,selectorChain:e.selectorChain,refLabel:e.refLabel}:{}}function m6(e){return e?.startsWith("@")?e.slice(1):e}async function m9(e){switch(e.req.command){case"press":return await m7(e,"press");case"click":return await m7(e,"click");case"longpress":return await m7(e,"longpress");case"fill":return await hi(e);default:return null}}async function m7(e,t){let r,{req:n,sessionName:i,sessionStore:a}=e,o=a.get(i);if(!o)return cX("SESSION_NOT_FOUND","No active session. Run open first.");let s="click"===t?"click":t,l="longpress"===t?"longpress":"press",u=m1(o,s);if(u)return u;if(!pd(l,o.device))return cX("UNSUPPORTED_OPERATION",`${l} is not supported on this device`);let d=ci(n.flags),c="primary"===d?{}:{button:d};if("longpress"!==t&&"primary"!==d){let e=ca({commandLabel:s,platform:o.device.platform,button:d,count:n.flags?.count,intervalMs:n.flags?.intervalMs,holdMs:n.flags?.holdMs,jitterPx:n.flags?.jitterPx,doubleTap:n.flags?.doubleTap});if(e)return cX(e.code,e.message,e.details)}let p="longpress"===t?function(e){var t,r,n;let i,a=m5(e);if(a){return{ok:!0,target:{kind:"point",x:a.x,y:a.y},...void 0===(t=e[2])?{}:{durationMs:Number(t)}}}let o=(i=(r=e).at(-1),r.length>1&&void 0!==(n=i)&&""!==n.trim()&&Number.isFinite(Number(n))?{targetPositionals:r.slice(0,-1),duration:{durationMs:Number(i)}}:{targetPositionals:r,duration:{}}),s=m4(o.targetPositionals,"longpress");return s.ok?{ok:!0,target:s.target,...o.duration}:s}(n.positionals??[]):m4(n.positionals??[],s);if(!p.ok)return p.response;if("ref"===p.target.kind){let i=e.refSnapshotFlagGuardResponse("longpress"===t?"longpress":"press",n.flags);if(i)return i;r=await hs(e,o)}let f=function(e){var t;let{session:r,commandLabel:n,target:i,flags:a}=e;if("click"!==n||"selector"!==i.kind||(t=a,t?.count!==void 0||t?.intervalMs!==void 0||t?.holdMs!==void 0||t?.jitterPx!==void 0||t?.doubleTap!==void 0||t?.clickButton!==void 0&&"primary"!==t.clickButton))return null;let o=my({session:r,selectorExpression:i.selector});return o?{...o,...a?.maestro?.allowNonHittableCoordinateFallback?{allowNonHittableCoordinateFallback:!0}:{}}:null}({session:o,commandLabel:s,target:p.target,flags:n.flags});if(f){let t=await hr(e,o,f);if(t)return t}let m="longpress"===t?p.durationMs:void 0;return await ho(e,{androidFreshnessBaseline:r,run:async e=>await he({runtime:e,command:t,target:p.target,sessionName:i,requestId:n.meta?.requestId,clickButton:d,flags:n.flags,durationMs:m}),afterRun:async e=>{var t;await f7(o,(t=p.target,"point"===t.kind?"coordinate tap":"ref"===e.kind&&e.target?.kind==="ref"?e.target.ref:"selector"===e.kind&&e.target?.kind==="selector"?e.target.selector:"target"))},buildPayloads:async r=>{var n;let i="durationMs"in(n=r)?n.durationMs:void 0,a=await ht({params:e,session:o,result:r,extra:"longpress"===t?{...void 0!==i?{durationMs:i}:{},gesture:"longpress"}:c});return{result:a,responseData:a}}})}async function he(e){let{runtime:t,command:r,target:n,sessionName:i,requestId:a,flags:o}=e;if("longpress"===r)return await t.interactions.longPress(n,{session:i,requestId:a,durationMs:e.durationMs});let s={session:i,requestId:a,button:e.clickButton,count:o?.count,intervalMs:o?.intervalMs,holdMs:o?.holdMs,jitterPx:o?.jitterPx,doubleTap:o?.doubleTap};return"click"===r?await t.interactions.click(n,s):await t.interactions.press(n,s)}async function ht(e){let{params:t,session:r,result:n,extra:i}=e,a="point"===n.kind?await mQ({session:r,flags:t.req.flags,sessionStore:t.sessionStore,contextFromFlags:t.contextFromFlags,captureSnapshotForSession:t.captureSnapshotForSession}):m0(r.snapshot?.nodes??[]);return mX({data:n.backendResult,fallbackX:n.point.x,fallbackY:n.point.y,referenceFrame:a,extra:{...m8(n),...i}})}async function hr(e,t,r){return await hn({params:e,session:t,selector:r,command:"press",positionals:[],extra:{selector:r.raw},fallbackPhase:"ios_direct_selector_tap_fallback"})}async function hn(e){let{params:t,session:r,selector:n,command:i,positionals:a,extra:o,fallbackPhase:s}=e,l=Date.now();try{var u,d;let e,s,c=await cF(r.device,i,a,t.req.flags?.out,{...t.contextFromFlags(t.req.flags,r.appBundleId,r.trace?.outPath),directElementSelector:n,surface:r.surface})??{},p=Date.now(),f=(u=c,e="number"==typeof u.x?u.x:void 0,s="number"==typeof u.y?u.y:void 0,void 0!==e&&void 0!==s?{x:e,y:s}:{x:0,y:0}),m=mX({data:c,fallbackX:f.x,fallbackY:f.y,referenceFrame:(d=c,"number"==typeof d.referenceWidth&&"number"==typeof d.referenceHeight?{referenceWidth:d.referenceWidth,referenceHeight:d.referenceHeight}:void 0),extra:{...o,...function(e,t){if(!e.allowNonHittableCoordinateFallback)return{};let r="tapped via non-hittable coordinate fallback"===t.message;return{maestroNonHittableCoordinateFallbackAllowed:!0,maestroNonHittableCoordinateFallbackUsed:r,...r?{maestroFallbackReason:"non-hittable-coordinate"}:{}}}(n,c)}});return mZ({session:r,sessionStore:t.sessionStore,command:t.req.command,positionals:t.req.positionals??[],flags:t.req.flags,result:m,responseData:m,actionStartedAt:l,actionFinishedAt:p})}catch(e){if(!mv(e))return{ok:!1,error:k(e)};return eN({level:"debug",phase:s,data:{selector:n.raw,error:e instanceof Error?e.message:String(e)}}),null}}async function hi(e){let{req:t,sessionName:r,sessionStore:n}=e,i=n.get(r);if(i){let e=m1(i,"fill");if(e)return e}if(i&&!pd("fill",i.device))return cX("UNSUPPORTED_OPERATION","fill is not supported on this device");if(!i)return cX("SESSION_NOT_FOUND","No active session. Run open first.");let a=function(e){let t=e[0]??"";if(t.startsWith("@")){var r;let n=e2(e).text;return n?{ok:!0,target:{kind:"ref",ref:t,fallbackLabel:(r=e).length>=3&&r[1]?.trim()||""},text:n}:{ok:!1,response:cX("INVALID_ARGS","fill requires text after ref")}}let n=m5(e);if(n){let t=e.slice(2).join(" ");return t?{ok:!0,target:{kind:"point",x:n.x,y:n.y},text:t}:{ok:!1,response:cX("INVALID_ARGS","fill requires text after coordinates")}}let i=e2(e);return"selector"!==i.kind?{ok:!1,response:cX("INVALID_ARGS","fill requires x y text, @ref text, or selector text")}:i.text.trim()?{ok:!0,target:{kind:"selector",selector:i.target.selector},text:i.text}:{ok:!1,response:cX("INVALID_ARGS","fill requires text after selector")}}(t.positionals??[]);if(!a.ok)return a.response;if("ref"===a.target.kind){let r=e.refSnapshotFlagGuardResponse("fill",t.flags);if(r)return r;await hs(e,i)}let o=function(e){let{session:t,target:r,flags:n}=e;if("selector"!==r.kind)return null;let i=my({session:t,selectorExpression:r.selector});return i?{...i,...n?.maestro?.allowNonHittableCoordinateFallback?{allowNonHittableCoordinateFallback:!0}:{}}:null}({session:i,target:a.target,flags:t.flags});if(o){let t=await ha(e,i,o,a.text);if(t)return t}return await ho(e,{run:async e=>await e.interactions.fill(a.target,a.text,{session:r,requestId:t.meta?.requestId,delayMs:t.flags?.delayMs}),buildPayloads:e=>{let t="point"===e.kind?void 0:m0(i.snapshot?.nodes??[]),r=mX({data:e.backendResult,fallbackX:e.point.x,fallbackY:e.point.y,referenceFrame:t,extra:{...m8(e),text:a.text}});e.warning&&(r.warning=e.warning);let n="ref"===e.kind?{...e.backendResult??{ref:m6(e.target?.kind==="ref"?e.target.ref:void 0),x:e.point.x,y:e.point.y}}:r;return e.warning&&(n.warning=e.warning),{result:r,responseData:n}}})}async function ha(e,t,r,n){return await hn({params:e,session:t,selector:r,command:"fill",positionals:[n],extra:{selector:r.raw,text:n},fallbackPhase:"ios_direct_selector_fill_fallback"})}async function ho(e,t){let r=e.sessionStore.get(e.sessionName);if(!r)return cX("SESSION_NOT_FOUND","No active session. Run open first.");let n=m2(e),i=Date.now();try{let a=await p4({session:r,command:e.req.command,phase:"before-command"}),o=await t.run(n);await t.afterRun?.(o),await p4({session:r,command:e.req.command,phase:"after-command"});let s=Date.now(),{result:l,responseData:u}=await t.buildPayloads(o);return"recovered"===a.status&&(l.warning=a.warning,u.warning=a.warning),mZ({session:r,sessionStore:e.sessionStore,command:e.req.command,positionals:e.req.positionals??[],flags:e.req.flags,result:l,responseData:u,actionStartedAt:i,actionFinishedAt:s,androidFreshnessBaseline:t.androidFreshnessBaseline})}catch(t){let e=M(t);if("COMMAND_FAILED"===e.code&&"string"==typeof e.details?.expectedPackage&&"string"==typeof e.details?.foregroundPackage)throw e;return{ok:!1,error:k(t)}}}async function hs(e,t){if(!pf(t))return;let r=t.snapshot?.comparisonSafe===!0?t.snapshot:void 0;try{await e.captureSnapshotForSession(t,e.req.flags,e.sessionStore,e.contextFromFlags,{interactiveOnly:!0,androidFreshnessMode:"ref-refresh"})}catch(t){eN({level:"warn",phase:"android_ref_snapshot_refresh_failed",data:{command:e.req.command,error:t instanceof Error?t.message:String(t)}})}return r}async function hl(e,t,r,n,i){let a={...t??{},snapshotInteractiveOnly:i.interactiveOnly,snapshotCompact:i.interactiveOnly},o=n(a,e.appBundleId,e.trace?.outPath),{snapshot:s}=await pG({device:e.device,session:e,flags:a,outPath:a.out,logPath:o.logPath??"",androidFreshnessMode:i.androidFreshnessMode});return pZ(e,s),r.set(e.name,e),s}async function hu(e){let t=await m9({...e,captureSnapshotForSession:hl,refSnapshotFlagGuardResponse:f9});if(t)return t;switch(e.req.command){case eD.type:return await hd({...e,captureSnapshotForSession:hl});case"get":return await mb(e);case"is":return await mA(e);default:return null}}async function hd(e){let{sessionName:t,sessionStore:r}=e,n=r.get(t);if(!n)return cX("SESSION_NOT_FOUND","No active session. Run open first.");if(!pd(eD.type,n.device))return cX("UNSUPPORTED_OPERATION","type is not supported on this device");let i=await hc(n);return i||await hp(e,n)}async function hc(e){return"android"===e.device.platform&&e.recording&&"failed"===await p5({session:e})?cX("COMMAND_FAILED","Android system dialog blocked the recording session"):null}async function hp(e,t){let{req:r,sessionName:n,sessionStore:i}=e,a=(r.positionals??[]).join(" "),o=m2(e),s=Date.now();try{let e=await p4({session:t,command:r.command,phase:"before-command"}),l=await o.interactions.typeText(a,{session:n,requestId:r.meta?.requestId,delayMs:r.flags?.delayMs});await p4({session:t,command:r.command,phase:"after-command"});let u=Date.now(),d={...l.backendResult??{},text:l.text,delayMs:l.delayMs,...eJ(l.message??`Typed ${Array.from(l.text).length} chars`)};return"recovered"===e.status&&(d.warning=e.warning),mZ({session:t,sessionStore:i,command:r.command,positionals:r.positionals??[],flags:r.flags,result:d,responseData:d,actionStartedAt:s,actionFinishedAt:u})}catch(e){return{ok:!1,error:k(e)}}}function hf(e){return{tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,leaseTtlMs:e.meta?.leaseTtlMs,leaseBackend:e.meta?.leaseBackend}}async function hm(e){let{req:t,leaseRegistry:r}=e,n=hf(t);switch(t.command){case"lease_allocate":return{ok:!0,data:{lease:r.allocateLease({tenantId:n.tenantId??"",runId:n.runId??"",backend:n.leaseBackend,ttlMs:n.leaseTtlMs})}};case"lease_heartbeat":return{ok:!0,data:{lease:r.heartbeatLease({leaseId:n.leaseId??"",tenantId:n.tenantId,runId:n.runId,ttlMs:n.leaseTtlMs})}};case"lease_release":return{ok:!0,data:r.releaseLease({leaseId:n.leaseId??"",tenantId:n.tenantId,runId:n.runId})};default:return null}}async function hh(e){var t,r;let{req:n,sessionName:i,sessionStore:a}=e;if(n.command!==eD.reactNative)return null;let o=1===(t=n.positionals??[]).length&&"dismiss-overlay"===t[0]?{ok:!0}:{ok:!1,response:cX("INVALID_ARGS","react-native supports only: dismiss-overlay")};if(!o.ok)return o.response;let s=a.get(i);if(!s)return cX("SESSION_NOT_FOUND","No active session. Run open first.");if(!pd(eD.reactNative,s.device))return cX("UNSUPPORTED_OPERATION","react-native dismiss-overlay is not supported on this device");try{let t=await hl(s,n.flags,a,e.contextFromFlags,{interactiveOnly:!0}),i=tS(t.nodes);if(!i){return r=t,tj(r.nodes).detected?cX("COMMAND_FAILED","React Native overlay detected, but no safe dismiss target was found",{hint:"Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body."}):{ok:!0,data:{action:"dismiss-overlay",detected:!1,dismissed:!1,...eJ("No React Native overlay detected")}}}return await hw(e,s,t,i)}catch(e){return{ok:!1,error:k(e)}}}async function hw(e,t,r,n){let{req:i,sessionStore:a}=e,o=Date.now(),s=await cF(t.device,"press",[String(n.point.x),String(n.point.y)],i.flags?.out,e.contextFromFlags(i.flags,t.appBundleId,t.trace?.outPath))??{},l=Date.now(),u={...m0(r.nodes),...s,action:"dismiss-overlay",overlayAction:n.action,x:n.point.x,y:n.point.y,...n.ref?{ref:n.ref}:{},...n.label?{label:n.label}:{},...n.warning?{warning:n.warning}:{},dismissed:!0,verified:!1,verificationRequired:!0,nextCommand:"agent-device snapshot -i -c",...eJ("minimize"===n.action?"React Native RedBox minimize action sent; run snapshot -i before continuing":"React Native overlay dismiss action sent; run snapshot -i before continuing")};return mZ({session:t,sessionStore:a,command:i.command,positionals:i.positionals??[],flags:i.flags,result:u,responseData:u,actionStartedAt:o,actionFinishedAt:l})}function hg(e=process.env){let t=hI(),r=f.join(t,"home"),n=f.join(t,"module-cache");return l.mkdirSync(r,{recursive:!0}),l.mkdirSync(n,{recursive:!0}),{...e,HOME:r,CLANG_MODULE_CACHE_PATH:n}}async function hy(e){let t=l.statSync(e.sourcePath),r=l.readFileSync(e.sourcePath),n=hx(e.cacheName??f.basename(e.sourcePath,f.extname(e.sourcePath))),i=h_(["2",process.platform,process.arch,f.resolve(e.sourcePath),t.size,r]),a=f.join(hI(),"bin",`${n}-${i}`);return await hb({sourcePath:e.sourcePath,executablePath:a,timeoutMs:e.timeoutMs}),a}async function hv(e){let t=hx(e.cacheName),r=h_(["2",process.platform,process.arch,e.source]),n=f.join(hI(),"sources",`${t}-${r}.swift`),i=f.join(hI(),"bin",`${t}-${r}`);return await hb({sourcePath:n,executablePath:i,sourceText:e.source,timeoutMs:e.timeoutMs}),i}function hI(){let e=process.env.AGENT_DEVICE_SWIFT_CACHE_DIR?.trim();return e?f.resolve(e):f.join(c.tmpdir(),"agent-device-swift-cache")}async function hb(e){if(hS(e.executablePath))return;let t=f.dirname(e.executablePath);l.mkdirSync(t,{recursive:!0});let r=`${e.executablePath}.lock`;if(!await hA(r,e.executablePath,e.timeoutMs??12e4))return;let n=l.mkdtempSync(f.join(t,`.${f.basename(e.executablePath)}.${process.pid}.`)),i=f.join(n,f.basename(e.executablePath));try{if(hS(e.executablePath))return;void 0===e.sourceText||l.existsSync(e.sourcePath)||(l.mkdirSync(f.dirname(e.sourcePath),{recursive:!0}),l.writeFileSync(e.sourcePath,e.sourceText)),await R("xcrun",["swiftc",e.sourcePath,"-o",i],{timeoutMs:e.timeoutMs??12e4,env:hg()}),l.renameSync(i,e.executablePath)}finally{l.rmSync(n,{recursive:!0,force:!0}),l.rmSync(r,{recursive:!0,force:!0})}}async function hA(e,t,r){let n=Date.now()+r;for(;;){if(hS(t))return!1;try{return l.mkdirSync(e),!0}catch(t){if("EEXIST"!==t.code)throw t;if(function(e,t){try{return Date.now()-l.statSync(e).mtimeMs>=t}catch{return!1}}(e,r)){l.rmSync(e,{recursive:!0,force:!0});continue}if(Date.now()>=n)throw new D("COMMAND_FAILED",`Timed out waiting for Swift cache lock: ${e} (${r}ms)`,{lockDir:e,timeoutMs:r,hint:`Another agent-device process may still be compiling this Swift helper. Retry shortly; if no agent-device process is active, remove "${e}" and retry.`});await S(25)}}}function hS(e){try{return l.accessSync(e,l.constants.X_OK),l.statSync(e).isFile()}catch{return!1}}function hx(e){return e.replaceAll(/[^A-Za-z0-9._-]/g,"-").replaceAll(/^-+|-+$/g,"")||"swift-helper"}function h_(e){let t=s("sha256");for(let r of e)t.update(Buffer.isBuffer(r)?r:String(r)),t.update("\0");return t.digest("hex").slice(0,16)}let hN=`
35
- import Foundation
36
- import AVFoundation
37
-
38
- let url = URL(fileURLWithPath: CommandLine.arguments[1])
39
- let asset = AVURLAsset(url: url)
40
- let semaphore = DispatchSemaphore(value: 0)
41
- var exitCode: Int32 = 1
42
-
43
- Task {
44
- defer { semaphore.signal() }
45
- do {
46
- let playable = try await asset.load(.isPlayable)
47
- let duration = try await asset.load(.duration)
48
- if playable && duration.isValid && !duration.isIndefinite && CMTimeGetSeconds(duration) > 0 {
49
- exitCode = 0
50
- }
51
- } catch {
52
- exitCode = 1
53
- }
54
- }
55
-
56
- semaphore.wait()
57
- exit(exitCode)
58
- `.trim();async function hM(e,t={}){let r,n=t.pollMs??150,i=t.attempts??12,a=0;for(let t=0;t<i;t+=1){let t=0;try{t=l.statSync(e).size}catch{t=0}if(t>0&&t===r){if((a+=1)>=2)return}else a=0;r=t,await e8(n)}}async function hk(e){try{let t=await hD(),r=await R(t,[e],{allowFailure:!0,timeoutMs:1e4,env:hg()});if(0===r.exitCode)return!0;if(hP(r.stderr,r.stdout))return hR(e);return!1}catch(r){var t;if((t=r)instanceof D&&("TOOL_MISSING"===t.code||hP(String(t.details?.stderr??""),String(t.details?.stdout??""))))return hR(e);throw r}}async function hD(){t??=hv({source:hN,cacheName:"video-validator",timeoutMs:3e4});try{return await t}catch(e){throw t=void 0,e}}async function hO(e,t={}){let r=t.pollMs??150,n=t.attempts??12;for(let t=0;t<n;t+=1){if(await hk(e))return;await e8(r)}}function hP(e,t){let r=`${e}
59
- ${t}`;return/\b(no such module ['"]AVFoundation['"]|unable to find utility ["']swiftc?["']|xcrun: error: unable to find utility ["']swiftc?["'])\b/i.test(r)}function hR(e){try{let t=l.statSync(e);if(!t.isFile()||t.size<=0)return!1}catch{return!1}let t=function(e){try{let t=l.openSync(e,"r");try{let e=l.fstatSync(t).size,r=0,n=[];for(;r+8<=e&&n.length<16;){let e=Buffer.alloc(8);if(8>l.readSync(t,e,0,8,r))break;let i=e.readUInt32BE(0),a=e.toString("latin1",4,8);if(n.push(a),1===i){let e=Buffer.alloc(8);if(8>l.readSync(t,e,0,8,r+8))break;i=Number(e.readBigUInt64BE(0))}if(!Number.isFinite(i)||i<=0)break;r+=i}return n}finally{l.closeSync(t)}}catch{return[]}}(e);return t.includes("ftyp")&&t.includes("moov")}function hC(e){let t=f.parse(e);return f.join(t.dir,`${t.name}.gesture-telemetry.json`)}function hE(e){return[...e].sort((e,t)=>e.tMs-t.tMs)}function hL(e){let t=f.dirname(g(import.meta.url)),r=[g(new URL(`./${e}`,import.meta.url)),f.resolve(t,`../../ios-runner/AgentDeviceRunner/RecordingScripts/${e}`),f.resolve(t,`../../../ios-runner/AgentDeviceRunner/RecordingScripts/${e}`),f.resolve(process.cwd(),`ios-runner/AgentDeviceRunner/RecordingScripts/${e}`)];for(let e of r)if(l.existsSync(e))return e;throw new D("COMMAND_FAILED",`Missing recording helper script: ${e}`,{hint:"Ensure ios-runner/AgentDeviceRunner/RecordingScripts is present in this checkout or bundled with the package.",scriptName:e,searchedPaths:r})}async function hT(e){var t;let r,n,{videoPath:i,scriptPath:a,scriptArgs:o,commandDescription:s}=e;await hM(i),await hO(i);let u=(t=i,r=f.parse(t),n=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,f.join(r.dir,`.${r.name}.agent-device-${n}${r.ext||".mp4"}`));try{let e=await hy({sourcePath:a});await R(e,["--input",i,"--output",u,...o],{timeoutMs:12e4,env:hg()}),await hO(u),l.renameSync(u,i)}catch(t){let e=t instanceof D?t:new D("COMMAND_FAILED",String(t),void 0,t instanceof Error?t:void 0);throw new D("COMMAND_FAILED",s,{...e.details,videoPath:i,script:a},e)}finally{l.rmSync(u,{force:!0})}}async function h$(e){let{videoPath:t,trimStartMs:r}=e;r>0&&await hT({videoPath:t,scriptPath:n??=hL("recording-trim.swift"),scriptArgs:["--trim-start-ms",String(r)],commandDescription:"Failed to trim the start of the iOS recording"})}async function hF(e){let{videoPath:t,telemetryPath:n,targetLabel:i="recording"}=e;await hT({videoPath:t,scriptPath:r??=hL("recording-overlay.swift"),scriptArgs:["--events",n],commandDescription:`Failed to add touch overlays to the ${i}`})}async function hU(e){let{videoPath:t,quality:r,targetLabel:n="recording"}=e;await hT({videoPath:t,scriptPath:i??=hL("recording-resize.swift"),scriptArgs:["--quality",String(r)],commandDescription:`Failed to resize the ${n}`})}function hV(e){return e instanceof Error?e.message:String(e)}function hG(e,t){return e.stderr.trim()||e.stdout.trim()||`${t} exited with code ${e.exitCode}`}async function hq(e){let{recording:t,deps:r,trimStartMs:n,targetLabel:i}=e,a=function(e){var t,r,n;let i,a,{recording:o,trimStartMs:s}=e,u=(i=hC((t={videoPath:o.outPath,events:o.gestureEvents,trimStartMs:s}).videoPath),a={version:1,generatedAt:new Date().toISOString(),events:(r=t.events,(n=t.trimStartMs??0)>0?hE(r.flatMap(e=>{let t=e.tMs-n,r="durationMs"in e?e.durationMs:void 0;return("number"==typeof r?t+r:t)<=0?[]:[{...e,tMs:Math.max(0,t)}]})):hE(r))},l.writeFileSync(i,JSON.stringify(a,null,2)),i);return o.telemetryPath=u,u}({recording:t,trimStartMs:n});if(!t.showTouches)return void eN({level:"debug",phase:"record_stop_overlay_skipped",data:{reason:"hide_touches"}});if(0===t.gestureEvents.length)return void eN({level:"debug",phase:"record_stop_overlay_skipped",data:{reason:"no_gesture_events"}});let o=function(e=process.platform){if("darwin"!==e)return"touch overlay burn-in is only available on macOS hosts; returning raw video plus gesture telemetry"}();if(o){t.overlayWarning??=o;return}try{await e_("record_stop_overlay_export",()=>r.overlayRecordingTouches({videoPath:t.outPath,telemetryPath:a,targetLabel:i}),{targetLabel:i,gestureEventCount:t.gestureEvents.length})}catch(e){t.overlayWarning??=`failed to overlay recording touches: ${hV(e)}`}}async function hB(e,t,r){return await Z(z(e),t,r)}async function hj(e,t){let r=await hB(e,["shell","ps","-o","pid=","-p",t],{allowFailure:!0});return 0===r.exitCode&&r.stdout.split(/\s+/).map(e=>e.trim()).includes(t)}async function hH(e,t){for(let r=0;r<40;r+=1){if(!await hj(e,t))return!0;await e8(250)}return!await hj(e,t)}async function hW(e,t){let r,n=0;for(let i=0;i<20;i+=1){let i=await hB(e,["shell","stat","-c","%s",t],{allowFailure:!0}),a=0===i.exitCode?i.stdout.trim():"";if(a.length>0&&a===r){if((n+=1)>=4)return}else n=0;r=a,await e8(250)}}async function hz(e,t,r){for(let n=0;n<8;n+=1){let i=await hB(e,["shell","stat","-c","%s",t],{allowFailure:!0}),a=0===i.exitCode?Number(i.stdout.trim()):NaN;if(Number.isFinite(a)&&a>0)return!0;if(!await hj(e,r))break;if(n+1>=2)return!0;await e8(250)}return!1}async function hK(e){let t,{deps:r,deviceId:n,remotePath:i,outPath:a}=e;for(let e=0;e<2;e+=1){try{l.rmSync(a,{force:!0})}catch{}let o=z(n),s=await e7(i,a,{allowFailure:!0,device:o});if(0!==s.exitCode)t=hG(s,"adb pull");else{await r.waitForStableFile(a,{pollMs:250,attempts:20});let t=await r.isPlayableVideo(a);if(eN({level:"debug",phase:"record_stop_android_pull_validation",data:{deviceId:n,remotePath:i,outPath:a,attempt:e+1,fileSize:(()=>{try{return l.statSync(a).size}catch{return 0}})(),playable:t}}),t)return;eN({level:"warn",phase:"record_stop_android_invalid_video_retry",data:{deviceId:n,remotePath:i,outPath:a,attempt:e+1}})}e<1&&await e8(750)}return t?`failed to copy recording from device: ${t}`:"failed to copy recording from device: pulled file is not a playable MP4"}async function hJ(e){let{deviceId:t,quality:r}=e;if(void 0===r||r>=10)return;let n=await hB(t,["shell","wm","size"],{allowFailure:!0}),i=n.stdout.match(/Override size:\s*(\d+)x(\d+)/)??n.stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(0!==n.exitCode||!i)throw Error(`failed to resolve Android screen size for recording quality: ${hG(n,"adb shell wm size")}`);return{width:hX(Number(i[1]),r),height:hX(Number(i[2]),r)}}function hX(e,t){return Math.max(2,2*Math.round(e*t/10/2))}async function hZ(e,t){await hB(e,["shell","rm","-f",t],{allowFailure:!0})}async function hY(e,t){let r=await hB(e,["shell","kill","-9",t],{allowFailure:!0});return eN({level:"warn",phase:"record_stop_android_force_signal",data:{deviceId:e,remotePid:t,exitCode:r.exitCode,stdout:r.stdout.trim(),stderr:r.stderr.trim()}}),!(0!==r.exitCode&&await hj(e,t))&&await hH(e,t)}async function hQ(e){var t;let r,n,{device:i,recordingBase:a}=e,o="failed to start recording: Android screenrecord did not begin producing frames";try{r=await hJ({deviceId:i.id,quality:a.quality})}catch(e){return cX("COMMAND_FAILED",e instanceof Error?e.message:String(e))}for(let e of(t=Date.now(),n=`agent-device-recording-${t}.mp4`,[`/sdcard/${n}`,`/data/local/tmp/${n}`])){let t=await hB(i.id,["shell",function(e,t){let r=["screenrecord"];return t&&r.push("--size",`${t.width}x${t.height}`),r.push(e),`${r.join(" ")} >/dev/null 2>&1 & echo $!`}(e,r)],{allowFailure:!0});if(0!==t.exitCode){o=`failed to start recording: ${hG(t,"adb shell screenrecord")}`;continue}let n=t.stdout.split(/\r?\n/).map(e=>e.trim()).filter(e=>/^\d+$/.test(e)).at(-1);if(!n){o="failed to start recording: adb did not return a valid Android screenrecord pid",await hZ(i.id,e);continue}if(eN({level:"debug",phase:"record_start_android_started",data:{deviceId:i.id,remotePath:e,remotePid:n}}),await hz(i.id,e,n))return{platform:"android",remotePath:e,remotePid:n,...a,startedAt:Date.now()};o="failed to start recording: Android screenrecord did not begin producing frames",await hY(i.id,n),await hZ(i.id,e)}return cX("COMMAND_FAILED",o)}async function h0(e){let t,r,{deps:n,device:i,recording:a}=e;eN({level:"debug",phase:"record_stop_android_enter",data:{deviceId:i.id,remotePath:a.remotePath,remotePid:a.remotePid}});let o=await hB(i.id,["shell","kill","-2",a.remotePid],{allowFailure:!0});if(eN({level:"debug",phase:"record_stop_android_signal",data:{deviceId:i.id,remotePath:a.remotePath,remotePid:a.remotePid,exitCode:o.exitCode,stdout:o.stdout.trim(),stderr:o.stderr.trim()}}),0!==o.exitCode?await hj(i.id,a.remotePid)&&!await hY(i.id,a.remotePid)&&(t=`failed to stop recording: ${hG(o,"adb shell kill")}`):await hH(i.id,a.remotePid)||await hY(i.id,a.remotePid)||(t=`failed to stop recording: Android screenrecord pid ${a.remotePid} did not exit`),!t){await hW(i.id,a.remotePath);let e=await hK({deps:n,deviceId:i.id,remotePath:a.remotePath,outPath:a.outPath});if(e)return await s(),cX("COMMAND_FAILED",e);await hq({recording:a,deps:n,targetLabel:"Android recording"})}if(await s(),t)return cX("COMMAND_FAILED",t);if(r)return cX("COMMAND_FAILED",r);return null;async function s(){let e=await hB(i.id,["shell","rm","-f",a.remotePath],{allowFailure:!0});eN({level:"debug",phase:"record_stop_android_cleanup",data:{deviceId:i.id,remotePath:a.remotePath,exitCode:e.exitCode,stdout:e.stdout.trim(),stderr:e.stderr.trim()}}),0===e.exitCode||t||(r=`failed to clean up remote recording: ${hG(e,"adb shell rm")}`)}}function h1(e){let t=e.appBundleId?.trim();return t&&t.length>0?t:void 0}function h2(e,t,r){return{verbose:e.flags?.verbose,logPath:t,traceLogPath:r.trace?.outPath,requestId:e.meta?.requestId}}async function h3(e){let{req:t,activeSession:r,device:n,logPath:i,deps:a}=e,o=h1(r);try{await a.runIosRunnerCommand(n,{command:"recordStop",appBundleId:o},h2(t,i,r))}catch(e){eN({level:"warn",phase:"record_stop_runner_failed",data:{platform:n.platform,kind:n.kind,deviceId:n.id,session:r.name,error:hV(e)}})}}async function h5(e){let{req:t,activeSession:r,device:n,logPath:i,deps:a}=e,o=h1(r);if(o)try{await a.runIosRunnerCommand(n,{command:"snapshot",appBundleId:o,interactiveOnly:!0,compact:!0,depth:1},h2(t,i,r))}catch(e){eN({level:"warn",phase:"record_start_simulator_runner_warm_failed",data:{deviceId:n.id,session:r.name,appBundleId:o,error:hV(e)}})}}async function h4(e){let t,r,{req:n,activeSession:i,sessionStore:a,device:o,logPath:s,deps:l,fpsFlag:u,recordingBase:d,appBundleId:c}=e,p=`agent-device-recording-${Date.now()}.mp4`,f=`tmp/${p}`,m=h2(n,s,i),h=async()=>l.runIosRunnerCommand(o,{command:"recordStart",outPath:p,fps:u,quality:d.quality,appBundleId:c},m);try{let e=await h();t="number"==typeof e.recorderStartUptimeMs?e.recorderStartUptimeMs:void 0,r="number"==typeof e.targetAppReadyUptimeMs?e.targetAppReadyUptimeMs:void 0}catch(n){var w,g;if(!hV(n).toLowerCase().includes("recording already in progress"))return cX("COMMAND_FAILED",`failed to start recording: ${hV(n)}`);eN({level:"warn",phase:"record_start_runner_desynced",data:{platform:o.platform,kind:o.kind,deviceId:o.id,session:i.name,error:hV(n)}});let e=(w=o.id,g=i.name,a.toArray().find(e=>e.name!==g&&"ios"===e.device.platform&&"device"===e.device.kind&&e.device.id===w&&e.recording?.platform==="ios-device-runner"));if(e)return cX("COMMAND_FAILED",`failed to start recording: recording already in progress in session '${e.name}'`);try{await l.runIosRunnerCommand(o,{command:"recordStop",appBundleId:c},m)}catch{}try{let e=await h();t="number"==typeof e.recorderStartUptimeMs?e.recorderStartUptimeMs:void 0,r="number"==typeof e.targetAppReadyUptimeMs?e.targetAppReadyUptimeMs:void 0}catch(e){return cX("COMMAND_FAILED",`failed to start recording: ${hV(e)}`)}}return{platform:"ios-device-runner",remotePath:f,runnerStartedAtUptimeMs:t,targetAppReadyUptimeMs:r,...d}}async function h8(e){let{req:t,activeSession:r,device:n,logPath:i,deps:a,fpsFlag:o,recordingBase:s,appBundleId:l}=e;try{await a.runIosRunnerCommand(n,{command:"recordStart",outPath:s.outPath,fps:o,quality:s.quality,appBundleId:l},h2(t,i,r))}catch(e){return cX("COMMAND_FAILED",`failed to start recording: ${hV(e)}`)}return{platform:"macos-runner",...s}}async function h6(e){let{req:t,activeSession:r,device:n,logPath:i,deps:a,recording:o}=e;await h3({req:t,activeSession:r,device:n,logPath:i,deps:a});let s={stdout:"",stderr:"",exitCode:1};for(let e of nG)if(0===(s=await a.runCmd("xcrun",["devicectl","device","copy","from","--device",n.id,"--source",o.remotePath,"--destination",o.outPath,"--domain-type","appDataContainer","--domain-identifier",e],{allowFailure:!0})).exitCode)break;if(0!==s.exitCode){let e=s.stderr.trim()||s.stdout.trim()||`devicectl exited with code ${s.exitCode}`;return cX("COMMAND_FAILED",`failed to copy recording from device: ${e}`)}let l="number"!=typeof o.runnerStartedAtUptimeMs||"number"!=typeof o.targetAppReadyUptimeMs?0:Math.max(0,o.targetAppReadyUptimeMs-o.runnerStartedAtUptimeMs);return l>0&&await a.trimRecordingStart({videoPath:o.outPath,trimStartMs:l}),await hq({recording:o,deps:a,trimStartMs:l,targetLabel:"iOS recording"}),null}async function h9(e){let{req:t,activeSession:r,device:n,logPath:i,deps:a,recording:o}=e;return await h3({req:t,activeSession:r,device:n,logPath:i,deps:a}),await hq({recording:o,deps:a,targetLabel:"macOS recording"}),null}async function h7(e){let{deps:t,recording:r}=e;r.child.kill("SIGINT");let n=await we(r.wait,5e3);return n||(await wt(t,r,"SIGINT"),(n=await we(r.wait,2e3))||(r.child.kill("SIGTERM"),await wt(t,r,"SIGTERM"),n=await we(r.wait,2e3)))?n:(r.child.kill("SIGKILL"),await wt(t,r,"SIGKILL"),await we(r.wait,2e3))}async function we(e,t){return await Promise.race([e,e8(t).then(()=>null)])}async function wt(e,t,r){await wn(e,t,r)||await wr(e,t.outPath,r)}async function wr(e,t,r){let n,i=`simctl.*recordVideo.*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`;try{n=await e.runCmd("pgrep",["-f",i],{allowFailure:!0})}catch(e){eN({level:"warn",phase:"record_stop_ios_simulator_pgrep_failed",data:{outPath:t,signal:r,error:hV(e)}});return}let a=wa(ws(n.stdout)),o=wo(a,r);eN({level:o>0?"warn":"debug",phase:"record_stop_ios_simulator_signal_recorders",data:{outPath:t,signal:r,matchedPidCount:a.length,signaled:o,pgrepExitCode:n.exitCode}})}async function wn(e,t,r){let n=t.recorderPid??t.child.pid;if("number"!=typeof n||!Number.isInteger(n)||n<=0)return eN({level:"debug",phase:"record_stop_ios_simulator_owned_recorder_unavailable",data:{outPath:t.outPath,signal:r,reason:"missing_recorder_pid"}}),!1;let i=await wi(e,n,t.outPath,r),a=wa([n,...i.pids]),o=wo(a,r);return eN({level:o>0?"warn":"debug",phase:"record_stop_ios_simulator_signal_owned_recorder",data:{outPath:t.outPath,signal:r,recorderPid:n,childPidCount:i.pids.length,matchedPidCount:a.length,signaled:o,pgrepExitCode:i.exitCode}}),o>0}async function wi(e,t,r,n){let i;try{i=await e.runCmd("pgrep",["-P",String(t)],{allowFailure:!0})}catch(e){return eN({level:"warn",phase:"record_stop_ios_simulator_owned_pgrep_failed",data:{outPath:r,signal:n,parentPid:t,error:hV(e)}}),{pids:[]}}return{pids:ws(i.stdout),exitCode:i.exitCode}}function wa(e){return Array.from(new Set(e)).filter(e=>Number.isInteger(e)&&e>0&&e!==process.pid)}function wo(e,t){let r=0;for(let n of e)try{process.kill(n,t),r+=1}catch{}return r}function ws(e){return e.split(/\s+/).map(e=>Number(e)).filter(e=>Number.isInteger(e)&&e>0)}async function wl(e){"ios"!==e.platform||0!==e.gestureEvents.length&&await e8(350)}async function wu(e){for(let t=0;t<2;t+=1){try{if(l.statSync(e).size>0)return Date.now()}catch{}if(t+1>=2)break;await e8(250)}return Date.now()}async function wd(e){let t,r,{req:n,activeSession:i,device:a,logPath:o,deps:s,recordingBase:l,resolvedOut:u}=e;l.showTouches&&await h5({req:n,activeSession:i,device:a,logPath:o,deps:s});let{child:d,wait:c}=s.startIosSimulatorRecording({device:a,outPath:u}),p=await wu(u);if(l.showTouches)try{let e=Date.now(),l=await s.runIosRunnerCommand(a,{command:"uptime",appBundleId:h1(i)},h2(n,o,i)),u=Date.now();t=Math.round((e+u)/2),r="number"==typeof l.currentUptimeMs?l.currentUptimeMs:void 0}catch{}return{platform:"ios",child:d,wait:c,...l,recorderPid:d.pid,startedAt:p,gestureClockOriginAtMs:void 0===r?void 0:t,gestureClockOriginUptimeMs:r}}async function wc(e){let t,{req:r,sessionName:n,sessionStore:i,activeSession:a,device:o,logPath:s,deps:u}=e;if(a.recording)return cX("INVALID_ARGS","recording already in progress");let d=r.flags?.fps,c=r.flags?.quality;if(void 0!==d&&(!Number.isInteger(d)||d<1||d>120))return cX("INVALID_ARGS","fps must be an integer between 1 and 120");if(void 0!==c&&(!Number.isInteger(c)||c<5||c>10))return cX("INVALID_ARGS","quality must be an integer between 5 and 10");if(!pd("record",o))return cX("UNSUPPORTED_OPERATION","record is not supported on this device");let p=r.positionals?.[1]??`./recording-${Date.now()}.mp4`,m=i4.expandHome(p,r.meta?.cwd),h={outPath:m,clientOutPath:r.meta?.clientArtifactPaths?.outPath,startedAt:Date.now(),quality:r.flags?.quality,showTouches:r.flags?.hideTouches!==!0,gestureEvents:[]};if(l.mkdirSync(f.dirname(m),{recursive:!0}),l.rmSync(m,{force:!0}),"ios"===o.platform&&"device"===o.kind){let e=h1(a);if(!e)return cX("INVALID_ARGS","record on physical iOS devices requires an active app session; run open <app> first");t=await h4({req:r,activeSession:a,sessionStore:i,device:o,logPath:s,deps:u,fpsFlag:d,recordingBase:h,appBundleId:e})}else if("macos"===o.platform){let e=h1(a);if(!e)return cX("INVALID_ARGS","record on macOS requires an active app session; run open <app> first");t=await h8({req:r,activeSession:a,device:o,logPath:s,deps:u,fpsFlag:d,recordingBase:h,appBundleId:e})}else t="ios"===o.platform?await wd({req:r,activeSession:a,device:o,logPath:s,deps:u,recordingBase:h,resolvedOut:m}):await hQ({device:o,recordingBase:h});return"ok"in t?t:(a.recording=t,i.set(n,a),i.recordAction(a,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:{action:"start",showTouches:t.showTouches}}),{ok:!0,data:{recording:"started",outPath:t.clientOutPath??p,showTouches:t.showTouches}})}async function wp(e){let{deps:t,device:r,recording:n}=e;if("android"===n.platform)return await h0({deps:t,device:r,recording:n});await e_("record_stop_tail_settle",()=>t.waitForRecordingTail(n),{platform:n.platform,gestureEventCount:n.gestureEvents.length});let i=await e_("record_stop_ios_simulator_process",()=>h7({deps:t,recording:n}),{outPath:n.outPath});if(!i)return cX("COMMAND_FAILED","failed to stop recording: simctl recordVideo did not exit after 5000ms and forced cleanup");if(0!==i.exitCode)return cX("COMMAND_FAILED",`failed to stop recording: ${hG(i,"simctl recordVideo")}`);if(await e_("record_stop_video_stable",()=>t.waitForStableFile(n.outPath,{pollMs:150,attempts:12}),{outPath:n.outPath}),!await e_("record_stop_video_playable_check",()=>t.isPlayableVideo(n.outPath),{outPath:n.outPath}))return cX("COMMAND_FAILED",`failed to stop recording: ${n.outPath} was not finalized into a playable video`);if(void 0!==n.quality&&n.quality<10){let e=n.quality;try{await e_("record_stop_resize",()=>t.resizeRecording({videoPath:n.outPath,quality:e,targetLabel:"iOS recording"}),{outPath:n.outPath,quality:e})}catch(e){n.overlayWarning=`failed to resize recording: ${hV(e)}`}}return await e_("record_stop_finalize_overlay",()=>hq({recording:n,deps:t,targetLabel:"iOS recording"}),{outPath:n.outPath,showTouches:n.showTouches,gestureEventCount:n.gestureEvents.length}),null}async function wf(e){var t;let r,{req:n,activeSession:i,device:a,logPath:o,deps:s}=e;if(!i.recording)return cX("INVALID_ARGS","no active recording");let l=i.recording,u=l.invalidatedReason;i.recording=void 0;let d="ios-device-runner"===l.platform?await h6({req:n,activeSession:i,device:a,logPath:o,deps:s,recording:l}):"macos-runner"===l.platform?await h9({req:n,activeSession:i,device:a,logPath:o,deps:s,recording:l}):await wp({deps:s,device:a,recording:l});if(d)return d;if(u&&"ios"===l.platform&&l.showTouches)l.overlayWarning??=`overlay unavailable: ${u}`;else if(u)return cX("COMMAND_FAILED",u);return r=[{field:"outPath",path:(t=l).outPath,localPath:t.clientOutPath,fileName:f.basename(t.clientOutPath??t.outPath)}],t.telemetryPath&&r.push({field:"telemetryPath",path:t.telemetryPath,localPath:function(e){if(e.clientOutPath)return hC(e.clientOutPath)}(t),fileName:f.basename(t.telemetryPath)}),{ok:!0,data:{recording:"stopped",outPath:t.outPath,telemetryPath:t.telemetryPath,artifacts:r,showTouches:t.showTouches,overlayWarning:t.overlayWarning}}}async function wm(e){let{req:t,sessionName:r,sessionStore:n,logPath:i}=e,a={runCmd:async(e,t,r)=>"xcrun"===e?await rU(t,r):await R(e,t,r),startIosSimulatorRecording:e=>c4.resolve(void 0).startIosSimulatorRecording(e),runIosRunnerCommand:iP,waitForRecordingTail:wl,waitForStableFile:hM,isPlayableVideo:hk,trimRecordingStart:h$,resizeRecording:hU,overlayRecordingTouches:hF},o=n.get(r),s=o?.device??await oW(t.flags??{});o||await sp(s);let l=o??{name:r,device:s,createdAt:Date.now(),actions:[]},u=(t.positionals?.[0]??"").toLowerCase();if(!["start","stop"].includes(u))return cX("INVALID_ARGS","record requires start|stop");if("start"===u)return wc({req:t,sessionName:r,sessionStore:n,activeSession:l,device:s,logPath:i,deps:a});let d=await wf({req:t,activeSession:l,device:s,logPath:i,deps:a});return d.ok&&n.recordAction(l,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{action:"stop",outPath:d.data?.outPath,showTouches:d.data?.showTouches}}),d}async function wh(e){let{req:t,sessionName:r,sessionStore:n,logPath:i}=e,a=t.command;if("record"===a)return wm({req:t,sessionName:r,sessionStore:n,logPath:i});if("trace"===a){let e=(t.positionals?.[0]??"").toLowerCase();if(!["start","stop"].includes(e))return cX("INVALID_ARGS","trace requires start|stop");let i=n.get(r);if(!i)return cX("SESSION_NOT_FOUND","No active session");if("start"===e){if(i.trace)return cX("INVALID_ARGS","trace already in progress");let e=t.positionals?.[1]??n.defaultTracePath(i),r=i4.expandHome(e);return l.mkdirSync(f.dirname(r),{recursive:!0}),l.appendFileSync(r,""),i.trace={outPath:r,startedAt:Date.now()},n.recordAction(i,{command:a,positionals:t.positionals??[],flags:t.flags??{},result:{action:"start",outPath:r}}),{ok:!0,data:{trace:"started",outPath:r}}}if(!i.trace)return cX("INVALID_ARGS","no active trace");let o=i.trace.outPath;if(t.positionals?.[1]){let e=i4.expandHome(t.positionals[1]);l.mkdirSync(f.dirname(e),{recursive:!0}),l.existsSync(o)?l.renameSync(o,e):l.appendFileSync(e,""),o=e}return i.trace=void 0,n.recordAction(i,{command:a,positionals:t.positionals??[],flags:t.flags??{},result:{action:"stop",outPath:o}}),{ok:!0,data:{trace:"stopped",outPath:o}}}return null}let ww=new Map;async function wg(e){let t=await A.mkdtemp(f.join(c.tmpdir(),"agent-device-materialized-"));try{let r=await wI(e.installablePath,f.join(t,"installable")),n=e.archivePath?await wI(e.archivePath,f.join(t,"archive")):void 0,i=o.randomUUID(),a=e.ttlMs??9e5,s=Date.now()+a,l=setTimeout(()=>{wy(i)},a);return ww.set(i,{rootPath:t,installablePath:r,archivePath:n,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:s,timer:l}),{materializationId:i,installablePath:r,...n?{archivePath:n}:{},expiresAt:new Date(s).toISOString()}}catch(e){throw await A.rm(t,{recursive:!0,force:!0}),e}}async function wy(e,t){let r=ww.get(e);if(!r)throw new D("INVALID_ARGS",`Materialized paths not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new D("UNAUTHORIZED","Materialized paths belong to a different tenant");clearTimeout(r.timer),ww.delete(e),await A.rm(r.rootPath,{recursive:!0,force:!0})}async function wv(e){let t=Array.from(ww.entries()).filter(([,t])=>t.sessionName===e).map(([e])=>e);await Promise.all(t.map(async e=>{await wy(e)}))}async function wI(e,t){let r=await A.stat(e);await A.mkdir(t,{recursive:!0});let n=f.join(t,f.basename(e));return r.isDirectory()?await A.cp(e,n,{recursive:!0}):await A.copyFile(e,n),n}async function wb(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new D("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await sp(e.session.device),e.session.device}if(!r)throw new D("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let n=await oW(e.flags??{});return await sp(n),n}async function wA(e){let{prepared:t,retention:r,req:n,session:i,sessionName:a}=e;if(r.enabled)return await wg({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:n.meta?.tenantId,sessionName:i?a:void 0,ttlMs:r.ttlMs})}function wS(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function wx(e){let{req:t,sessionName:r,sessionStore:n}=e,i=n.get(r);try{let e,a,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new D("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new D("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new D("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new D("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new D("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(a=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:aK(a,t.meta?.tenantId)},cleanup:()=>{aJ(a)}}:{source:e,cleanup:()=>{}}),s=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new D("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),l=await wb({session:i,flags:t.flags});if(!pd("install",l))return cX("UNSUPPORTED_OPERATION","install_from_source is not supported on this device");let u=rS(t.meta?.requestId),d=async(e,a)=>{let l;try{var u;l=await wA({prepared:e,retention:s,req:t,session:i,sessionName:r});let o=await a(l),d=eV(o,(u=o,`Installed: ${e3(u)}`));return!function(e){let{session:t,sessionStore:r,req:n,data:i}=e;t&&r.recordAction(t,{command:"install_source",positionals:[],flags:n.flags??{},result:i})}({session:i,sessionStore:n,req:t,data:d}),{ok:!0,data:d}}catch(e){throw l&&await wy(l.materializationId,t.meta?.tenantId).catch(()=>{}),e}finally{await e.cleanup(),o.cleanup()}};if("ios"===l.platform){let{installIosInstallablePath:e}=await Promise.resolve(rc),{prepareIosInstallArtifact:t}=await Promise.resolve(rp),r=await t(o.source,{signal:u});return await d(r,async t=>{if(await e(l,r.installablePath),!r.bundleId)throw new D("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");return{...wS(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:c}=await import("../1769.js"),{installAndroidInstallablePathAndResolvePackageName:p}=await import("../1769.js"),f=await c(o.source,{signal:u});return await d(f,async e=>{let t=await p(l,f.installablePath,f.packageName);if(!t)throw new D("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let{inferAndroidAppName:r}=await import("../1769.js"),n=r(t);return{...wS(e),packageName:t,...n?{appName:n}:{},launchTarget:t}})}catch(e){return{ok:!1,error:k(e)}}}async function w_(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new D("INVALID_ARGS","release_materialized_paths requires a materializationId");return await wy(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:k(e)}}}let wN="shared_prefs/ReactNativeDevPrefs.xml",wM="debug_http_host",wk="dev_server_https",wD="RCT_jsLocation",wO="RCT_packager_scheme",wP="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.",wR='<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n</map>\n';function wC(e){return void 0!==ey(e)}async function wE(e){let{device:t,appId:r,runtime:n}=e;if(!r)return;let i=ey(n);if(i){if("android"===t.platform)return void await wT(t,r,i);"ios"===t.platform&&"simulator"===t.kind&&await wV(t,r,i)}}async function wL(e){let{device:t,appId:r}=e;if(r){if("android"===t.platform)return void await w$(t,r);"ios"===t.platform&&"simulator"===t.kind&&await wG(t,r)}}async function wT(e,t,r){var n,i,a,o,s,l;let u,d;wH(t);let c=(n=await wF(e,t),i=wM,a=`${r.host}:${r.port}`,u=` <string name="${wW(i)}">${wW(a)}</string>`,wB(wj(n,i),u));o=c,s=wk,l="https"===r.scheme,d=` <boolean name="${wW(s)}" value="${l?"true":"false"}" />`,c=wB(wj(o,s),d),await wU(e,t,c)}async function w$(e,t){wH(t);let r=await wF(e,t),n=wj(r,wM),i=wj(n,wk);i!==r&&await wU(e,t,i)}async function wF(e,t){let r=await Z(e,["shell","run-as",t,"cat",wN],{allowFailure:!0});return 0!==r.exitCode?wR:wq(r.stdout)}async function wU(e,t,r){let n=["shell","run-as",t,"id"],i=await Z(e,n,{allowFailure:!0});if(0!==i.exitCode){let e=wz(i.stdout,i.stderr);throw new D("COMMAND_FAILED",e?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,{package:t,cmd:"adb",args:n,stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,hint:e?wP:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await Z(e,["shell","run-as",t,"mkdir","-p","shared_prefs"]),await Z(e,["shell","run-as",t,"tee",wN],{stdin:r.trimEnd()})}catch(n){let e=M(n);if("TOOL_MISSING"===e.code)throw e;let r=wz("string"==typeof e.details?.stdout?e.details.stdout:"","string"==typeof e.details?.stderr?e.details.stderr:"");throw new D("COMMAND_FAILED",r?`Failed to access Android app sandbox for ${t}`:`Failed to write Android runtime hints for ${t}`,{...e.details??{},package:t,cmd:"adb",phase:"write-runtime-hints",hint:r?wP:"adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command."},e)}}async function wV(e,t,r){await rU(rB(e,["spawn",e.id,"defaults","write",t,wD,"-string",`${r.host}:${r.port}`])),await rU(rB(e,["spawn",e.id,"defaults","write",t,wO,"-string",r.scheme]))}async function wG(e,t){await rU(rB(e,["spawn",e.id,"defaults","delete",t,wD]),{allowFailure:!0}),await rU(rB(e,["spawn",e.id,"defaults","delete",t,wO]),{allowFailure:!0})}function wq(e){let t=e.trim();return t.includes("<map")&&t.includes("</map>")?`${t}
60
- `:wR}function wB(e,t){return wq(e).replace("</map>",`${t}
61
- </map>`)}function wj(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return wq(e).replace(RegExp(`^\\s*<string name="${r}">[\\s\\S]*?<\\/string>\\n?`,"m"),"").replace(RegExp(`^\\s*<boolean name="${r}" value="(?:true|false)"\\s*\\/?>\\n?`,"m"),"")}function wH(e){if("binary"!==ec(e))return;let t=X(e);throw new D("INVALID_ARGS",t,{package:e,hint:t})}function wW(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function wz(e,t){let r=`${e}
62
- ${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=>r.includes(e))}let wK=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function wJ(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function wX(e,t){if(void 0!==e){if("string"!=typeof e)throw new D("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return ew(e)}}function wZ(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new D("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function wY(e){if("ios"===e||"android"===e)return e}async function wQ(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:n,session:i}=e;!t||!i?.appBundleId||!wC(r)||wC(n)||await wL({device:i.device,appId:i.appBundleId})}async function w0(e){var t,r;let{req:n,sessionName:i,sessionStore:a}=e,o=(n.positionals?.[0]??"show").toLowerCase(),s=a.get(i),l=a.getRuntimeHints(i);if(!["set","show","clear"].includes(o))return cX("INVALID_ARGS","runtime requires set, show, or clear");if("clear"===o){wC(l)&&s?.appBundleId&&await wL({device:s.device,appId:s.appBundleId});let e=a.clearRuntimeHints(i);return{ok:!0,data:{session:i,cleared:e}}}if("show"===o)return{ok:!0,data:{session:i,configured:!!l,runtime:l}};let u=wY(n.flags?.platform??l?.platform??s?.device.platform);if(!u)return cX("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(s&&s.device.platform!==u)return cX("INVALID_ARGS",`runtime set targets ${u}, but session "${i}" is already bound to ${s.device.platform}.`);let d={platform:(t=n.flags,r={platform:u,metroHost:ew(t?.metroHost),metroPort:wZ(t?.metroPort),bundleUrl:ew(t?.bundleUrl),launchUrl:ew(t?.launchUrl)}).platform??l?.platform,metroHost:r.metroHost??l?.metroHost,metroPort:r.metroPort??l?.metroPort,bundleUrl:r.bundleUrl??l?.bundleUrl,launchUrl:r.launchUrl??l?.launchUrl};return 0===wJ(d)?cX("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(a.setRuntimeHints(i,d),{ok:!0,data:{session:i,configured:!0,runtime:d}})}let w1="open-command-roundtrip",w2="Not implemented for this platform in this release.",w3=new Set(["app","desktop","frontmost-app"]);async function w5(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await um();return{appBundleId:t.bundleId,appName:t.appName}}function w4(e){let t=e.replaceAll(",","").match(/^-?\d+(?:\.\d+)?/);if(!t)return null;let r=Number(t[0]);return Number.isFinite(r)?r:null}function w8(e){return Math.round(10*e)/10}function w6(e){return Math.round(10*e)/10}let w9="adb-shell-dumpsys-gfxinfo-framestats";function w7(e,t,r){let n=t.get(r);if(void 0===n)return null;let i=Number(e[n]);return Number.isFinite(i)?i:null}function ge(e){return 0===e.length?{}:{firstFrameNs:Math.min(...e.map(e=>e.intendedVsyncNs)),lastFrameNs:Math.max(...e.map(e=>e.frameCompletedNs))}}function gt(e,t){if(void 0!==e&&void 0!==t)return Math.max(0,Math.round((t-e)/1e6))}function gr(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=e.match(RegExp(`^\\s*${r}:\\s*([0-9][0-9,]*)`,"im"));if(!n)return;let i=n[1];return void 0===i?void 0:w4(i)??void 0}async function gn(e,t,r={}){var n,i,a,o,s,l,u,d;let c=tn(e,r.adb);try{let u,d,p,f,m,h,w,g,y,v,I,b=(n=(await c(["shell","dumpsys","gfxinfo",t,"framestats"],{timeoutMs:15e3})).stdout,i=new Date().toISOString(),function(e,t){if(/no process found for:/i.test(e))throw new D("COMMAND_FAILED",`Android gfxinfo did not find a running process for ${t}`,{metric:"fps",package:t,hint:"Run open <app> for this session again to ensure the Android app is active, then retry perf after the interaction you want to inspect."})}(n,t),p=function(e){let t=e.split(/\nProfile data in ms:\n/i)[0]??"",r=gr(t,"Total frames rendered"),n=t.match(/^\s*Janky frames:\s*([0-9][0-9,]*)\s*\(([0-9.]+)%\)/im);if(void 0===r||!n)return;let i=n[1],a=n[2];if(void 0===i||void 0===a)return;let o=w4(i)??void 0,s=Number(a);if(void 0===o||!Number.isFinite(s)||r<0)return;let l=gr(t,"Uptime"),u=gr(t,"Stats since");return{droppedFramePercent:w8(s),droppedFrameCount:o,totalFrameCount:r,sampleWindowMs:function(e){let{uptimeMs:t,statsSinceNs:r}=e;if(void 0===t||void 0===r)return;let n=t-Math.round(r/1e6);return n>=0?n:void 0}({uptimeMs:l,statsSinceNs:u}),uptimeMs:l,statsSinceNs:u}}(n),f=function(e){let t=[],r=null;for(let i of e.split("\n")){var n;let e=i.trim();if(0===e.length||"---PROFILEDATA---"===e)continue;let a=e.split(",").map(e=>e.trim());if((n=a).includes("IntendedVsync")&&n.includes("FrameCompleted")){r=new Map(a.map((e,t)=>[e,t]));continue}let o=function(e,t){if(!t||e.length<t.size)return;let r=w7(e,t,"Flags"),n=w7(e,t,"IntendedVsync"),i=w7(e,t,"FrameCompleted");if(0===r&&null!==n&&null!==i&&!(n<=0)&&!(i<=n))return{intendedVsyncNs:n,frameCompletedNs:i,durationNs:i-n}}(a,r);o&&t.push(o)}return t.sort((e,t)=>e.intendedVsyncNs-t.intendedVsyncNs)}(n),m=function(e,t,r){let n=function(e){var t;let r=(t=e.map(e=>e.intendedVsyncNs),[...new Set(t.filter(e=>Number.isFinite(e)))].sort((e,t)=>e-t)),n=[];for(let e=1;e<r.length;e+=1){let t=r[e]-r[e-1];t>=4e6&&t<=5e7&&n.push(t)}if(0!==n.length){let e,t;return e=[...n].sort((e,t)=>e-t),t=Math.floor(e.length/2),e.length%2==1?e[t]:(e[t-1]+e[t])/2}}(e);if(t||0!==e.length||function(e){throw new D("COMMAND_FAILED",`Failed to parse Android framestats output for ${e}`,{metric:"fps",package:e,hint:"Retry perf after exercising the app screen. If the problem persists, capture adb shell dumpsys gfxinfo <package> framestats output for debugging."})}(r),t||void 0!==n)return n;throw new D("COMMAND_FAILED",`Failed to infer Android frame deadline from framestats output for ${r}`,{metric:"fps",package:r,hint:"Retry perf after a longer interaction window so consecutive Android frame timestamps are available."})}(f,p,t),h=Date.parse(i),w=function(e){let{frames:t,measuredAtMs:r,summary:n}=e,i=ge(t),a=n?.statsSinceNs,o=a??i.firstFrameNs,s=gt(o,i.lastFrameNs),l=n?.sampleWindowMs??s;if(!Number.isFinite(r)||n?.uptimeMs===void 0||void 0===o)return{sampleWindowMs:l,windowStartNs:o};let u=r-n.uptimeMs;return{sampleWindowMs:l,windowStartNs:o,windowStartedAt:new Date(u+o/1e6).toISOString(),windowEndedAt:function(e){let{deviceBootWallClockMs:t,measuredAtMs:r,summaryStartNs:n,lastFrameNs:i}=e;return void 0!==n?new Date(r).toISOString():void 0===i?void 0:new Date(t+i/1e6).toISOString()}({deviceBootWallClockMs:u,measuredAtMs:r,summaryStartNs:a,lastFrameNs:i.lastFrameNs}),timestampSource:"estimated-from-device-uptime"}}({frames:f,measuredAtMs:h,summary:p}),g=function(e){let{frames:t,frameDeadlineNs:r,summaryDroppedFrameCount:n}=e;return void 0!==n?n<=0?[]:[...t].sort((e,t)=>t.durationNs-e.durationNs).slice(0,n).sort((e,t)=>e.intendedVsyncNs-t.intendedVsyncNs):void 0===r?[]:t.filter(e=>e.durationNs>r)}({frames:f,frameDeadlineNs:m,summaryDroppedFrameCount:p?.droppedFrameCount}),y=p?.sampleWindowMs??w.sampleWindowMs??function(e){if(0===e.length)return;let t=ge(e);return gt(t.firstFrameNs,t.lastFrameNs)}(f),a=p,o=f,s=g,u=a?.totalFrameCount??o.length,d=a?.droppedFrameCount??s.length,v={totalFrameCount:u,droppedFrameCount:d,droppedFramePercent:a?.droppedFramePercent??(u>0?w8(d/u*100):0)},I=function(e){let{droppedFrames:t,timing:r,measuredAtMs:n,summary:i}=e;if(0===t.length)return;let a=function(e){let{frames:t,windowStartNs:r,measuredAtMs:n,uptimeMs:i}=e;if(0===t.length||void 0===r)return[];let a=[],o=[];for(let e of t){let t=o.at(-1);if(!t||e.intendedVsyncNs-t.frameCompletedNs<=5e8){o.push(e);continue}a.push(o),o=[e]}return o.length>0&&a.push(o),a.map(e=>(function(e){let{frames:t,windowStartNs:r,measuredAtMs:n,uptimeMs:i}=e,a=Math.min(...t.map(e=>e.intendedVsyncNs)),o=Math.max(...t.map(e=>e.frameCompletedNs)),s=Math.max(0,Math.round((a-r)/1e6)),l=Math.max(s,Math.round((o-r)/1e6)),u=void 0!==i&&Number.isFinite(n)?n-i:void 0;return{startOffsetMs:s,endOffsetMs:l,startAt:void 0===u?void 0:new Date(u+a/1e6).toISOString(),endAt:void 0===u?void 0:new Date(u+o/1e6).toISOString(),missedDeadlineFrameCount:t.length,worstFrameMs:w6(Math.max(...t.map(e=>e.durationNs))/1e6)}})({frames:e,windowStartNs:r,measuredAtMs:n,uptimeMs:i})).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}({frames:t,windowStartNs:r.windowStartNs,measuredAtMs:n,uptimeMs:i?.uptimeMs});return a.length>0?a:void 0}({droppedFrames:g,timing:w,measuredAtMs:h,summary:p}),{...v,sampleWindowMs:y,...(l=m,{frameDeadlineMs:void 0===l?void 0:w6(l/1e6),refreshRateHz:void 0===l?void 0:w6(1e9/l)}),windowStartedAt:w.windowStartedAt,windowEndedAt:w.windowEndedAt,timestampSource:w.timestampSource,measuredAt:i,method:w9,source:p?"android-gfxinfo-summary":"framestats-rows",worstWindows:I&&I.length>0?I:void 0});return await gi(e,t,r),b}catch(e){throw u=t,(d=e)instanceof D?new D(d.code,d.message,{...d.details??{},metric:"fps",package:u},d):new D("COMMAND_FAILED",`Failed to sample Android fps for ${u}`,{metric:"fps",package:u},d)}}async function gi(e,t,r={}){let n=tn(e,r.adb);try{await n(["shell","dumpsys","gfxinfo",t,"reset"],{allowFailure:!0,timeoutMs:3e3})}catch{}}let ga="adb-shell-dumpsys-cpuinfo",go="adb-shell-dumpsys-meminfo";async function gs(e,t,r={}){let n=tn(e,r.adb);try{let e=await n(["shell","dumpsys","cpuinfo"],{timeoutMs:15e3});return function(e,t,r){let n=new Set,i=0;for(let r of eG(e)){var a,o;let e=r.match(/^([0-9]+(?:\.[0-9]+)?)%\s+\d+\/([^\s]+):\s/);if(!e)continue;let s=e[1],l=e[2];if(void 0===s||void 0===l)continue;let u=Number(s);Number.isFinite(u)&&(a=l,o=t,a===o||a.startsWith(`${o}:`))&&(i+=u,n.add(l))}return{usagePercent:w8(i),measuredAt:r,method:ga,matchedProcesses:[...n]}}(e.stdout,t,new Date().toISOString())}catch(e){throw gu("cpu",t,e)}}async function gl(e,t,r={}){let n=tn(e,r.adb);try{let e=await n(["shell","dumpsys","meminfo",t],{timeoutMs:15e3});return function(e,t,r){if(/no process found for:/i.test(e))throw new D("COMMAND_FAILED",`Android meminfo did not find a running process for ${t}`,{metric:"memory",package:t,hint:"Run open <app> for this session again to ensure the Android app is active, then retry perf."});let n=gd(e,"TOTAL PSS")??function(e){for(let t of e.split("\n")){let e=t.trim();if(!/^TOTAL\b(?!\s+PSS:)/.test(e))continue;let r=e.split(/\s+/).slice(1).find(e=>null!==w4(e));if(!r)break;return w4(r)??void 0}}(e);if(void 0===n)throw new D("COMMAND_FAILED",`Failed to parse Android meminfo output for ${t}`,{metric:"memory",package:t,hint:"Retry perf after reopening the app session. If the problem persists, capture adb shell dumpsys meminfo output for debugging."});return{totalPssKb:n,totalRssKb:gd(e,"TOTAL RSS"),measuredAt:r,method:go}}(e.stdout,t,new Date().toISOString())}catch(e){throw gu("memory",t,e)}}function gu(e,t,r){return r instanceof D?new D(r.code,r.message,{...r.details??{},metric:e,package:t},r):new D("COMMAND_FAILED",`Failed to sample Android ${e} for ${t}`,{metric:e,package:t},r)}function gd(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=e.match(RegExp(`${r}:\\s*([0-9][0-9,]*)`,"i"));if(!n)return;let i=n[1];return void 0===i?void 0:w4(i)??void 0}async function gc(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return em(t)?"macos"===e.platform?void 0:"device"===e.kind?ee(r,t):en(t)?void 0:r??await gp(e,t):await gf(e,t)}async function gp(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await Promise.resolve(rc);return await r(e,t)}catch{return}}async function gf(e,t){try{let{resolveIosApp:r}=await Promise.resolve(rc);return await r(e,t)}catch{return}}async function gm(e,t){if(!("android"!==e.platform||!t||em(t)))try{let{resolveAndroidApp:r}=await import("../1769.js"),n=await r(e,t);return"package"===n.type?n.value:void 0}catch{return}}async function gh(e,t,r){if(r||"android"!==e.platform||!t||!em(t))return r;try{let{getAndroidAppState:t}=await import("../1769.js"),n=await t(e);return n.package?.trim()||r}catch{return r}}async function gw(e,t,r,n){return await gc(e,t,r)??await n(e,t)??("android"===e.platform&&t&&em(t)?r:void 0)}function gg(e){return cX("INVALID_ARGS",e)}function gy(e,t,r,n){try{return function(e){let{device:t,surfaceFlag:r,openTarget:n,existingSurface:i}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return i??"app";if("linux"===t.platform){if(!r)return"app";let e=tq(r);if(!w3.has(e))throw new D("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&n)throw new D("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new D("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let a=r?tq(r):"app";if("app"!==a&&"menubar"!==a&&n)throw new D("INVALID_ARGS",`open --surface ${a} does not accept an app target`);return a}({device:e,surfaceFlag:t,openTarget:r,existingSurface:n})}catch(e){return cX(e instanceof D?e.code:"INVALID_ARGS",String(e.message))}}function gv(e){let{shouldRelaunch:t,openTarget:r,surface:n,device:i}=e;return t?r&&em(r)?gg("open --relaunch does not support URL targets."):"app"!==n?gg("open --relaunch is supported only for app surfaces."):"android"===i.platform&&r&&"binary"===ec(r)?gg(X(r)):null:null}async function gI(e){let{req:t,sessionName:r,sessionStore:n,device:i,surface:a,openTarget:o,existingSession:s}=e;await sp(i);let{appBundleId:l,appName:u}=await gb({device:i,surface:a,openTarget:o,existingAppBundleId:s?.appBundleId}),d=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:n,device:i}=e,a=r.getRuntimeHints(n),o=function(e){let{runtime:t,sessionName:r,platform:n}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new D("INVALID_ARGS","open runtime must be an object.");let i=Object.keys(t).find(e=>!wK.includes(e));if(i)throw new D("INVALID_ARGS",`Invalid open runtime field: ${i}. Supported fields are ${wK.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new D("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new D("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,n),metroHost:wX(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new D("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return wZ(e)}}(t.metroPort),bundleUrl:wX(t.bundleUrl,"bundleUrl"),launchUrl:wX(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:n,platform:wY(i.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let n=e.getRuntimeHints(t);if(!n)return;let i=r?.platform,a=wY(i);if(n.platform&&r&&!a)throw new D("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${i}.`);if(n.platform&&a&&n.platform!==a)throw new D("INVALID_ARGS",`Session runtime hints target ${n.platform}, but session "${t}" is bound to ${i}. Clear the runtime hints or use a different session.`);return a&&n.platform!==a?{...n,platform:a}:n}(r,n,i),previousRuntime:a,replacedStoredRuntime:!1}:{runtime:o&&wJ(o)>0?o:void 0,previousRuntime:a,replacedStoredRuntime:!0}}(e)}}catch(t){let e=M(t);return cX(e.code,e.message,e.details)}}({req:t,sessionStore:n,sessionName:r,device:i});if(!d.ok)return{type:"response",response:d};if(s){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=d.data;await wQ({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:s})}return{type:"details",details:{appBundleId:l,appName:u,runtime:d.data.runtime}}}async function gb(e){let{device:t,surface:r,openTarget:n,existingAppBundleId:i}=e,a=await w5(r);return{appBundleId:a.appBundleId??await gw(t,n,i,gm),appName:a.appName??n}}let gA=new Map;async function gS(e){let{device:t,closeTarget:r,outFlag:n,context:i}=e;"android"!==t.platform&&await iy(t.id),await cF(t,"close",[r],n,i),await c0(t,300)}async function gx(e){var t,r;let n,{runtime:i,device:a,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,c=i?.launchUrl;if(!c||0===d.length||d.length>1)return;let p=d[0]?.trim();!p||em(p)||await cF(a,"open",[c],o.flags?.out,{...(t=s,r=o.flags,n=pg(t,r,l,u),delete n.launchConsole,n)})}async function g_(e){var t,r,n,i;let a,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:c,openPositionals:p,appName:f,surface:m,appBundleId:h,runtime:w,existingSession:g}=e,y=o.flags?.relaunch===!0,v=g?.trace?.outPath,I=h,b=Date.now(),A={};if(y&&c){let e=I??c,t=Date.now();await gS({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...pg(u,o.flags,I??g?.appBundleId,v)}}),A.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let S=Date.now();await wE({device:d,appId:I,runtime:w}),A.runtimeHintsDurationMs=Math.max(0,Date.now()-S);let x="ios"===d.platform&&"app"===m&&p.length>0,_={verbose:o.flags?.verbose,logPath:u,traceLogPath:v,requestId:o.meta?.requestId};x&&I&&(A.runnerPrewarmKind="session",A.runnerPrewarmScheduled=!0,a=function(e,t={}){return"ios"!==e.platform?void 0:!function(e,t={}){return void 0!==ik(e,t)}(e,{requestId:t.requestId})?im(e,t).then(()=>{}).catch(t=>{eN({level:"warn",phase:"ios_runner_session_prewarm_failed",data:{deviceId:e.id,error:t instanceof Error?t.message:String(t)}})}):void eN({level:"debug",phase:"ios_runner_session_prewarm_skipped_scoped_provider",data:{deviceId:e.id}})}(d,_));let N=Date.now();await cF(d,"open",p,o.flags?.out,{...pg(u,o.flags,I)}),A.openDispatchDurationMs=Math.max(0,Date.now()-N);let M=Date.now();if(await gx({runtime:w,device:d,req:o,logPath:u,appBundleId:I,traceLogPath:v,openPositionals:p}),A.launchUrlDurationMs=Math.max(0,Date.now()-M),y&&a){let e=Date.now();await a,A.runnerPrewarmWaited=!0,A.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else a&&(A.runnerPrewarmWaited=!1);I=await gh(d,c,I),"android"===d.platform&&I&&await gi(d,I);let k=c?(t=I,{durationMs:Math.max(0,Date.now()-N),measuredAt:new Date().toISOString(),method:w1,appTarget:c,appBundleId:t}):void 0,D=Date.now();if(await c0(d,300),A.postOpenSettleDurationMs=Math.max(0,Date.now()-D),rA(o.meta?.requestId)){let e=rx();return cX(e.code,e.message,e.details)}g&&pp(g,"open",g.snapshot);let O=function(e){let{existingSession:t,sessionName:r,device:n,surface:i,appBundleId:a,appName:o,saveScript:s}=e;return t?{...t,device:n,surface:i,appBundleId:a,appName:o,recordSession:t.recordSession||s,snapshot:void 0}:{name:r,device:n,createdAt:Date.now(),surface:i,appBundleId:a,appName:o,recordSession:s,actions:[]}}({existingSession:g,sessionName:s,device:d,surface:m,appBundleId:I,appName:f,saveScript:!!o.flags?.saveScript});void 0!==o.runtime&&(r=l,n=s,(i=w)&&(0===wJ(i)?r.clearRuntimeHints(n):r.setRuntimeHints(n,i))),A.totalDurationMs=Math.max(0,Date.now()-b);let P=function(e){let{sessionName:t,appName:r,appBundleId:n,surface:i,startup:a,timing:o,device:s,runtime:l,runtimeHintCount:u}=e,d={session:t,surface:i};return r&&(d.appName=r),n&&(d.appBundleId=n),a&&(d.startup=a),o&&(d.timing=o),l&&u(l)>0&&(d.runtime=l),s&&(d.platform=s.platform,d.target=s.target??"mobile",d.device=s.name,d.id=s.id,d.kind=s.kind,"android"===s.platform&&(d.serial=s.id)),s?.platform==="ios"&&(d.device_udid=s.id,d.ios_simulator_device_set=s.simulatorSetPath??null),{...d,...eJ(`Opened: ${r??n??t}`)}}({sessionName:s,appName:f,appBundleId:I,surface:m,startup:k,timing:A,device:d,runtime:w,runtimeHintCount:wJ});return l.recordAction(O,{command:"open",positionals:p,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:P}),l.set(s,O),{ok:!0,data:P}}async function gN(e){let{req:t,sessionName:r,logPath:n,sessionStore:i}=e;if(i.has(r)){let e=i.get(r);if(!e)return cX("SESSION_NOT_FOUND",`Session "${r}" not found.`);let a=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(a?e.appName:void 0),l=gy(e.device,t.flags?.surface,s,e.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return a?gg("open --relaunch requires an app name or an active session app."):gg("Session already active. Close it first or pass a new --session name.");let u=gv({shouldRelaunch:a,openTarget:s,surface:l,device:e.device});if(u)return u;let d=await c2(e.device),c=await gI({req:t,sessionName:r,sessionStore:i,device:d,surface:l,openTarget:s,existingSession:e});return"response"===c.type?c.response:await g_({req:t,sessionName:r,sessionStore:i,logPath:n,device:d,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:c.details.appBundleId,appName:c.details.appName,runtime:c.details.runtime,surface:l,existingSession:e})}let a=t.flags?.relaunch===!0,o=t.positionals?.[0];if(a&&!o)return gg("open --relaunch requires an app argument.");let s=function(e){let{shouldRelaunch:t,openTarget:r,platform:n}=e;return t?r&&em(r)?gg("open --relaunch does not support URL targets."):"android"===n&&r&&"binary"===ec(r)?gg(X(r)):null:null}({shouldRelaunch:a,openTarget:o,platform:t.flags?.platform==="android"?"android":void 0});if(s)return s;let l=await oW(t.flags??{}),u=gy(l,t.flags?.surface,o);if("string"!=typeof u)return u;let d=gv({shouldRelaunch:a,openTarget:o,surface:u,device:l});return d||await nr(gA,l.id,async()=>{let e=i.toArray().find(e=>e.device.id===l.id);if(e)return cX("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:l.id,deviceName:l.name,hint:`Run agent-device session list and reuse --session ${e.name}, or close that session before opening a new one on this device.`});let a=await gI({req:t,sessionName:r,sessionStore:i,device:l,surface:u,openTarget:o});return"response"===a.type?a.response:await g_({req:t,sessionName:r,sessionStore:i,logPath:n,device:l,openTarget:o,openPositionals:t.positionals??[],appBundleId:a.details.appBundleId,appName:a.details.appName,runtime:a.details.runtime,surface:u})})}async function gM(e){let t=await Z(e,["emu","kill"],{allowFailure:!0,timeoutMs:15e3});return{success:0===t.exitCode,exitCode:t.exitCode,stdout:String(t.stdout??""),stderr:String(t.stderr??"")}}async function gk(e){let{device:t,shutdownRequested:r}=e;if(r&&(cQ(t)||"android"===t.platform&&"emulator"===t.kind))try{return cQ(t)?await l2(t):await gM(t)}catch(t){let e=k(t);return{success:!1,exitCode:-1,stdout:"",stderr:e.message,error:e}}}async function gD(e){if(await iy(e.device.id),"macos"!==e.device.platform)return;let t="frontmost-app"===e.surface?{surface:"frontmost-app"}:e.appBundleId?{bundleId:e.appBundleId}:{};await ug("dismiss",t).catch(t=>{eN({level:"debug",phase:"macos_close_alert_dismiss_failed",data:{session:e.name,error:t instanceof Error?t.message:String(t)}})})}async function gO(e,t){e.appLog&&await aG(e.appLog),nn(e.device.platform)&&await gD(e),await wv(t).catch(()=>{})}async function gP(e){let t,{req:r,sessionName:n,logPath:i,sessionStore:a}=e,o=a.get(n);if(!o)return await gR(r,i);o.appLog&&await aG(o.appLog),r.positionals&&r.positionals.length>0&&(nn(o.device.platform)&&await gD(o),await cF(o.device,"close",r.positionals,r.flags?.out,{...pg(i,r.flags,o.appBundleId,o.trace?.outPath)}),await c0(o.device,300)),nn(o.device.platform)&&(t=(r.positionals?.length??0)>0,!cQ(o.device)||t||r.flags?.shutdown||o.recording)?await gD(o):nn(o.device.platform)&&eN({level:"debug",phase:"ios_runner_retained_after_close",data:{session:o.name,deviceId:o.device.id}}),wC(a.getRuntimeHints(n))&&o.appBundleId&&await wL({device:o.device,appId:o.appBundleId}).catch(()=>{}),a.recordAction(o,{command:"close",positionals:r.positionals??[],flags:r.flags??{},result:{session:n,...eJ(`Closed: ${n}`)}}),r.flags?.saveScript&&(o.recordSession=!0),a.writeSessionLog(o),await wv(n).catch(()=>{}),a.delete(n);let s=await gk({device:o.device,shutdownRequested:r.flags?.shutdown});return s?{ok:!0,data:eV({session:n,shutdown:s},`Closed: ${n}`)}:{ok:!0,data:{session:n,...eJ(`Closed: ${n}`)}}}async function gR(e,t){if(!e.positionals||0===e.positionals.length)return cX("SESSION_NOT_FOUND","No active session");let r=await c1({session:void 0,flags:e.flags,ensureReady:!0});return await cF(r,"close",e.positionals,e.flags?.out,{...pg(t,e.flags)}),await c0(r,300),{ok:!0,data:{app:e.positionals[0],...eJ(`Closed: ${e.positionals[0]}`)}}}let gC={ios:async(e,t,r)=>{let{reinstallIosApp:n}=await Promise.resolve(rc);return await n(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:n}=await import("../1769.js");return await n(e,t,r)}},gE={ios:async(e,t,r)=>{let{installIosApp:n}=await Promise.resolve(rc),i=await n(e,r,{appIdentifierHint:t});return{bundleId:i.bundleId,appName:i.appName,launchTarget:i.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:n}=await import("../1769.js"),i=await n(e,r);return{package:i.packageName,appName:i.appName,launchTarget:i.launchTarget}}};async function gL(e){let{req:t,command:r,sessionName:n,sessionStore:i,deployOps:a}=e,o=i.get(n),s=t.flags??{},u=cZ(r,o,s);if(u)return u;let d=t.positionals?.[0]?.trim(),c=t.positionals?.[1]?.trim();if(!d||!c)return cX("INVALID_ARGS",`${r} requires: ${r} <app> <path-to-app-binary>`);let p=t.meta?.uploadedArtifactId;try{var f;let e,n=p?aK(p,t.meta?.tenantId):i4.expandHome(c);if(!l.existsSync(n))return cX("INVALID_ARGS",`App binary not found: ${n}`);let u=await c1({session:o,flags:s,ensureReady:!1});if(!pd(r,u))return cX("UNSUPPORTED_OPERATION",`${r} is not supported on this device`);if("ios"===u.platform){let t=await a.ios(u,d,n),r=t.bundleId;e=r?{app:d,appPath:n,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:n,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await a.android(u,d,n),r=t.package;e=r?{app:d,appPath:n,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:n,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}let m=eV(e,(f=e,`Installed: ${f.appName??eL(f)}`));return o&&i.recordAction(o,{command:r,positionals:t.positionals??[],flags:t.flags??{},result:m??{}}),{ok:!0,data:m}}finally{p&&aJ(p)}}async function gT(e,t,r){return await rl(e,t,r)}async function g$(e){let{req:t,sessionName:r,sessionStore:n}=e;if("session_list"===t.command)return{ok:!0,data:{sessions:n.toArray().map(e=>({name:e.name,platform:e.device.platform,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,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}))}};if("devices"===t.command)try{let e=ep(t.flags?.androidDeviceAllowlist),r=t.flags?.platform,n=na({simulatorSetPath:Y(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),i=await oX({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:n,androidSerialAllowlist:e?Array.from(e).sort():void 0}),a=r?i.filter(e=>{var t,n;return t=e,!(n=r)||("apple"===n?nn(t.platform):t.platform===n)}):i,o=(t.flags?.target?a.filter(e=>(e.target??"mobile")===t.flags?.target):a).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=M(t);return cX(e.code,e.message,e.details)}if("apps"===t.command){let e=n.get(r),i=t.flags??{},a=cZ(t.command,e,i);if(a)return a;let o=await c1({session:e,flags:i,ensureReady:!0});if(!pd("apps",o))return cX("UNSUPPORTED_OPERATION","apps is not supported on this device");let s=rd(t.flags?.appsFilter);return nn(o.platform)?{ok:!0,data:{apps:(await dh(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await H(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function gF(e){let{ensureAndroidEmulatorBooted:t}=await import("../1769.js");return await t(e)}let gU='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',gV='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function gG(e){let{req:t,sessionName:r,sessionStore:n}=e,i=n.get(r),a=t.flags??{},o=a.platform;if(!i&&"string"==typeof a?.session&&a.session.trim().length>0)return cX("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=cZ("appstate",i,a);if(s)return s;let l=nn(i?.device.platform)&&function(e,t){if(!t)return!1;if(!cY(e))return!0;let r=e?.platform;return!(r&&!ni(t.device.platform,r)||e?.target&&e.target!==(t.device.target??"mobile")||e?.udid&&e.udid!==t.device.id||e?.serial&&e.serial!==t.device.id)&&(!e?.device||e.device.trim().toLowerCase()===t.device.name.trim().toLowerCase())}(a,i);if("ios"===o&&!l)return cX("SESSION_NOT_FOUND",gU);if("macos"===o&&!l)return cX("SESSION_NOT_FOUND",gV);if(l&&i){let e=i.appName??i.appBundleId;if(!i.appName&&!i.appBundleId){if("macos"===i.device.platform&&i.surface&&"app"!==i.surface&&"frontmost-app"!==i.surface)return{ok:!0,data:{platform:i.device.platform,appName:i.surface,appBundleId:i.appBundleId,source:"session",surface:i.surface}};let e="macos"===i.device.platform?"macOS":"iOS";return cX("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:i.device.platform,appName:e??"unknown",appBundleId:i.appBundleId,source:"session",surface:i.surface??"app",..."ios"===i.device.platform?{device_udid:i.device.id,ios_simulator_device_set:i.device.simulatorSetPath??null}:{}}}}let u=await c1({session:i,flags:a,ensureReady:!0});if("ios"===u.platform)return cX("SESSION_NOT_FOUND",gU);if("macos"===u.platform)return cX("SESSION_NOT_FOUND",gV);let{getAndroidAppState:d}=await import("../1769.js"),c=await d(u);return{ok:!0,data:{platform:"android",package:c.package,activity:c.activity}}}async function gq(e){let{req:t,sessionName:r,sessionStore:n}=e;if("boot"===t.command){let e,i=n.get(r),a=t.flags??{},o=cZ(t.command,i,a);if(o)return o;let s="android"===(a.platform??i?.device.platform),l=!0===a.headless;if(l&&!s)return cX("INVALID_ARGS","boot --headless is supported only for Android emulators.");let u=c3({flags:a,sessionDevice:i?.device}),d=s&&!!u,c=!1;try{e=await c1({session:i,flags:a,ensureReady:!1})}catch(r){let t=M(r);if(s&&l&&!u&&"DEVICE_NOT_FOUND"===t.code)return cX("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!d||"DEVICE_NOT_FOUND"!==t.code||!u)throw r;e=await gF({avdName:u,serial:a.serial,headless:l}),c=!0}if(a.target&&(e.target??"mobile")!==a.target)return cX("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${a.target}.`);if(s&&l){if("android"!==e.platform||"emulator"!==e.kind)return cX("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!c){let t=c3({flags:a,sessionDevice:i?.device,resolvedDevice:e});if(!t)return cX("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await gF({avdName:t,serial:a.serial,headless:!0})}await sp(e)}else("android"!==e.platform||!0!==e.booted)&&await sp(e);return pd("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:cX("UNSUPPORTED_OPERATION","boot is not supported on this device")}return"appstate"===t.command?await gG({req:t,sessionName:r,sessionStore:n}):null}function gB(e,t){for(let r of e){if(t(r))return r;let e=gB(r.children,t);if(e)return e}}function gj(e,t){let r=[];for(let n of e)t(n)&&r.push(n),r.push(...gj(n.children,t));return r}function gH(e,t){let r=gB(e,e=>"schema"===e.name&&e.attributes.name===t);return r?r.children.filter(e=>"col"===e.name).map(e=>{let t;return t=e.children.find(e=>"mnemonic"===e.name),t?.text??null??""}):[]}function gW(e){if(!e||e.children.some(e=>"sentinel"===e.name)||!e.text)return null;let t=Number(e.text);return Number.isFinite(t)?t:null}function gz(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.numberValue??null:gW(e):null}let gK="xctrace-animation-hitches";function gJ(e,t){let r=nf(e),n=gH(r,t);return{rows:0===n.length?[]:gj(r,e=>"row"===e.name),schema:n}}function gX(e,t){for(let r of e)gX(r.children,t),r.attributes.id&&t.set(r.attributes.id,{numberValue:gW(r),process:gZ(r)})}function gZ(e){if(!e||e.children.some(e=>"sentinel"===e.name))return null;let t=gW(gB(e.children,e=>"pid"===e.name)),r=(e.attributes.fmt??"").replace(/\s+\(\d+\)$/,"").trim();return null===t&&0===r.length?null:{pid:t??void 0,name:r.length>0?r:void 0}}let gY="ps-process-snapshot",gQ="ps-process-snapshot",g0="xctrace-activity-monitor",g1="xctrace-activity-monitor";async function g2(e,t){if("ios"===e.platform&&"device"===e.kind)return await yr(e,t);let r=await yt(e,t),n=await yl(e,r);if(0===n.length)throw new D("COMMAND_FAILED",`No running process found for ${t}`,{appBundleId:t,hint:"Run open <app> for this session again to ensure the Apple app is active, then retry perf."});let i=new Date().toISOString();return yu({usagePercent:n.reduce((e,t)=>e+t.cpuPercent,0),residentMemoryKb:n.reduce((e,t)=>e+t.rssKb,0),measuredAt:i,matchedProcesses:[r.executableName],cpuMethod:gY,memoryMethod:gQ})}async function g3(e,t){var r;let n,i,a,o,s,l;if("ios"!==e.platform||"device"!==e.kind)throw new D("COMMAND_FAILED","Apple frame-health sampling is currently available only on connected iOS devices.",{metric:"fps",platform:e.platform,deviceKind:e.kind});let u=await yn(e,t),d=await g5(e,t,u);return n=gJ((r={hitchesXml:d.hitchesXml,frameLifetimesXml:d.frameLifetimesXml,displayInfoXml:d.displayInfoXml,processIds:u.map(e=>e.pid),processNames:iT(u.map(e=>f.basename(g(e.executable)))),windowStartedAt:d.windowStartedAt,windowEndedAt:d.windowEndedAt,measuredAt:d.windowEndedAt}).frameLifetimesXml,"hitches-frame-lifetimes").rows.length,i=function(e){if(!e)return;let{rows:t,schema:r}=gJ(e,"device-display-info"),n=r.indexOf("max-refresh-rate");if(n<0)return;let i=new Map;for(let e of t){gX(e.children,i);let t=gz(e.children[n],i);if(null!==t&&t>0)return t}}(r.displayInfoXml),o=(a=(function(e){let t,r,n=nf(e),i=Object.values(r={start:(t=gH(n,"hitches")).indexOf("start"),duration:t.indexOf("duration"),process:t.indexOf("process"),isSystem:t.indexOf("is-system")}).every(e=>e>=0)?r:null;if(!i)return[];let a=new Map;return gj(n,e=>"row"===e.name).map(e=>(function(e,t,r){var n,i,a;let o;if(gX(e.children,r),!0===(n=e.children[t.isSystem],null===(o=gz(n,r))?null:0!==o))return null;let s=gz(e.children[t.start],r),l=gz(e.children[t.duration],r);if(null===s||null===l)return null;let u=(i=e.children[t.process],a=r,i?i.attributes.ref?a.get(i.attributes.ref)?.process??null:gZ(i):null);return{startNs:s,durationNs:l,pid:u?.pid,processName:u?.name}})(e,i,a)).filter(e=>!!e)})(r.hitchesXml).filter(e=>{var t,n,i;return t=e,n=r.processIds,i=r.processNames,!!(void 0!==t.pid&&n.includes(t.pid))||!!t.processName&&i.includes(t.processName)})).length,s=Math.max(0,Math.round(Date.parse(r.windowEndedAt)-Date.parse(r.windowStartedAt))),l=function(e,t){if(0===e.length)return[];let r=[...e].sort((e,t)=>e.startNs-t.startNs),n=[],i=[];for(let e of r){let t=i.at(-1);if(!t||e.startNs-(t.startNs+t.durationNs)<=5e8){i.push(e);continue}n.push(i),i=[e]}return i.length>0&&n.push(i),n.map(e=>{var r,n;let i,a,o,s;return r=e,n=t,i=Math.min(...r.map(e=>e.startNs)),a=Math.max(...r.map(e=>e.startNs+e.durationNs)),s=Math.max(o=Math.max(0,Math.round(i/1e6)),Math.round(a/1e6)),{startOffsetMs:o,endOffsetMs:s,startAt:new Date(n+o).toISOString(),endAt:new Date(n+s).toISOString(),missedDeadlineFrameCount:r.length,worstFrameMs:w8(Math.max(...r.map(e=>e.durationNs))/1e6)}}).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}(a,Date.parse(r.windowStartedAt)),{droppedFramePercent:n>0?w8(o/n*100):0,droppedFrameCount:o,totalFrameCount:n,sampleWindowMs:s,windowStartedAt:r.windowStartedAt,windowEndedAt:r.windowEndedAt,measuredAt:r.measuredAt,method:gK,matchedProcesses:[...new Set(a.map(e=>e.processName).filter(e=>"string"==typeof e&&e.length>0))],frameDeadlineMs:void 0===i?void 0:w8(1e3/i),refreshRateHz:i,worstWindows:l.length>0?l:void 0}}async function g5(e,t,r){let n=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-frame-perf-")),i=f.join(n,"animation-hitches.trace"),a=f.join(n,"hitches.xml"),o=f.join(n,"frame-lifetimes.xml"),s=f.join(n,"display-info.xml");try{let n=await g4({device:e,appBundleId:t,tracePath:i,template:"Animation Hitches",duration:"2s",targetPids:r.map(e=>e.pid),validateTraceOutput:!0,failureMessage:`Failed to record iOS frame-health sample for ${t}`});await g9(e,t,i,"hitches",a),await g9(e,t,i,"hitches-frame-lifetimes",o);let l=await g7(e,t,i,"device-display-info",s);return{windowStartedAt:n.startedAt,windowEndedAt:n.endedAt,hitchesXml:await d.readFile(a,"utf8"),frameLifetimesXml:await d.readFile(o,"utf8"),displayInfoXml:l?await d.readFile(s,"utf8"):void 0}}finally{await d.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}async function g4(e){let{device:t,appBundleId:r,tracePath:n,template:i,duration:a}=e,o=e.allProcesses?["--all-processes"]:(e.targetPids??[]).flatMap(e=>["--attach",String(e)]),s=["xctrace","record","--template",i,"--device",t.id,...o,"--time-limit",a,"--output",n,"--quiet","--no-prompt"],l=await g8(s,e.tracePath);if(0===l.result.exitCode)return e.validateTraceOutput&&await g6(e,l.result.stdout,l.result.stderr),{startedAt:l.startedAt,endedAt:l.endedAt,capturedAtMs:l.capturedAtMs};throw new D("COMMAND_FAILED",e.failureMessage,{cmd:"xcrun",args:s,exitCode:l.result.exitCode,stdout:l.result.stdout,stderr:l.result.stderr,appBundleId:r,deviceId:t.id,hint:yc(l.result.stdout,l.result.stderr)})}async function g8(e,t){let r;for(let n=1;n<=3;n+=1){n>1&&(await d.rm(t,{recursive:!0,force:!0}).catch(()=>{}),await new Promise(e=>setTimeout(e,1500)));let i=new Date().toISOString(),a=await rU(e,{allowFailure:!0,timeoutMs:6e4});if(r={result:a,startedAt:i,endedAt:new Date().toISOString(),capturedAtMs:Date.now()},0===a.exitCode||!function(e){let t=`${e.stdout}
63
- ${e.stderr}`.toLowerCase();return t.includes("_lockkperf")||t.includes("could not lock kperf")||t.includes("likely another session just started")}(a))break}return r}async function g6(e,t,r){let n=await d.stat(e.tracePath).catch(()=>null);if(!(n?.isDirectory()===!0?(await d.readdir(e.tracePath).catch(()=>[])).length>0:(n?.size??0)>0))throw new D("COMMAND_FAILED",`${e.failureMessage}: xctrace produced no trace data`,{tracePath:e.tracePath,appBundleId:e.appBundleId,deviceId:e.device.id,stdout:t,stderr:r,hint:"Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf."})}async function g9(e,t,r,n,i){let a=["xctrace","export","--input",r,"--xpath",`/trace-toc/run/data/table[@schema="${n}"]`,"--output",i],o=await rU(a,{allowFailure:!0,timeoutMs:15e3});if(0!==o.exitCode)throw new D("COMMAND_FAILED",`Failed to export iOS device ${n} data`,{cmd:"xcrun",args:a,exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr,appBundleId:t,deviceId:e.id,hint:yc(o.stdout,o.stderr)})}async function g7(e,t,r,n,i){try{return await g9(e,t,r,n,i),!0}catch{return!1}}async function ye(e){let t=nf(e),r=gH(t,"activity-monitor-process-live");if(0===r.length)throw new D("COMMAND_FAILED","Failed to parse xctrace activity-monitor-process-live schema");let n=r.indexOf("pid"),i=r.indexOf("process"),a=r.indexOf("cpu-total"),o=r.indexOf("memory-real");if(n<0||i<0||a<0||o<0)throw new D("COMMAND_FAILED","xctrace activity-monitor-process-live export is missing expected columns");let s=gj(t,e=>"row"===e.name),l=[],u=new Map;for(let e of s){var d,c;let t=e.children;if(0===t.length)continue;for(let e of t){let t=gB(e.children,e=>"pid"===e.name&&"string"==typeof e.attributes.id);if(t?.attributes.id){let e=Number(t.text);u.set(t.attributes.id,{numberValue:Number.isFinite(e)?e:null})}e.attributes.id&&u.set(e.attributes.id,{numberValue:gW(e),processName:yd(e)})}let r=gz(t[n],u),s=(d=t[i],c=u,d?d.attributes.ref?c.get(d.attributes.ref)?.processName??null:yd(d):null);null!==r&&Number.isFinite(r)&&s&&l.push({pid:r,processName:s,cpuTimeNs:gz(t[a],u),residentMemoryBytes:gz(t[o],u)})}return l}async function yt(e,t){let r="macos"===e.platform?await yo(t):await ys(e,t),n="macos"===e.platform?f.join(r,"Contents","Info.plist"):f.join(r,"Info.plist"),i=await l5(n,"CFBundleExecutable");if(!i)throw new D("COMMAND_FAILED",`Failed to resolve executable for ${t}`,{appBundleId:t,appPath:r});return{executableName:i,executablePath:"macos"===e.platform?f.join(r,"Contents","MacOS",i):f.join(r,i)}}async function yr(e,t){let r=await yn(e,t),n=await yi(e,t),i=await yi(e,t),a=ya(await ye(n.xml),r,t,e),o=ya(await ye(i.xml),r,t,e),s=i.capturedAtMs-n.capturedAtMs;if(s<=0)throw new D("COMMAND_FAILED",`Invalid Activity Monitor sample window for ${t}`,{appBundleId:t,deviceId:e.id});if(null===a.cpuTimeNs||null===o.cpuTimeNs||null===o.residentMemoryBytes)throw new D("COMMAND_FAILED",`Incomplete Activity Monitor sample for ${t}`,{appBundleId:t,deviceId:e.id,hint:"Keep the app running in the foreground while perf samples the device, then retry."});return yu({usagePercent:Math.max(0,o.cpuTimeNs-a.cpuTimeNs)/(1e6*s)*100,residentMemoryKb:o.residentMemoryBytes/1024,measuredAt:new Date(i.capturedAtMs).toISOString(),matchedProcesses:o.matchedProcesses,cpuMethod:g0,memoryMethod:g1})}async function yn(e,t){let r=(await so(e,"all")).find(e=>e.bundleId===t);if(!r)throw new D("APP_NOT_INSTALLED",`No iOS device app found for ${t}`,{appBundleId:t,deviceId:e.id});if(!r.url)throw new D("COMMAND_FAILED",`Missing app bundle URL for ${t}`,{appBundleId:t,deviceId:e.id});let n=r.url.replace(/\/$/,""),i=g(n),a=(await ss(e)).filter(e=>e.executable.startsWith(`${n}/`));if(0===a.length)throw new D("COMMAND_FAILED",`No running process found for ${t}`,{appBundleId:t,deviceId:e.id,appBundlePath:i,hint:"Run open <app> for this session again to ensure the iOS app is active, then retry perf."});return a}async function yi(e,t){let r=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-perf-")),n=f.join(r,"sample.trace"),i=f.join(r,"activity-monitor-process-live.xml");try{let r=await g4({device:e,appBundleId:t,tracePath:n,template:"Activity Monitor",duration:"1s",allProcesses:!0,failureMessage:`Failed to record iOS device Activity Monitor sample for ${t}`});return await g9(e,t,n,"activity-monitor-process-live",i),{capturedAtMs:r.capturedAtMs,xml:await d.readFile(i,"utf8")}}finally{await d.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}function ya(e,t,r,n){let i=new Set(t.map(e=>e.pid)),a=new Set(t.map(e=>f.basename(g(e.executable)))),o=e.filter(e=>i.has(e.pid)||a.has(e.processName));if(0===o.length)throw new D("COMMAND_FAILED",`No Activity Monitor sample found for ${r}`,{appBundleId:r,deviceId:n.id,hint:"Keep the app running in the foreground while perf samples the device, then retry."});let s=new Map;for(let e of o){let t=s.get(e.pid);if(!t){s.set(e.pid,e);continue}s.set(e.pid,{pid:e.pid,processName:e.processName||t.processName,cpuTimeNs:yp(t.cpuTimeNs,e.cpuTimeNs),residentMemoryBytes:yp(t.residentMemoryBytes,e.residentMemoryBytes)})}let l=[...s.values()],u=l.map(e=>e.cpuTimeNs).filter(e=>null!==e),d=l.map(e=>e.residentMemoryBytes).filter(e=>null!==e);return{cpuTimeNs:u.length>0?u.reduce((e,t)=>e+t,0):null,residentMemoryBytes:d.length>0?d.reduce((e,t)=>e+t,0):null,matchedProcesses:iT(l.map(e=>e.processName))}}async function yo(e){let t=`kMDItemCFBundleIdentifier == "${e.replaceAll('"','\\"')}"`,r=await rF("mdfind",[t],{allowFailure:!0,timeoutMs:15e3});if(0!==r.exitCode)throw new D("COMMAND_FAILED",`Failed to resolve macOS app bundle for ${e}`,{appBundleId:e,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});let n=r.stdout.split("\n").map(e=>e.trim()).find(e=>e.endsWith(".app"));if(!n)throw new D("APP_NOT_INSTALLED",`No macOS app found for ${e}`,{appBundleId:e});return n}async function ys(e,t){let r=rB(e,["get_app_container",e.id,t,"app"]),n=await rU(r,{allowFailure:!0,timeoutMs:15e3});if(0!==n.exitCode)throw new D("COMMAND_FAILED",`Failed to resolve iOS simulator app container for ${t}`,{appBundleId:t,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,hint:"Ensure the iOS simulator app is installed and booted, then retry perf."});let i=n.stdout.trim();if(0===i.length)throw new D("APP_NOT_INSTALLED",`No iOS simulator app container found for ${t}`,{appBundleId:t});return i}async function yl(e,t){let r="macos"===e.platform?["-axo","pid=,%cpu=,rss=,command="]:rB(e,["spawn",e.id,"ps","-axo","pid=,%cpu=,rss=,command="]);return(function(e){let t=[];for(let r of eG(e)){let e=r.match(/^(\d+)\s+([0-9]+(?:\.[0-9]+)?)\s+(\d+)\s+(.+)$/);if(!e)continue;let[n,i,a,o]=e.slice(1);if(void 0===n||void 0===i||void 0===a||void 0===o)continue;let s=Number(n),l=Number(i),u=Number(a),d=o.trim();Number.isFinite(s)&&Number.isFinite(l)&&Number.isFinite(u)&&t.push({pid:s,cpuPercent:l,rssKb:u,command:d})}return t})(("macos"===e.platform?await rF("ps",r,{timeoutMs:15e3}):await rU(r,{timeoutMs:15e3})).stdout).filter(e=>{var r,n;let i;return r=e.command,n=t,i=function(e){let[t=""]=e.trim().split(/\s+/,1);return t}(r),!!(n.executablePath&&(r===n.executablePath||i===n.executablePath||r.startsWith(`${n.executablePath} `)))||f.basename(i)===n.executableName})}function yu(e){return{cpu:{usagePercent:w8(e.usagePercent),measuredAt:e.measuredAt,method:e.cpuMethod,matchedProcesses:e.matchedProcesses},memory:{residentMemoryKb:Math.round(e.residentMemoryKb),measuredAt:e.measuredAt,method:e.memoryMethod,matchedProcesses:e.matchedProcesses}}}function yd(e){let t=e?.attributes.fmt?.trim()??"";return t?t.replace(/\s+\(\d+\)$/,"").trim():null}function yc(e,t){let r=sd(e,t);if(r)return r;let n=`${e}
64
- ${t}`.toLowerCase();return n.includes("no device matched")||n.includes("failed to find device")?su:n.includes("timed out")?"Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.":"Ensure the iOS device is unlocked, trusted, visible to xctrace, and the target app stays active while perf samples it."}function yp(e,t){return null===e?t:null===t?e:Math.max(e,t)}async function yf(e,t={}){var r,n,i;let a,o,s,l,u=(s=(o=(a=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===w1&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:w1,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:o.durationMs,lastMeasuredAt:o.measuredAt,method:w1,sampleCount:a.length,samples:a}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:w1},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,fps:{available:!1,reason:"Dropped-frame sampling is currently available only on Android."},memory:{available:!1,reason:w2},cpu:{available:!1,reason:w2}},sampling:{startup:{method:w1,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},...function(e){if("android"===e.device.platform)return{memory:{method:go,description:"Memory snapshot from adb shell dumpsys meminfo <package>. Values are reported in kilobytes.",unit:"kB"},cpu:{method:ga,description:"Aggregated CPU usage for app processes matched from adb shell dumpsys cpuinfo.",unit:"percent"},fps:{method:w9,description:"Rendered-frame health from the current adb shell dumpsys gfxinfo <package> framestats window. Dropped frames use Android gfxinfo janky-frame/frame-deadline data when available; this is not video recording FPS.",unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}};var t=e.device;let r="ios"===t.platform&&"device"===t.kind?{method:gK,description:"Rendered-frame hitch health from xctrace Animation Hitches on connected iOS devices. Dropped frames are counted from native hitch rows for the attached app process, with total frames from the same trace frame-lifetime table.",unit:"percent",primaryField:"droppedFramePercent",window:"short 2s xctrace Animation Hitches record of the active app process",resetsAfterRead:!1}:{method:gK,description:"Unavailable on iOS simulators and macOS because local Apple tooling does not expose reliable app frame hitches for these targets.",unit:"percent",primaryField:"droppedFramePercent"};if("ios"===t.platform&&"device"===t.kind)return{fps:r,memory:{method:g1,description:"Resident memory snapshot from a short xctrace Activity Monitor sample on the connected iOS device.",unit:"kB"},cpu:{method:g0,description:"Recent CPU usage snapshot from a short xctrace Activity Monitor sample on the connected iOS device.",unit:"percent"}};let n="macos"===t.platform?"host ps for the running macOS app executable resolved from the bundle ID.":"xcrun simctl spawn ps for the running iOS simulator app executable resolved from the bundle ID.";return{fps:r,memory:{method:gQ,description:`Resident memory snapshot from ${n}`,unit:"kB"},cpu:{method:gY,description:`Recent CPU usage snapshot from ${n}`,unit:"percent"}}}(r)}});return"android"!==(n=e).device.platform&&"ios"!==n.device.platform&&"macos"!==n.device.platform||(e.appBundleId?"android"===e.device.platform?await ym(u,e,t):await yh(u,e):(i=u,l="android"===e.device.platform?"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.",i.metrics.fps={available:!1,reason:l},i.metrics.memory={available:!1,reason:l},i.metrics.cpu={available:!1,reason:l})),u}async function ym(e,t,r){let n=await yw(t,r);e.metrics.memory=yv(n.memory),e.metrics.cpu=yv(n.cpu),e.metrics.fps=yI(yv(n.fps),t)}async function yh(e,t){let r=await yg(t);e.metrics.memory=yv(r.memory),e.metrics.cpu=yv(r.cpu),e.metrics.fps=yI(yv(r.fps),t)}async function yw(e,t){let r=e.appBundleId,n={adb:t.androidAdb},[i,a,o]=await Promise.allSettled([gl(e.device,r,n),gs(e.device,r,n),gn(e.device,r,n)]);return{memory:i,cpu:a,fps:o}}async function yg(e){let t=e.appBundleId,r=await yy(g3(e.device,t)),n=await yy(g2(e.device,t));if("fulfilled"===n.status){let e=n.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:n.reason},cpu:{status:"rejected",reason:n.reason},fps:r}}async function yy(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function yv(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=k(e.reason);return{available:!1,reason:t.message,error:t}}function yI(e,t){var r,n;let i,a;if(!0!==e.available)return e;let o=(r=t.actions,i=yb((n=e).windowStartedAt),a=yb(n.windowEndedAt)??yb(n.measuredAt),void 0===i||void 0===a?[]:r.filter(e=>e.ts>=i&&e.ts<=a).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-i)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function yb(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}let yA=["path","start","stop","doctor","mark","clear"],yS=`logs requires ${yA.slice(0,-1).join(", ")}, or ${yA.at(-1)}`,yx=["dump","log"],y_=`network requires ${yx.join(" or ")}`,yN=["summary","headers","body","all"],yM=`network include mode must be one of: ${yN.join(", ")}`;async function yk(e){let{req:t}=e;return"perf"===t.command?yD(e):"logs"===t.command?yO(e):"network"===t.command?yL(e):null}async function yD(e){let{sessionName:t,sessionStore:r,androidAdbExecutor:n}=e,i=r.get(t);if(!i)return cX("SESSION_NOT_FOUND","perf requires an active session. Run open first.");try{return{ok:!0,data:await yf(i,{androidAdb:n})}}catch(e){return{ok:!1,error:k(e)}}}async function yO(e){let{req:t,sessionName:r,sessionStore:n}=e,i=n.get(r);if(!i)return cX("SESSION_NOT_FOUND","logs requires an active session");if(!pd("logs",i.device))return cX("UNSUPPORTED_OPERATION","logs is not supported on this device");let a=(t.positionals?.[0]??"path").toLowerCase(),o=!!t.flags?.restart;return yA.includes(a)?o&&"clear"!==a?cX("INVALID_ARGS","logs --restart is only supported with logs clear"):"path"===a?function(e,t,r){let n=r.resolveAppLogPath(t),i=function(e){if(!l.existsSync(e))return{exists:!1,sizeBytes:0};let t=l.statSync(e);return{exists:!0,sizeBytes:t.size,modifiedAt:t.mtime.toISOString()}}(n);return{ok:!0,data:{path:n,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?e.appLog.backend:"macos"===e.device.platform?"macos":"ios"===e.device.platform?"device"===e.device.kind?"ios-device":"ios-simulator":"android",sizeBytes:i.sizeBytes,modifiedAt:i.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}}(i,r,n):"doctor"===a?yP(i,r,n):"mark"===a?function(e,t,r){let n,i=e.positionals?.slice(1).join(" ")??"",a=r.resolveAppLogPath(t);return aL(a),n=`[agent-device][mark][${new Date().toISOString()}] ${i.trim()||"marker"}
65
- `,l.appendFileSync(a,n,"utf8"),{ok:!0,data:{path:a,marked:!0}}}(t,r,n):"clear"===a?yR(i,r,n,o):"start"===a?yC(i,r,n):"stop"===a?yE(i,r,n):cX("INVALID_ARGS",yS):cX("INVALID_ARGS",yS)}async function yP(e,t,r){let n=r.resolveAppLogPath(t),i=await aq(e.device,e.appBundleId);return{ok:!0,data:{path:n,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:i.checks,notes:i.notes}}}async function yR(e,t,r,n){if(e.appLog&&!n)return cX("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");if(n&&!e.appBundleId)return cX("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");let i=r.resolveAppLogPath(t);if(!n)return{ok:!0,data:aB(i)};e.appLog&&await aG(e.appLog);let a=aB(i),o=r.resolveAppLogPidPath(t);try{let n=await aF(e.device,e.appBundleId,i,o);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:n.backend,outPath:i,startedAt:n.startedAt,getState:n.getState,stop:n.stop,wait:n.wait}}),{ok:!0,data:{...a,restarted:!0}}}catch(n){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:k(n)}}}async function yC(e,t,r){if(e.appLog)return cX("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return cX("INVALID_ARGS","logs start requires an app session; run open <app> first");let n=r.resolveAppLogPath(t),i=r.resolveAppLogPidPath(t);try{let a=await aF(e.device,e.appBundleId,n,i);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:a.backend,outPath:n,startedAt:a.startedAt,getState:a.getState,stop:a.stop,wait:a.wait}}),{ok:!0,data:{path:n,started:!0}}}catch(e){return{ok:!1,error:k(e)}}}async function yE(e,t,r){if(!e.appLog)return cX("INVALID_ARGS","no app log stream active");let n=e.appLog.outPath;return await aG(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:n,stopped:!0}}}async function yL(e){let{req:t,sessionName:r,sessionStore:n}=e,i=n.get(r);if(!i)return cX("SESSION_NOT_FOUND","network requires an active session");if(!pd("network",i.device))return cX("UNSUPPORTED_OPERATION","network is not supported on this device");let a=(t.positionals?.[0]??"dump").toLowerCase();if(!yx.includes(a))return cX("INVALID_ARGS",y_);let o=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(o)||o<1||o>200)return cX("INVALID_ARGS","network dump limit must be an integer in range 1..200");let s=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return cX("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let n=(r??t??"summary").toLowerCase();return yN.includes(n)?{ok:!0,include:n}:cX("INVALID_ARGS",yM)}(t);if(!s.ok)return s;let{include:l}=s,u=await aT({device:i.device,appBundleId:i.appBundleId,appLogState:i.appLog?.getState(),appLogStartedAt:i.appLog?.startedAt,appLogPath:n.resolveAppLogPath(r),maxEntries:o,include:l,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...u.dump,active:!!i.appLog,state:i.appLog?.getState()??"inactive",backend:u.backend,notes:u.notes}}}let yT=/^[A-Z_][A-Z0-9_]*$/,y$=/(\\\$\{)|\$\{([A-Za-z_][A-Za-z0-9_.]*)(?::-((?:[^}\\]|\\.)*))?\}/g,yF="AD_VAR_";function yU(e){return e.startsWith("AD_")}function yV(e){return new D("INVALID_ARGS",`The AD_* namespace is reserved for built-in variables. Rename ${e} to avoid the AD_ prefix.`)}function yG(e){let t={};for(let[r,n]of Object.entries(e)){if("string"!=typeof n||!r.startsWith(yF))continue;let e=r.slice(yF.length);0!==e.length&&yT.test(e)&&(yU(e)||(t[e]=n))}return t}function yq(e){let t={};for(let r of e){let e=r.indexOf("=");if(e<=0)throw new D("INVALID_ARGS",`Invalid -e entry "${r}": expected KEY=VALUE.`);let n=r.slice(0,e);if(!yT.test(n))throw new D("INVALID_ARGS",`Invalid -e key "${n}": keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(yU(n))throw yV(n);t[n]=r.slice(e+1)}return t}function yB(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function yj(e){if(e&&"object"==typeof e&&!Array.isArray(e)){let t={};for(let[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}return process.env}function yH(e,t,r){return e.replace(y$,(e,n,i,a)=>{if(n)return"${";if(!i)return e;if(Object.prototype.hasOwnProperty.call(t.values,i))return String(t.values[i]);if(void 0!==a)return a.replace(/\\(.)/g,"$1");throw new D("INVALID_ARGS",`Unresolved variable \${${i}} at ${r.file}:${r.line}.`)})}function yW(e,t,r){return e?function e(t,r,n){return"string"==typeof t?yH(t,r,n):Array.isArray(t)?t.map(t=>e(t,r,n)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,i])=>[t,e(i,r,n)])):t}(e,t,r):e}let yz=new Set(["ios","android","macos","linux"]),yK=new Set(["mobile","tv","desktop"]);function yJ(e){let t=e.split(/\r?\n/),r={};for(let[e,n]of t.entries()){let t=n.trim();if(0===t.length||t.startsWith("#"))continue;if(yX(t)){!function(e,t,r){let{key:n,value:i}=function(e,t){let r=e.slice(3).replace(/^[\s]+/,""),n=r.indexOf("=");if(n<=0)throw new D("INVALID_ARGS",`Invalid env directive on line ${t}: expected "env KEY=VALUE".`);let i=r.slice(0,n);if(!yT.test(i))throw new D("INVALID_ARGS",`Invalid env key "${i}" on line ${t}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(i.startsWith("AD_"))throw new D("INVALID_ARGS",`Invalid env key "${i}" on line ${t}: the AD_* namespace is reserved for built-in variables. Rename ${i} to avoid the AD_ prefix.`);return{key:i,value:function(e,t){if(0===e.length)return"";if(e.startsWith('"'))try{let t=JSON.parse(e);if("string"!=typeof t)throw Error("not a string literal");return t}catch{throw new D("INVALID_ARGS",`Invalid quoted env value on line ${t}.`)}return e}(r.slice(n+1),t)}}(t,r),a=e.env??{};if(Object.prototype.hasOwnProperty.call(a,n))throw new D("INVALID_ARGS",`Duplicate env directive "${n}" on line ${r}.`);a[n]=i,e.env=a}(r,t,e+1);continue}if(!t.startsWith("context "))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&yz.has(e)&&yZ(r,"platform",e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&yK.has(e)&&yZ(r,"target",e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&yZ(r,"timeoutMs",Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&yZ(r,"retries",Math.floor(e))}}return r}function yX(e){return"env"===e||e.startsWith("env ")||e.startsWith("env ")}function yZ(e,t,r){let n=e[t];if(void 0!==n)throw new D("INVALID_ARGS",n===r?`Duplicate replay test metadata "${t}" in context header.`:`Conflicting replay test metadata "${t}" in context header: ${String(n)} vs ${String(r)}.`);e[t]=r}function yY(e){return!!e&&!Number.isNaN(Number(e))}let yQ=/[*?[\]{}]/;function y0(e){return"maestro"===e}let y1=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function y2(e){var t,r,n,i;let a,o,s="ok"in(t=e)?t.ok?null:t.error:"failed"===t.status?t.error:null;return!!s&&(r=s.details,"timeout_cleanup_pending"===(a="string"==typeof r?.reason?r.reason:"")||!!a&&es(a)||(n=s.code,i=s.message,o=`${n}
66
- ${i}`.toLowerCase(),y1.some(e=>o.includes(e))))}async function y3(e){let t,r,{filePath:n,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:l,artifactsDir:u,runReplay:d,cleanupSession:c}=e;rv(a);let p=new Set,f=!1,m=d({filePath:n,sessionName:i,platform:s,target:l,requestId:a,artifactsDir:u,artifactPaths:p}).catch(e=>({ok:!1,error:k(e)})).finally(()=>{rb(a)});try{return r="number"==typeof o?await Promise.race([m,new Promise(e=>{t=setTimeout(()=>{f=!0,rI(a),e(function(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}}}}(o,[...p]))},o)})]):await m}finally{var h;t&&clearTimeout(t),f&&(await y5(m)||((h=r)&&!h.ok&&(h.error.details={...h.error.details??{},reason:"timeout_cleanup_pending",timeoutCleanupPending:!0}),eN({level:"warn",phase:"test_timeout_cleanup_race",data:{session:i,requestId:a,graceMs:2e3}}),y4({replayPromise:m,cleanupSession:c,sessionName:i,requestId:a})));try{await c(i)}catch(e){eN({level:"warn",phase:"test_cleanup_failed",data:{session:i,error:k(e).message}})}}}async function y5(e){return await Promise.race([e.then(()=>!0),S(2e3).then(()=>!1)])}async function y4(e){let{replayPromise:t,cleanupSession:r,sessionName:n,requestId:i}=e;try{await t}finally{try{await r(n)}catch(e){eN({level:"warn",phase:"test_late_cleanup_failed",data:{session:n,requestId:i,error:k(e).message}})}}}async function y8(e){let{req:t,sessionName:r,runReplay:n,cleanupSession:i}=e;if((t.positionals?.length??0)===0)return cX("INVALID_ARGS","test requires at least one path or glob");try{var a,o,s,u,d,c;let e,p,m,h,w,g=function(e){var t,r,n;let{inputs:i,cwd:a,platformFilter:o,replayBackend:s}=e,u=(t=s,new Set(y0(t)?[".ad",".yaml",".yml"]:[".ad"])),d=a??process.cwd(),c=[...new Set(i.flatMap(e=>(function(e,t,r){var n,i;let a=i4.expandHome(e,t);if(l.existsSync(a)){let t=l.statSync(a);if(t.isDirectory())return[...r].map(e=>`**/*${e}`).flatMap(e=>l.globSync(e,{cwd:a}).map(e=>f.join(a,e)));if(t.isFile()){if(!r.has(f.extname(a)))throw new D("INVALID_ARGS",`test does not support this file type: ${e}`);return[a]}return[]}if(n=e,!yQ.test(n)&&(i=a,!yQ.test(i)))throw new D("INVALID_ARGS",`test input not found: ${e}`);let o=f.isAbsolute(a)?a:e;return l.globSync(o,{cwd:f.isAbsolute(a)?void 0:t}).map(e=>f.isAbsolute(e)?e:f.resolve(t,e)).filter(e=>r.has(f.extname(e))&&function(e){try{return l.statSync(e).isFile()}catch{return!1}}(e))})(e,d,u)))].map(e=>f.normalize(e)).sort((e,t)=>e.localeCompare(t)),p=[];for(let e of c){let t=yJ(l.readFileSync(e,"utf8"));if(!o){p.push({kind:"run",path:e,metadata:t});continue}if(!t.platform){y0(s)?p.push({kind:"run",path:e,metadata:t}):p.push({kind:"skip",path:e,reason:"skipped-by-filter",message:`missing platform metadata for --platform ${o}`});continue}r=o,n=t.platform,("apple"===r?"apple"===n||"ios"===n||"macos"===n:n===r)&&p.push({kind:"run",path:e,metadata:t})}if(0===p.filter(e=>"run"===e.kind).length){let e=o?` for --platform ${o}`:"";throw new D("INVALID_ARGS",`No replay tests matched${e}.`)}return p}({inputs:t.positionals,cwd:t.meta?.cwd,platformFilter:t.flags?.platform,replayBackend:t.flags?.replayBackend}),y=(a=t.meta?.requestId,(a?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite"),v=function(e){let{artifactsDir:t,cwd:r,suiteInvocationId:n}=e,i=i4.expandHome(t??".agent-device/test-artifacts",r);return f.join(i,n)}({artifactsDir:"string"==typeof t.flags?.artifactsDir?t.flags.artifactsDir:void 0,cwd:t.meta?.cwd,suiteInvocationId:y}),I=[],b=Date.now(),A=0;for(let[e,a]of g.entries()){if("skip"===a.kind){a5({type:"replay-test",file:a.path,status:"skip",index:e+1,total:g.length,message:a.message}),I.push({file:a.path,status:"skipped",durationMs:0,reason:a.reason,message:a.message});continue}A+=1;let l=await y6({entry:a,sessionName:r,suiteInvocationId:y,caseIndex:A-1,cwd:t.meta?.cwd,requestId:t.meta?.requestId,retries:function(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}(t.flags?.retries,a.metadata.retries),timeoutMs:(o=t.flags?.timeoutMs,s=a.metadata.timeoutMs,"number"==typeof o?o:s),suiteArtifactsDir:v,suiteIndex:e+1,suiteTotal:g.length,runReplay:n,cleanupSession:i});if(I.push(l),t.flags?.failFast===!0||y2(l))break}let S=(u=g.length,d=I,c=Date.now()-b,e=d.filter(e=>"passed"===e.status).length,m=(p=d.filter(e=>"failed"===e.status)).length,h=d.filter(e=>"skipped"===e.status).length,w=e+m,{total:u,executed:w,passed:e,failed:m,skipped:h,notRun:Math.max(0,u-w-h),durationMs:c,failures:p,tests:d});return{ok:!0,data:S}}catch(t){let e=M(t);return cX(e.code,e.message)}}async function y6(e){var t,r;let n,i,{entry:a,sessionName:o,suiteInvocationId:s,caseIndex:u,cwd:d,requestId:c,retries:p,timeoutMs:m,suiteArtifactsDir:h,suiteIndex:w,suiteTotal:g,runReplay:y,cleanupSession:v}=e,I=Date.now(),b=f.join(h,(t=a.path,(0===(i=d?f.relative(d,t):f.basename(t)).length||i.startsWith("..")?f.basename(t):i).toLowerCase().replace(/[\\/]+/g,"__").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"test")),A="",S=0;for(let e=0;e<=p;e+=1){S=e+1;let t=function(e,t,r,n,i=0){let a=f.basename(r,f.extname(r)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${e}:test:${t}:${n+1}${a?`-${a}`:""}:attempt-${i+1}`}(o,s,a.path,u,e),i=f.join(b,`attempt-${S}`);r=a.path,l.mkdirSync(i,{recursive:!0}),function(e,t){let r=f.join(t,"replay.ad");if(l.copyFileSync(e,r),!function(e){let t=f.extname(e).toLowerCase();return".yml"===t||".yaml"===t}(e))return;let n=f.join(t,f.basename(e));f.resolve(n)!==f.resolve(r)&&l.copyFileSync(e,n)}(r,i);let d=function(e){let{requestId:t,suiteInvocationId:r,filePath:n,caseIndex:i,attemptIndex:a}=e;return ry(`${t??r}:test:${i+1}:${f.basename(n)}:attempt:${a+1}`,r)}({requestId:c,suiteInvocationId:s,filePath:a.path,caseIndex:u,attemptIndex:e}),h=await y3({filePath:a.path,sessionName:t,requestId:d,timeoutMs:m,platform:a.metadata.platform,target:a.metadata.target,artifactsDir:i,runReplay:y,cleanupSession:v});if(!function(e){let{response:t,filePath:r,sessionName:n,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=[...function(e){let t=e.ok?e.data?.artifactPaths:e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e))]:[]}(t)];t.ok||"string"!=typeof t.error.logPath||s.push(t.error.logPath);let u=function(e,t){let r=[],n=new Map;for(let i of e){if(!function(e){try{return l.statSync(e).isFile()}catch{return!1}}(i))continue;let e=function(e,t){let r=f.extname(e),n=r?e.slice(0,-r.length):e,i=t.get(e)??0;return(t.set(e,i+1),0===i)?e:`${n}-${i+1}${r}`}(f.basename(i),n),a=f.join(t,e);f.resolve(i)!==f.resolve(a)&&l.copyFileSync(i,a),r.push(a)}return r}(s,o),d=[`file: ${r}`,`session: ${n}`,`attempt: ${i}/${a}`,`status: ${t.ok?"passed":"failed"}`];if(t.ok){let e="number"==typeof t.data?.replayed?t.data.replayed:0,r="number"==typeof t.data?.healed?t.data.healed:0;d.push(`replayed: ${e}`,`healed: ${r}`)}else d.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&d.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&d.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&d.push(`logPath: ${t.error.logPath}`),t.error.details?.reason==="timeout"&&d.push("timeoutMode: cooperative");u.length>0&&d.push(`copiedArtifacts: ${u.map(e=>f.basename(e)).join(", ")}`);let c=f.join(o,"result.txt"),p=`${d.join("\n")}
67
- `;l.writeFileSync(c,p),t.ok||l.writeFileSync(f.join(o,"failure.txt"),p)}({response:h,filePath:a.path,sessionName:t,attempts:S,maxAttempts:p+1,attemptArtifactsDir:i}),n=h,A=t,h.ok||y2(h)||e>=p)break;a5({type:"replay-test",file:a.path,status:"fail",index:w,total:g,attempt:S,maxAttempts:p+1,retrying:!0,message:h.error.message})}let x=Date.now()-I;if(n?.ok)return a5({type:"replay-test",file:a.path,status:"pass",index:w,total:g,attempt:S,maxAttempts:p+1,durationMs:x,artifactsDir:b}),{file:a.path,session:A,status:"passed",durationMs:x,attempts:S,artifactsDir:b,replayed:"number"==typeof n.data?.replayed?n.data.replayed:0,healed:"number"==typeof n.data?.healed?n.data.healed:0};let _=n?.ok?{code:"COMMAND_FAILED",message:"Unknown replay test failure"}:n?.error??{code:"COMMAND_FAILED",message:"Unknown replay test failure"};return a5({type:"replay-test",file:a.path,status:"fail",index:w,total:g,attempt:S,maxAttempts:p+1,durationMs:x,artifactsDir:b,message:_.message}),{file:a.path,session:A,status:"failed",durationMs:x,attempts:S,artifactsDir:b,error:_}}function y9(e,t=[],r){return{ts:Date.now(),command:e,positionals:t,flags:r??{}}}function y7(e,t,r){let n=new Set(r),i=Object.keys(e).filter(e=>!n.has(e));if(i.length>0)throw vl(`Maestro ${t} field "${i[0]}" is not supported yet.`)}function ve(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function vt(e){return e.map((e,t)=>{if("string"==typeof e||ve(e))return e;throw new D("INVALID_ARGS",`Unsupported Maestro command at index ${t+1}: expected a scalar or one-key map.`)})}function vr(e,t){if(null==e)return{};if(!ve(e))throw new D("INVALID_ARGS",`${t} expects a map.`);let r={};for(let[t,n]of Object.entries(e))("string"==typeof n||"number"==typeof n||"boolean"==typeof n)&&(r[t]=String(n));return r}function vn(e,t){return ve(e)&&"number"==typeof e.timeout&&Number.isFinite(e.timeout)?Math.max(0,Math.floor(e.timeout)):t}function vi(e,t){if(e.appId)return e.appId;throw new D("INVALID_ARGS",`${t} requires appId in the Maestro flow config.`)}function va(e,t){if("string"==typeof t)return t;throw new D("INVALID_ARGS",`${e} expects a string value.`)}function vo(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,r)=>Object.prototype.hasOwnProperty.call(t.env,r)?String(t.env[r]):e)}function vs(e){throw vl(`Maestro command "${e}" is not supported yet.`)}function vl(e){throw new D("INVALID_ARGS",`${e} See supported/unsupported Maestro compatibility at ${t$}. If this syntax matters for your flows, comment there or open a focused issue at ${tW}.`)}function vu(e,t,r){var n,i;if(null==e)return y9("open",[vo(vi(t,"launchApp"),r)]);if("string"==typeof e)return y9("open",[vo(e,r)]);if(!ve(e))throw new D("INVALID_ARGS","launchApp expects a string or map.");y7(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),vf(e,"permissions"),vf(e,"clearKeychain");let a=vo("string"==typeof e.appId?e.appId:vi(t,"launchApp"),r),o=(n=e,i=r,[...vc(n.arguments,"launchApp.arguments",i),...vc(n.launchArguments,"launchApp.launchArguments",i)]),s=!0===e.clearState;return y9("open",[a],{...!s&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...s?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function vd(e,t,r){if(null==e)return y9("close",[vo(vi(t,"stopApp"),r)]);if("string"==typeof e)return y9("close",[vo(e,r)]);throw new D("INVALID_ARGS","stopApp expects a string appId or no value.")}function vc(e,t,r){if(null==e)return[];if("string"==typeof e)return[vo(e,r)];if(Array.isArray(e))return e.map((e,n)=>vp(e,`${t}[${n}]`,r));if(ve(e))return Object.entries(e).flatMap(([e,n])=>[vo(e,r),vp(n,`${t}.${e}`,r)]);throw new D("INVALID_ARGS",`${t} expects a string, list, or map.`)}function vp(e,t,r){if("string"==typeof e)return vo(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new D("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function vf(e,t){if(void 0!==e[t])throw vl(`Maestro launchApp field "${t}" is not supported yet.`)}function vm(e){let t=e.match(/^(\d+),(\d+)$/);if(!t)throw vl('Only absolute Maestro point selectors like "100,200" are supported.');return{x:Number(t[1]),y:Number(t[2])}}function vh(e){let t=e.match(/^\s*(\d+)\s*,\s*(\d+)\s*$/);if(t)return{kind:"absolute",x:Number(t[1]),y:Number(t[2])};let r=e.match(/^\s*(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)%\s*$/);if(r)return{kind:"percent",x:Number(r[1]),y:Number(r[2])};throw vl('Only Maestro swipe coordinates like "100,200" or "50%,75%" are supported.')}let vw="__maestroRunFlowWhen",vg="__maestroRetry",vy="__maestroRunScript",vv="__maestroAssertVisible",vI="__maestroAssertNotVisible",vb="__maestroPressEnter",vA="__maestroWaitForAnimationToEnd",vS="__maestroScrollUntilVisible",vx="__maestroSwipeScreen",v_="__maestroSwipeOn",vN="__maestroTapOn",vM="__maestroTapPointPercent";function vk(e){if(null==e)return y9("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return y9("type",["\b".repeat(e)]);if(!ve(e))throw new D("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(y7(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return y9("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new D("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return y9("type",["\b".repeat(e.charactersToErase)])}function vD(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function vO(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw vl(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function vP(e){return vO(e,"swipe direction")}function vR(e,t,r=[],n){if("string"==typeof e)return vC(vo(e,n));if(!ve(e))throw new D("INVALID_ARGS",`${t} expects a string or selector map.`);y7(e,t,["id","text","enabled","selected",...r]);let i=[],a=[];if("boolean"==typeof e.enabled&&a.push(vL("enabled",String(e.enabled))),"boolean"==typeof e.selected&&a.push(vL("selected",String(e.selected))),"string"==typeof e.id&&i.push(vL("id",vo(e.id,n)),...a),"string"==typeof e.text&&0===i.length)return vC(vo(e.text,n),a);if("string"==typeof e.label&&0===i.length&&i.push(vL("label",vo(e.label,n)),...a),0===i.length&&a.length>0&&i.push(...a),0===i.length)throw new D("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return i.join(" ")}function vC(e,t=[]){return[[vL("label",e),...t].join(" "),[vL("text",e),...t].join(" "),[vL("id",e),...t].join(" ")].join(" || ")}function vE(e){let t=vD(e.duration);return t?[t]:[]}function vL(e,t){return`${e}=${JSON.stringify(t)}`}function vT(e){var t,r;if(!ve(e))return;let n={},i="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,a="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return i&&i>1&&(n.count=i),void 0!==a&&(n.intervalMs=a),!0===e.optional&&(n.maestro={optional:!0}),Object.keys(n).length>0?n:void 0}function v$(e){let t=vT(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function vF(e){let t={doubleTap:!0};return ve(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class vU{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new D("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 D("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new D("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new D("INVALID_ARGS","runFlow.when.true supports maestro.platform comparisons.");this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type==="operator"&&("=="===e.value||"!="===e.value))return this.index+=1,e.value;throw new D("INVALID_ARGS","runFlow.when.true comparison requires == or !=.")}expectString(){let e=this.peek();if(e?.type==="string")return this.index+=1,e.value;throw new D("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function vV(e){return{command:e.command,positionals:e.positionals,flags:e.flags,...void 0!==e.runtime?{runtime:e.runtime}:{}}}function vG(e,t,r){let n="string"==typeof e?vo(e,t):e,i="number"==typeof n?n:"string"==typeof n&&/^\d+$/.test(n)?Number(n):void 0;if(void 0===i||!Number.isInteger(i)||i<0)throw new D("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return i}let vq=`
68
- const fs = require('node:fs');
69
- const input = JSON.parse(fs.readFileSync(0, 'utf8'));
70
- if (typeof fetch !== 'function') {
71
- console.error('global fetch is required for Maestro runScript http helpers');
72
- process.exit(1);
73
- }
74
- fetch(input.url, {
75
- method: input.method,
76
- headers: input.headers,
77
- body: input.body,
78
- }).then(async response => {
79
- process.stdout.write(JSON.stringify({
80
- status: response.status,
81
- body: await response.text(),
82
- headers: Object.fromEntries(response.headers.entries()),
83
- }));
84
- }).catch(error => {
85
- console.error(error && error.stack ? error.stack : String(error));
86
- process.exit(1);
87
- });
88
- `;function vB(e){if("string"!=typeof e)throw new D("COMMAND_FAILED",`Maestro runScript json() expected a string body, received ${typeof e}.`);if(0===e.trim().length)throw new D("COMMAND_FAILED","Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.");try{return JSON.parse(e,vj)}catch(t){throw new D("COMMAND_FAILED",`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,1e3)},t instanceof Error?t:void 0)}}function vj(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let vH={launchApp:({value:e,config:t,context:r})=>[vu(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return y9(vN,[vC(vo(e,t))],v$(e));if(ve(e)&&"string"==typeof e.point){y7(e,"tapOn",["point","repeat","delay","optional","label"]);let t=vh(e.point);return"percent"===t.kind?y9(vM,[String(t.x),String(t.y)],vT(e)):y9("click",[String(t.x),String(t.y)],vT(e))}ve(e)&&y7(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=v$(e);return y9(vN,[vR(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!ve(e))return[];let r={};if(void 0!==e.index){if("number"!=typeof e.index||!Number.isInteger(e.index)||e.index<0)throw new D("INVALID_ARGS","tapOn.index must be a non-negative integer.");r.index=e.index}return void 0!==e.childOf&&(r.childOf=vR(e.childOf,"tapOn.childOf",[],t)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}(e,t)],r)}(e,t)],doubleTapOn:({value:e,context:t})=>[function(e,t){if(ve(e)&&"string"==typeof e.point){y7(e,"doubleTapOn",["point","delay"]);let t=vm(e.point);return y9("click",[String(t.x),String(t.y)],vF(e))}return ve(e)&&y7(e,"doubleTapOn",["id","text","enabled","selected","delay"]),y9("click",[vR(e,"doubleTapOn",["delay"],t)],vF(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(ve(e)&&"string"==typeof e.point){y7(e,"longPressOn",["point"]);let t=vm(e.point);return y9("longpress",[String(t.x),String(t.y),"3000"])}return ve(e)&&y7(e,"longPressOn",["id","text","enabled","selected"]),y9("click",[vR(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[y9("type",[vo(function(e){if("string"==typeof e)return e;if(!ve(e))throw new D("INVALID_ARGS","inputText expects a string or map.");if(y7(e,"inputText",["text","label"]),"string"!=typeof e.text)throw new D("INVALID_ARGS","inputText map requires a string text field.");return e.text}(e),t)])],eraseText:({value:e})=>[vk(e)],pasteText:({value:e,context:t,name:r})=>[y9("type",[vo(va(r,e),t)])],openLink:({value:e,config:t,context:r,name:n})=>{var i,a,o,s,l,u;let d;return[(i=e,a=t,o=r,s=n,d=vo((l=i,u=s,"string"==typeof l?l:ve(l)?(y7(l,u,["link"]),va(`${u}.link`,l.link)):va(u,l)),o),("ios"===o.platform||"android"===o.platform)&&a.appId?y9("open",[vo(vi(a,s),o),d]):y9("open",[d]))]},assertVisible:({value:e,context:t,name:r})=>[y9(vv,[vR(e,r,[],t),"5000"])],assertNotVisible:({value:e,context:t,name:r})=>[y9(vI,[vR(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!ve(e))throw new D("INVALID_ARGS","extendedWaitUntil expects a map.");y7(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw vl("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let n=vR(r,"extendedWaitUntil",[],t),i=String(vn(e,3e4));return void 0!==e.notVisible?[y9("wait",[i]),y9("is",["hidden",n])]:[y9(vv,[n,i])]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[y9("screenshot",[vo(va(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw vl("Maestro scroll options are not supported yet.");return y9("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[y9(vS,[vC(vo(e,t)),"5000","down"])];if(!ve(e))throw new D("INVALID_ARGS","scrollUntilVisible expects a string or map.");y7(e,"scrollUntilVisible",["element","direction","timeout"]);let r=vR(e.element,"scrollUntilVisible.element",[],t),n="string"==typeof e.direction?vO(e.direction,"scrollUntilVisible.direction"):"down";return[y9(vS,[r,String(vn(e,5e3)),n])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,n,i;let a;if(!ve(e))throw new D("INVALID_ARGS","swipe expects a map.");y7(e,"swipe",["start","end","direction","duration","from","label"]);let o=e.from??("string"==typeof e.label?e.label:void 0);return void 0!==o?(r=e,n=o,i=t,a=vP("string"==typeof r.direction?r.direction:"up"),y9(v_,[vR(n,"swipe.from",[],i),a,...vE(r)])):"string"==typeof e.direction?y9(vx,["direction",vP(e.direction),...vE(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:vh(e.start),end:vh(e.end)};throw vl("Only Maestro swipe start/end coordinates are supported.")}(e);var n=t,i=r,a=vD(e.duration);if("absolute"===n.kind&&"absolute"===i.kind)return y9("swipe",[String(n.x),String(n.y),String(i.x),String(i.y),...a?[a]:[]]);if("percent"===n.kind&&"percent"===i.kind)return y9(vx,["percent",String(n.x),String(n.y),String(i.x),String(i.y),...a?[a]:[]]);throw vl("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[y9("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=va("pressKey",e).toLowerCase();if("back"===t)return y9("back");if("enter"===t||"return"===t)return y9(vb);if("home"===t)return y9("home");throw vl(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[y9("back")],waitForAnimationToEnd:({value:e})=>[y9(vA,[String(vn(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[vd(e,t,r)],runScript:({value:e,context:t})=>{let r;return[y9(vy,[function(e,t){if(f.isAbsolute(e))return e;if(!t.baseDir)throw new D("INVALID_ARGS","runScript file paths require replay input to have a source path.");return f.resolve(t.baseDir,e)}((r=function(e,t){if("string"==typeof e)return{file:vo(e,t),env:{}};if(!ve(e))throw new D("INVALID_ARGS","runScript expects a file path string or map.");return y7(e,"runScript",["file","env"]),{file:vo(va("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(vr(e.env,"runScript.env")).map(([e,r])=>[e,vo(r,t)]))}}(e,t)).file,t)],{...Object.keys(r.env).length>0?{maestro:{runScriptEnv:r.env}}:{}})]},runFlow:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,i){if("string"==typeof e)return n.parseRunFlowFile(vo(e,r),r).actions;if(!ve(e))throw new D("INVALID_ARGS","runFlow expects a file path string or map.");y7(e,"runFlow",["file","commands","env","when","label"]);let a=function(e,t){var r,n;if(null==e)return{shouldRun:!0};if(!ve(e))throw new D("INVALID_ARGS","runFlow.when expects a map.");return(y7(e,"runFlow.when",["platform","visible","notVisible","true"]),!function(e,t){if(void 0!==e.true&&!function(e,t){let r;if("boolean"==typeof e)return e;if("string"!=typeof e)throw new D("INVALID_ARGS","runFlow.when.true expects a boolean or expression string.");return new vU(function(e){let t=[],r=0;for(;r<e.length;){var n,i;let a=e.slice(r),o=(n=a,/^\s+/.exec(n)?.[0].length??0);if(o>0){r+=o;continue}let s=function(e){let t="maestro.platform";return e.startsWith(t)?{token:{type:"platform"},length:t.length}:null}(i=a)??function(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:"operator",value:t},length:t.length}:null}(i)??function(e){let t=e[0];return"("===t||")"===t?{token:{type:"paren",value:t},length:1}:null}(i)??function(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:"string",value:t[2]??""},length:t[0].length}:null}(i)??function(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:"boolean",value:"true"===t},length:t.length}:null}(i);if(s){t.push(s.token),r+=s.length;continue}throw new D("INVALID_ARGS",`Unsupported runFlow.when.true expression near "${a.slice(0,24)}".`)}return t}((r=vo(e,t).trim()).startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():r),{platform:t.platform}).parse()}(e.true,t))return!1;if(void 0===e.platform)return!0;let r=function(e,t){if("string"!=typeof e)throw new D("INVALID_ARGS",`${t} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if("android"===r||"ios"===r||"web"===r)return r;throw new D("INVALID_ARGS",`${t} expects Android, iOS, or Web.`)}(e.platform,"runFlow.when.platform");if(!t.platform)throw new D("INVALID_ARGS","Maestro runFlow.when.platform requires replay to be run with --platform ios|android.");return r===t.platform}(e,t))?{shouldRun:!1}:{shouldRun:!0,...(r=e,n=t,{...void 0!==r.visible?{visibleSelector:vR(r.visible,"runFlow.when.visible",[],n)}:{},...void 0!==r.notVisible?{notVisibleSelector:vR(r.notVisible,"runFlow.when.notVisible",[],n)}:{}})}}(e.when,r);if(!a.shouldRun)return[];let o={...r,env:{...r.env,...vr(e.env,"runFlow.env"),...r.envOverrides}};var s=function(e,t,r,n,i){if("string"==typeof e.file)return n.parseRunFlowFile(vo(e.file,r),r).actions;if(Array.isArray(e.commands))return i(vt(e.commands),t,r,n);throw new D("INVALID_ARGS","runFlow map requires either file or commands.")}(e,t,o,n,i),l=a;if(!l.visibleSelector&&!l.notVisibleSelector)return s;if(l.visibleSelector&&l.notVisibleSelector)throw vl("Maestro runFlow.when cannot combine visible and notVisible yet.");return[y9(vw,l.visibleSelector?["visible",l.visibleSelector]:["notVisible",l.notVisibleSelector??""],{batchSteps:s.map(vV)})]})(e,t,r,n,vK),repeat:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,i){var a;if(!ve(e))throw new D("INVALID_ARGS","repeat expects a map.");if(y7(e,"repeat",["times","commands","while"]),void 0!==e.while)throw vl("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(a=e.times,vG(a,r,"repeat.times"));if(!Array.isArray(e.commands))throw new D("INVALID_ARGS","repeat requires a commands list.");if(o>1e3)throw new D("INVALID_ARGS","repeat.times must be <= 1000 for deterministic replay expansion.");let s=vt(e.commands);return Array.from({length:o}).flatMap(()=>i(s,t,r,n))})(e,t,r,n,vK),retry:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,i){var a,o;if(!ve(e))throw new D("INVALID_ARGS","retry expects a map.");if(y7(e,"retry",["maxRetries","commands"]),!Array.isArray(e.commands))throw new D("INVALID_ARGS","retry requires a commands list.");let s=(a=e.maxRetries,o=r,void 0===a?1:vG(a,o,"retry.maxRetries")),l=i(vt(e.commands),t,r,n);return[y9(vg,[String(s)],{batchSteps:l.map(vV)})]})(e,t,r,n,vK)},vW={launchApp:(e,t)=>[vu(void 0,e,t)],scroll:()=>[y9("scroll",["down"])],hideKeyboard:()=>[y9("keyboard",["dismiss"])],eraseText:()=>[vk(void 0)],back:()=>[y9("back")],waitForAnimationToEnd:()=>[y9(vA,["15000"])],stopApp:(e,t)=>[vd(void 0,e,t)]};function vz(e,t,r,n,i){try{return function(e,t,r,n){if("string"==typeof e){var i,a,o;let n;return i=e,a=t,o=r,(n=vW[i])?n(a,o):vs(i)}let s=Object.entries(e);if(1!==s.length)throw new D("INVALID_ARGS","Maestro command maps must contain exactly one command.");let[l,u]=s[0],d=vH[l];return d?d({value:u,config:t,context:r,deps:n,name:l}):vs(l)}(e,t,n,i)}catch(e){if(e instanceof D&&!/\bline \d+\b/.test(e.message))throw new D(e.code,`${e.message} (line ${r})`,e.details);throw e}}function vK(e,t,r,n){return e.flatMap((e,i)=>vz(e,t,i+1,r,n))}function vJ(e,t){let{config:r,commands:n}=function(e){if(0===e.length)throw new D("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:vt(e[0])};let t=function(e){if(!ve(e))throw new D("INVALID_ARGS","Maestro flow config must be a YAML map.");return{..."string"==typeof e.appId&&e.appId.length>0?{appId:e.appId}:{},...ve(e.env)?{env:vr(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:vt(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:vt(e.onFlowComplete)}:{}}}(e[0]),r=e[1];if(!Array.isArray(r))throw new D("INVALID_ARGS","Maestro flow must contain a command list after the YAML document separator.");return{config:t,commands:vt(r)}}(function(e){let t=x(e);for(let e of t)if(e.errors.length>0){let t=e.errors[0]?.message??"Invalid Maestro YAML flow.";throw new D("INVALID_ARGS",`Invalid Maestro YAML flow: ${t}`)}return t.map(e=>e.toJSON()).filter(e=>null!==e)}(e)),i={...t,env:{...t.env,...r.env??{},...t.envOverrides}},{actions:a,actionLines:o}=function(e){let{config:t,commands:r,commandLines:n,context:i}=e,a=[...t.onFlowStart??[],...r,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...n,...Array.from({length:t.onFlowComplete?.length??0},()=>n.at(-1)??1)],s=[],l=[];for(let[e,r]of a.entries()){let n=o[e]??e+1,a=vz(r,t,n,i,{parseRunFlowFile:vZ});s.push(...a),a.forEach(()=>l.push(n))}return function(e,t){let r=[],n=[];for(let i=0;i<e.length;i+=1){let a=e[i],o=function(e,t,r){var n;let i=e[r],a=e[r+1],o=function(e){if(e?.command!=="type"||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(a),s=function(e){if(e?.command!==vN)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(i);if(!a||null===o||null===s)return null;let l=t[r]??1;if(n=s,!/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(n.replace(/([a-z])([A-Z])/g,"$1 $2")))return{actions:[vX(i)],actionLines:[l],consumed:1};let u=e[r+2];return u?.command!==vb?{actions:[vX(i)],actionLines:[l],consumed:1}:{actions:[{...i,command:"wait",positionals:[s,"30000"]},{...a,command:"fill",positionals:[s,o],flags:i.flags},u],actionLines:[l,l,t[r+2]??l],consumed:3}}(e,t,i);if(o){r.push(...o.actions),n.push(...o.actionLines),i+=o.consumed-1;continue}r.push(a),n.push(t[i]??1)}return{actions:r,actionLines:n}}(s,l)}({config:r,commands:n,commandLines:function(e){let t=e.split(/\r?\n/),r=t.findIndex(e=>"---"===e.trim()),n=-1===r?0:r+1,i=[];for(let e=n;e<t.length;e+=1)/^-\s+/.test(t[e]??"")&&i.push(e+1);return i}(e),context:i});return{actions:a,actionLines:o,metadata:{env:r.env}}}function vX(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}function vZ(e,t){let r=function(e,t){if(f.isAbsolute(e))return e;if(!t.baseDir)throw new D("INVALID_ARGS","runFlow file paths require replay input to have a source path.");return f.resolve(t.baseDir,e)}(e,t);if(t.visitedPaths.has(r))throw new D("INVALID_ARGS",`Maestro runFlow cycle detected at ${r}.`);let n=l.readFileSync(r,"utf8"),i=new Set(t.visitedPaths);return i.add(r),vJ(n,{...t,baseDir:f.dirname(r),visitedPaths:i})}let vY={maestro:{parse:function(e,t={}){var r;let n;return vJ(e,(n=(r=t).visitedPaths??new Set,r.sourcePath&&n.add(f.resolve(r.sourcePath)),{baseDir:r.sourcePath?f.dirname(r.sourcePath):void 0,platform:function(e){if(e){let t;return"android"===(t=e.trim().toLowerCase())?"android":"ios"===t?"ios":void 0}}(r.platform),env:{},envOverrides:r.env??{},visitedPaths:n}))}}};function vQ(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=void 0!==t&&/^\d+$/.test(t)?t:null,n=t1(null!==r?e.slice(0,-1):e.slice());return!n||n.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:n.selectorExpression,selectorTimeout:r}}async function v0(e){let{action:t,sessionName:r,logPath:n,sessionStore:i}=e;if(!(iB(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let a=i.get(r);if(!a)return null;let o=(function(e){let t=[],r=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];if(t.push(...r),iB(e.command)){let r=function(e){let t=e.positionals??[];if("longpress"!==e.command)return t;let r=t.at(-1);return t.length>1&&v1(r)?t.slice(0,-1):t}(e),n=r[0]??"";n&&!n.startsWith("@")&&t.push(r.join(" "))}if("fill"===e.command){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&Number.isNaN(Number(r))&&t.push(r)}if("get"===e.command){let r=e.positionals?.[1]??"";r&&!r.startsWith("@")&&t.push(e.positionals.slice(1).join(" "))}if("is"===e.command){let{split:r}=t4(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=vQ(e.positionals??[]);r&&t.push(r)}return iT(t).filter(e=>e.trim().length>0)})(t).map(e=>t3(e)).filter(e=>null!==e);if(0===o.length)return null;let s=iB(t.command)||"fill"===t.command,l=iB(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await v2(a,t,n,s,i);for(let e of o){let r=re(u.nodes,e,{platform:a.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let n=rn(r.node,a.device.platform,{action:"fill"===t.command?"fill":iB(t.command)?"click":"get"}).join(" || ");if(iB(t.command))return{...t,positionals:"longpress"===t.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);return e.length>1&&v1(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,n):[n]};if("fill"===t.command){let e=iL(t);if(!e)continue;return{...t,positionals:[n,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,n]}}if("is"===t.command){let{predicate:e,split:r}=t4(t.positionals);if(!e)continue;let i=r?.rest.join(" ").trim()??"",a=[e,n];return"text"===e&&i.length>0&&a.push(i),{...t,positionals:a}}if("wait"===t.command){let{selectorTimeout:e}=vQ(t.positionals??[]),r=[n];return e&&r.push(e),{...t,positionals:r}}}return null}function v1(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function v2(e,t,r,n,i){let a=pz(await cF(e.device,"snapshot",[],t.flags?.out,{...pg(r,{...t.flags??{},snapshotInteractiveOnly:n,snapshotCompact:n},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:n,snapshotCompact:n});return pZ(e,a),i.set(e.name,e),a}let v3=new WeakMap;function v5(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function v4(e){var t;let r,n=await e.invoke({...e.baseReq,command:"snapshot",positionals:[],flags:{...e.baseReq.flags,noRecord:!0,snapshotRaw:!0,snapshotForceFull:!0}});return n.ok&&e.scope&&(t=e.scope,(r=fE(v8(n.data)))&&v3.set(t,r)),n}function v8(e){if("object"==typeof e&&null!==e&&Array.isArray(e.nodes))return e}let v6=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function v9(e,t,r,n){var i;let a,o,s=Ir(e,t,r),l=(a=(i={nodes:e.nodes,matches:s,platform:r}).matches.filter(e=>tM({predicate:"visible",node:e,nodes:i.nodes,platform:i.platform}).pass),{matches:(o=v7(i.nodes,a)).matches,blockedByReactNativeOverlay:o.blockedByReactNativeOverlay}),u=Ia(e.nodes,l.matches,void 0,It(t),n,!0);return u?{ok:!0,node:u.node,rect:u.rect,matches:l.matches.length}:{ok:!1,message:s.length>0?l.blockedByReactNativeOverlay?`Maestro selector matched ${s.length} element(s), but React Native overlay is covering app content: ${t}`:`Maestro selector matched ${s.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function v7(e,t){let r=tj(e);if(!r.detected||!r.redBox)return{matches:t,blockedByReactNativeOverlay:!1};let n=new Set([...r.dismissNodes,...r.minimizeNodes,...r.collapsedNodes].map(e=>e.index)),i=t.filter(e=>n.has(e.index));return{matches:i,blockedByReactNativeOverlay:t.length>0&&0===i.length}}function Ie(e){return e?.platform==="android"?"android":"ios"}function It(e){let t=t9(e).selectors.flatMap(e=>e.terms);if(0===t.length||!t.some(e=>"label"===e.key||"text"===e.key)||!t.every(e=>["label","text","id"].includes(e.key)))return null;let r=t.map(e=>"string"==typeof e.value?e.value:""),n=r[0];return n&&r.every(e=>e===n)?n:null}function Ir(e,t,r){for(let n of t9(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r){return!!rt(e,t,r)||t.terms.every(t=>(function(e,t,r){var n,i,a;return"string"!=typeof t.value||"id"!==(n=t.key)&&"label"!==n&&"text"!==n&&"value"!==n?rt(e,{raw:t.key,terms:[t]},r):In((i=e,"id"===(a=t.key)?i.identifier:"label"===a?i.label:"value"===a?i.value:t2(i)),t.value)})(e,t,r))})(e,n,r));if(t.length>0)return t}return[]}function In(e,t){let r=e??"";if(ro(r)===ro(t))return!0;try{return new RegExp(t).test(r)}catch{return!1}}function Ii(e,t,r){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let n=function(e,t,r){let n=t;for(;"number"==typeof n.parentIndex&&(n=r.get(n.parentIndex)??e[n.parentIndex]);)if(n.rect)return n.rect.width>0&&n.rect.height>0?n.rect:null;return null}(e,t,r);return n?{rect:n,inherited:!0}:null}function Ia(e,t,r,n,i,a=!1,o=!1){var s,l,u,d,c,p,f,m,h,w,g,y,v,I,b,A,S,x,_;let N,M,k,D,O=Ih(e),P=(s=e,l=t,u=O,d=n,c=r,p=i,f=a,k=(M=(N=l.map(e=>{var t;let r;return(r=Ii(s,t=e,u))?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e)).filter(e=>!e.inheritedRect)).length>0?M:N,d&&void 0===c?(m=k,h=p,w=f,D=m.filter(e=>{var t,r;let n,i;return t=e.rect,r=h,n=r?.referenceWidth??1/0,i=r?.referenceHeight??1/0,t.x<n&&t.y<i&&t.x+t.width>0&&t.y+t.height>0}),w||D.length>0?D:m):N),R=function(e,t,r,n,i){var a,o,s,l,u;if(void 0!==r)return t[r]??null;let d=(a=e,o=t,s=n,i&&s?function(e,t,r){let n=t.filter(e=>0===Ip(e.node,r));if(n.length>=2){let t=Is(e,n,r);if(t)return t}let i=t.filter(e=>1===Ip(e.node,r));return n.length>0||i.length<2?null:Is(e,i,r)}(a,o,s)??Io(a,o,s):Io(a,o,s));return(l=d,u=n,i&&u&&l)?function(e,t,r){var n,i,a,o,s,l,u,d,c,p,f,m,h,w,g,y,v;let I,b,A,S,x,_,N,M;if(n=t,i=r,!(("other"===(I=rr(n.node.type??""))||"scrollview"===I||"scroll-area"===I)&&!(n.rect.width<120)&&!(n.rect.height<32)&&!(n.rect.height>80)&&1>=Ip(n.node,i)))return null;let k=(a=e,o=t,s=r,a.filter(e=>{var t,r,n,i,a;let l,u;return e.parentIndex===o.node.index&&!!e.rect&&(t=e,r=o.rect,n=s,!("button"!==(l=rr(t.type??""))&&"cell"!==l&&"other"!==l||1>=Ip(t,n))&&!(t.rect.width<16)&&!(t.rect.height<16)&&!!Ic(r,t.rect)&&(i=r,a=t.rect,u=Math.max(i.y,a.y),Math.max(0,Math.min(i.y+i.height,a.y+a.height)-u)/Math.max(1,Math.min(i.height,a.height))>=.5))}).sort((e,t)=>e.rect.x-t.rect.x));if(0===k.length)return null;let D=(A=Math.floor((b=[...k.map(e=>e.rect.width)].sort((e,t)=>e-t)).length/2),b[A]??0),O=function(e,t){let r=[],n=e.x,i=e.x+e.width;for(let a of t){let t=Math.max(e.x,a.x),o=Math.min(i,a.x+a.width);t>n&&r.push({x:n,width:t-n}),n=Math.max(n,o)}return i>n&&r.push({x:n,width:i-n}),r}(t.rect,k.map(e=>e.rect)),P=(l=t,u=r,d=O,c=D,_=d.filter(e=>{var t,r;return t=e.width,r=c,!(t<24)&&!(r<24)&&t>=.4*r&&t<=1.6*r}),N=(p=l,f=u,S=d.find(e=>1>Math.abs(e.x-p.rect.x)),x=Math.max(48,Math.min(220,8*f.length+24)),(m=p,h=f,w=S,g=x,w&&"scrollview"===rr(m.node.type??"")&&1>=Ip(m.node,h)&&m.rect.width>=240&&m.rect.height>=32&&m.rect.height<=80&&w.width<=.55*m.rect.width&&w.width>=.6*g)?{x:p.rect.x,width:Math.min(x,S.width)}:null),M=_.some(e=>{var t;return t=l.rect,1>Math.abs(e.x-t.x)}),N&&!M?N:1===_.length?_[0]??null:N);return P?(y=t,v=P,{...y,rect:{x:v.x,y:y.rect.y,width:v.width,height:y.rect.height}}):null}(e,d,n)??d:d}(e,P,r,n,o);return g=e,y=R,v=O,I=o,b=i,y?I?(A=g,S=y,x=v,_=b,(Id(S.node)?null:Im(A,S.node,x,e=>{if(!Id(e))return null;let t=Ii(A,e,x);return t&&function(e,t,r){if(!Ic(t,e))return!1;let n=Il(t),i=Il(e);if(i>0&&n>30*i)return!1;if(r){let e=r.referenceWidth*r.referenceHeight;if(e>0&&n>.5*e)return!1}return!0}(S.rect,t.rect,_)?{node:e,rect:t.rect}:null}))??{node:y.node,rect:y.rect}):{node:y.node,rect:y.rect}:null}function Io(e,t,r){return(function(e,t,r){if(!r||t.length<2)return t;let n=t.filter(e=>0===Ip(e.node,r));if(n.length<2)return t;let i=Ih(e),a=n.map(t=>{var r,n;return{candidate:t,container:(r=e,n=t.node,Im(r,n,i,e=>{let t;return!e.rect||"scrollview"!==(t=rr(e.type??""))&&"scroll-area"!==t&&"list"!==t||e.rect.width<240||e.rect.height<320?null:e}))}}).filter(e=>!!e.container);if(a.length<2||a.length!==n.length)return t;let o=a.filter(e=>{var t;return t=e,a.some(e=>{var r,n;let i,a,o;return e!==t&&t.container.index!==e.container.index&&(r=t.container.rect,n=e.container.rect,i=Math.max(r.x,n.x),a=Math.min(r.x+r.width,n.x+n.width),o=Math.max(r.y,n.y),Math.max(0,a-i)*Math.max(0,Math.min(r.y+r.height,n.y+n.height)-o)/Math.max(1,Math.min(Il(r),Il(n)))>=.6)})});if(o.length<2)return t;let s=Math.max(...o.map(e=>e.container.index)),l=o.filter(e=>e.container.index===s).map(e=>e.candidate);return l.length>0?l:t})(e,t,r).sort((e,t)=>(function(e,t,r){var n,i;let a=function(e,t,r){if(r){let n=Ip(e.node,r)-Ip(t.node,r);if(0!==n)return n}let n=Iu(e.node)-Iu(t.node);if(0!==n)return n;let i=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==i)return i;let a=r&&Iu(e.node)===Iu(t.node)?Il(t.rect)-Il(e.rect):Il(e.rect)-Il(t.rect);return 0!==a?a:0}(e,t,r);if(0!==a)return a;if(n=e.rect,i=t.rect,Math.round(n.x)!==Math.round(i.x)||Math.round(n.y)!==Math.round(i.y)||Math.round(n.width)!==Math.round(i.width)||Math.round(n.height)!==Math.round(i.height))return e.node.index-t.node.index;let o=(t.node.depth??0)-(e.node.depth??0);return 0!==o?o:t.node.index-e.node.index})(e,t,r))[0]??null}function Is(e,t,r){let n=Ih(e),i=t.filter(r=>{var i;return(i=r).rect.width>=16&&i.rect.width<=260&&i.rect.height>=24&&i.rect.height<=80&&t.some(t=>{var i,a,o,s;return i=e,a=t,o=r,s=n,!(a.node.index===o.node.index||!Ic(a.rect,o.rect)||Il(a.rect)<2*Il(o.rect))&&If(i,o.node,a.node,s)})});return Io(e,i,r)}function Il(e){return e.width*e.height}function Iu(e){return v6.get(rr(e.type??""))??3}function Id(e){let t=rr(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function Ic(e,t){return t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height}function Ip(e,t){let r=[e.label,t2(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>ro(e)===ro(t))?1:r.some(e=>In(e,t))?2:3}function If(e,t,r,n){return!!Im(e,t,n,e=>e===r||e.index===r.index?e:null)}function Im(e,t,r,n){let i=t;for(;"number"==typeof i.parentIndex&&(i=r.get(i.parentIndex)??e[i.parentIndex]);){let e=n(i);if(e)return e}return null}function Ih(e){return new Map(e.map(e=>[e.index,e]))}async function Iw(e){let t,r=function(e){let[t,r="5000"]=e;if(!t)return{ok:!1,response:v5("INVALID_ARGS","assertVisible requires a selector.")};let n=Number(r);return!Number.isFinite(n)||n<0?{ok:!1,response:v5("INVALID_ARGS","assertVisible timeout must be a non-negative number.")}:{ok:!0,selector:t,timeoutMs:n}}(e.positionals);if(!r.ok)return r.response;let n=Date.now(),i=r.timeoutMs+1e3,a=!1;for(;;){let d=Date.now(),c=await Ig(e,r.selector,n);if(c.done)return c.response;if(t=c.response,Date.now()-n>=i){var o,s,l,u;if(o=a,s=d,l=n,u=i,!o&&s-l<u){a=!0;continue}break}await e8(250)}return t??v5("COMMAND_FAILED",`Expected visible but did not match: ${r.selector}`,{selector:r.selector,timeoutMs:r.timeoutMs})}async function Ig(e,t,r){let n=await v4(e);if(!n.ok)return{done:!1,response:n};let i=v8(n.data);if(!i)return{done:!0,response:v5("COMMAND_FAILED","Unable to read snapshot data for assertVisible.")};let a=v9(i,t,Ie(e.baseReq.flags),fE(i));return a.ok?{done:!0,response:{ok:!0,data:{selector:t,matches:a.matches,nodeIndex:a.node.index,nodeType:a.node.type,nodeLabel:a.node.label,nodeIdentifier:a.node.identifier,rect:a.rect,waitedMs:Date.now()-r}}}:{done:!1,response:v5("COMMAND_FAILED",a.message,{selector:t})}}async function Iy(e){let t,[r]=e.positionals;if(!r)return v5("INVALID_ARGS","assertNotVisible requires a selector.");let n=Date.now(),i=0;for(;Date.now()-n<=3e3;){let a=await Iv(e,r);if(a.visible)i=0,t=a.response;else{if(!a.hidden)return a.response;i+=1;let e=Date.now()-n;if(i>=2||e>=3e3)return{ok:!0,data:{pass:!0,selector:r,stableSamples:i,waitedMs:e,timeoutMs:3e3}}}await e8(250)}return v5("COMMAND_FAILED",`Expected not visible but matched: ${r}`,{selector:r,timeoutMs:3e3,lastResponse:t})}async function Iv(e,t){let r=await v4(e);if(!r.ok)return{visible:!1,hidden:!1,response:r};let n=v8(r.data);if(!n)return{visible:!1,hidden:!1,response:v5("COMMAND_FAILED","Unable to read snapshot data for assertNotVisible.")};let i=v9(n,t,Ie(e.baseReq.flags),fE(n));return i.ok?{visible:!0,hidden:!1,response:{ok:!0,data:{selector:t,matches:i.matches,nodeIndex:i.node.index,nodeType:i.node.type,nodeLabel:i.node.label,nodeIdentifier:i.node.identifier,rect:i.rect}}}:{visible:!1,hidden:!0,response:v5("COMMAND_FAILED",i.message,{selector:t})}}async function II(e){let t,r,n=Number(e.positionals[0]??15e3);if(!Number.isFinite(n)||n<0)return v5("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let i=Date.now();for(;Date.now()-i<n;){let i=await v4(e),a=function(e,t,r){let n=function(e){if(!e.ok)return null;let t=v8(e.data);return t?JSON.stringify(t.nodes.map(e=>({index:e.index,parentIndex:e.parentIndex,type:e.type,identifier:e.identifier,label:e.label,value:e.value,rect:e.rect?{x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height)}:void 0}))):null}(e);return e.ok?n?t===n?{done:!0,response:{ok:!0,data:{stable:!0,timeoutMs:r}}}:{done:!1,signature:n}:{done:!0,response:e}:{done:!1}}(i,t,n);if(a.done)return a.response;t=a.signature??t,r=i,await e8(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:n}}}function Ib(e){let t={ts:Date.now(),command:e.command,positionals:e.positionals??[],flags:e.flags??{}};return e.runtime&&"object"==typeof e.runtime&&(t.runtime=e.runtime),t}function IA(e){return(e??[]).map(Ib)}async function IS(e){for(let[t,r]of e.actions.entries()){let n=await e.invokeReplayAction({action:r,line:e.line,step:e.step+t/1e3});if(!n.ok)return n}return{ok:!0,data:{ran:e.actions.length}}}async function Ix(e){let t;for(let r=0;r<=e.maxRetries;r+=1){let n=await IS({actions:e.actions,line:e.line,step:e.step+r,invokeReplayAction:e.invokeReplayAction});if(n.ok)return{ok:!0,data:{attempts:r+1,retried:r>0}};t=n}return t??{ok:!1,error:{code:"COMMAND_FAILED",message:"retry commands failed."}}}async function I_(e){let t=function(e){let[t,r]=e;return("visible"===t||"notVisible"===t)&&r?{ok:!0,mode:t,selector:r}:{ok:!1,response:v5("INVALID_ARGS","runFlow.when requires visible/notVisible and a selector.")}}(e.positionals);if(!t.ok)return t.response;let r=await IM(e,t);return r.ok?r.matched?await IO(e,t):{ok:!0,data:{skipped:!0,condition:t.mode,selector:t.selector}}:r.response}async function IN(e){let[t="1"]=e.positionals,r=Number(t);return!Number.isInteger(r)||r<0?v5("INVALID_ARGS","retry.maxRetries must be a non-negative integer."):await Ix({actions:IA(e.batchSteps),maxRetries:r,line:e.line,step:e.step,invokeReplayAction:e.invokeReplayAction})}async function IM(e,t){if("visible"===t.mode)return await Ik(e,t);let r=await v4(e);if(!r.ok)return{ok:!1,response:r};let n=ID(e,t.selector,r);return n.ok?{ok:!0,matched:!n.matched}:{ok:!1,response:n.response}}async function Ik(e,t){let r=Date.now();for(;;){let n=await v4(e);if(!n.ok)return{ok:!1,response:n};let i=ID(e,t.selector,n);if(!i.ok)return{ok:!1,response:i.response};if(i.matched)return{ok:!0,matched:!0};if(Date.now()-r>=3e3)return{ok:!0,matched:!1};await e8(250)}}function ID(e,t,r){let n=v8(r.data);return n?{ok:!0,matched:v9(n,t,Ie(e.baseReq.flags),fE(n)).ok}:{ok:!1,response:v5("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")}}async function IO(e,t){let r=await IS({actions:IA(e.batchSteps),line:e.line,step:e.step,invokeReplayAction:e.invokeReplayAction});return r.ok?{ok:!0,data:{ran:r.data?.ran,condition:t.mode,selector:t.selector}}:r}let IP=.35,IR=120,IC=360,IE=8,IL=120,IT=70,I$=200,IF=168,IU=48;function IV(e,t){return Math.round(Math.min(IC,Math.max(IR,"number"==typeof e?e*IP:0,1.5*t)))}function IG(e,t,r){return Math.round(Math.min(r,Math.max(t,e)))}async function Iq(e){var t,r,n;let[i,a="5000",o="down"]=e.positionals;if(!i)return v5("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(a);if(!Number.isFinite(s)||s<=0)return v5("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=It(i),u=Math.max(1,Math.ceil(s/500)),d=null;for(let t=0;t<u;t+=1){let r=await I0(e,i,l,Math.min(500,Math.max(1,s-500*t)));if(r.ok)return r;if(d=r,t===u-1)break;let n=await e.invoke({...e.baseReq,command:"scroll",positionals:[o]});if(!n.ok)return n}return t=d,r=i,n=s,t?{ok:!1,error:{...t.error,message:`scrollUntilVisible timed out after ${n}ms for selector: ${r}. Last wait: ${t.error.message}`}}:v5("COMMAND_FAILED",`scrollUntilVisible timed out after ${n}ms for selector: ${r}`)}async function IB(e){let[t,r]=e.positionals,n=Number(t),i=Number(r);if(!Number.isFinite(n)||!Number.isFinite(i))return v5("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let a=await v4(e);if(!a.ok)return a;let o=v8(a.data);if(!o)return v5("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=fE(o);return s?await e.invoke({...e.baseReq,command:"click",positionals:[String(Math.round(s.referenceWidth*n/100)),String(Math.round(s.referenceHeight*i/100))]}):v5("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.")}async function Ij(e){let t=await IK(e);return t.ok?await Iz(e,t,t.durationMs):t.response}async function IH(e){var t,r,n,i;let a,[o,s]=e.positionals;if(!o)return v5("INVALID_ARGS","tapOn requires a selector.");let l=function(e){if(!e)return{ok:!0,value:null};try{let t=JSON.parse(e);return{ok:!0,value:t}}catch{return{ok:!1,response:v5("INVALID_ARGS","tapOn runtime options must be valid JSON.")}}}(s);if(!l.ok)return l.response;let u=Date.now(),d=(t=e,t.baseReq.flags?.maestro?.optional===!0?3e3:3e4);for(;Date.now()-u<d;){let t=await I1(e,o,l.value??{});if(!t.retry)return t.response;a=t.response,await e8(250)}return r=e,n=o,i=a,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:n}}:i??v5("COMMAND_FAILED",`tapOn timed out for selector: ${n}`)}async function IW(e){let[t,r="up",n]=e.positionals;if(!t)return v5("INVALID_ARGS","swipe.label requires a label selector.");let i=await I5(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!i.ok)return i.response;let a=function(e,t){let r=tA(e.rect),n=e.frame,i=IV(n?.referenceWidth,e.rect.width),a=IV(n?.referenceHeight,e.rect.height),o=IE,s=n?n.referenceWidth-o:r.x+i,l=n?n.referenceHeight-o:r.y+a;switch(t.toLowerCase()){case"up":return{ok:!0,start:r,end:{x:r.x,y:IG(r.y-a,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:IG(r.y+a,o,l)}};case"left":return{ok:!0,start:r,end:{x:IG(r.x-i,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:IG(r.x+i,o,s),y:r.y}};default:return{ok:!1,message:"swipe.label direction must be up, down, left, or right."}}}(i.target,r);return a.ok?await Iz(e,a,n):v5("INVALID_ARGS",a.message)}async function Iz(e,t,r){return await e.invoke({...e.baseReq,command:"swipe",positionals:[String(t.start.x),String(t.start.y),String(t.end.x),String(t.end.y),...r?[r]:[]]})}async function IK(e){var t;let r=((t=e.scope)?v3.get(t):void 0)??await IJ(e);if(!r)return{ok:!1,response:v5("COMMAND_FAILED","Unable to resolve screen size for Maestro swipe.")};let[n,...i]=e.positionals;return"direction"===n?function(e,t,r){let[n,i]=e;if(!n)return{ok:!1,response:v5("INVALID_ARGS","Maestro direction swipe requires a direction.")};switch(n){case"up":return{ok:!0,start:IY(t,50,80,8),end:IY(t,50,20,8),durationMs:i};case"down":return{ok:!0,start:IY(t,50,20,8),end:IY(t,50,80,8),durationMs:i};case"left":{let[e,n]=IX(r,80,20),a=IZ(r,e,50,n,50);return{ok:!0,start:IY(t,e,a,8),end:IY(t,n,a,8),durationMs:i}}case"right":{let[e,n]=IX(r,20,80),a=IZ(r,e,50,n,50);return{ok:!0,start:IY(t,e,a,8),end:IY(t,n,a,8),durationMs:i}}default:return{ok:!1,response:v5("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(i,r,Ie(e.baseReq.flags)):"percent"===n?function(e,t,r){let[n,i,a,o,s]=e,l=[n,i,a,o].map(Number);if(l.some(e=>!Number.isFinite(e)))return{ok:!1,response:v5("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[u,d,c,p]=l,f=IZ(r,u,d,c,p);return{ok:!0,start:IY(t,u,f,1),end:IY(t,c,f,1),durationMs:s}}(i,r,Ie(e.baseReq.flags)):{ok:!1,response:v5("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function IJ(e){let t=await v4(e);if(t.ok)return fE(v8(t.data))}function IX(e,t,r){return"android"!==e?[t,r]:t<r?[20,80]:[80,20]}function IZ(e,t,r,n,i){return"android"!==e||r!==i||50!==r||30>Math.abs(n-t)?i:65}function IY(e,t,r,n){return{x:IQ(Math.round(e.referenceWidth*t/100),n,e.referenceWidth),y:IQ(Math.round(e.referenceHeight*r/100),n,e.referenceHeight)}}function IQ(e,t,r){return Math.min(Math.max(t,r-t),Math.max(t,e))}async function I0(e,t,r,n){let i=await e.invoke({...e.baseReq,command:"wait",positionals:[t,String(n)]});return i.ok||!r?i:await e.invoke({...e.baseReq,command:"find",positionals:[r,"wait",String(n)]})}async function I1(e,t,r){let n=It(t),i=await I2(e,t,r);return i.response.ok?{retry:!1,response:i.response}:i.targetResolved&&n?await I3(e,n):{retry:!0,response:i.response}}async function I2(e,t,r){var n,i;let a=await I5(e,t,r,"tapOn",{promoteTapTarget:!0});if(!a.ok)return{response:a.response,targetResolved:!1};let o=(n=a.target,i=null!==It(t),!function(e,t,r){if(!t||r.width<IL)return!1;let n=rr(e.type??"");return!(r.height<IT)&&!(r.height>I$)&&("cell"===n||"other"===n||"scrollview"===n||"scroll-area"===n)}(n.node,i,n.rect)?tA(n.rect):{x:tV(n.rect.x,Math.min(n.rect.width,IF)),y:tV(n.rect.y,Math.min(n.rect.height,IU))});return{response:await e.invoke({...e.baseReq,command:"click",positionals:[String(o.x),String(o.y)]}),targetResolved:!0}}async function I3(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0}});return r.ok?{retry:!1,response:r}:{retry:!0,response:r}}async function I5(e,t,r,n,i){let a=await v4(e);if(!a.ok)return{ok:!1,response:a};let o=v8(a.data);if(!o)return{ok:!1,response:v5("COMMAND_FAILED",`Unable to read snapshot data for ${n}.`)};let s=fE(o),l=function(e,t,r,n,i,a={}){let o=Ir(e,t,n);if(r.childOf){let t=Ir(e,r.childOf,n);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let i=Ih(e.nodes);o=o.filter(r=>t.some(t=>If(e.nodes,r,t,i)))}let s=v7(e.nodes,o),l=Ia(e.nodes,s.matches,r.index,It(t),i,!1,a.promoteTapTarget);if(!l){let e=r.index??0;return{ok:!1,message:s.blockedByReactNativeOverlay?`Maestro selector matched ${o.length} element(s), but React Native overlay is covering app content: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:l.node,rect:l.rect}}(o,t,r,Ie(e.baseReq.flags),s,i);if(!l.ok){let e=It(t);if(e){let t=function(e,t,r,n={}){let i=function(e,t){let r=ro(t);if(!r)return[];let n=[],i=[];for(let t of e.nodes){let e=[t.label,t2(t),t.identifier,t.value].filter(e=>!!e).map(e=>ro(e));e.some(e=>e===r)?n.push(t):e.some(e=>e.includes(r))&&i.push(t)}return n.length>0?n:i}(e,t),a=Ia(e.nodes,i,void 0,t,r,!1,n.promoteTapTarget);return a?{ok:!0,node:a.node,rect:a.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}(o,e,s,i);if(t.ok)return{ok:!0,target:{node:t.node,rect:t.rect,frame:s}}}}return l.ok?{ok:!0,target:{node:l.node,rect:l.rect,frame:s}}:{ok:!1,response:v5("ELEMENT_NOT_FOUND",l.message,{selector:t,options:r,command:n})}}async function I4(e){switch(e.command){case vv:return await Iw(e);case vI:return await Iy(e);case vg:return await IN(e);case vb:return await I8(e);case vA:return await II(e);case vS:return await Iq(e);case vx:return await Ij(e);case v_:return await IW(e);case vN:return await IH(e);case vM:return await IB(e);case vw:return await I_(e);case vy:return function(e){let[t]=e.positionals;if(!t)return v5("INVALID_ARGS","runScript requires a file path.");try{let r=function(e){let{scriptPath:t,env:r}=e,n=l.readFileSync(t,"utf8"),i=Object.create(null);try{var a,o;_.runInNewContext(n,(a=r,o=i,{...a,output:o,json:vB,http:{post:(e,t)=>(function(e,t,r){let n=C(process.execPath,["-e",vq],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??""}),timeoutMs:3e4,allowFailure:!0});if(0!==n.exitCode){let r;throw new D("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${(r=n.stderr.trim()).length>0?r.slice(0,1e3):"request process exited without stderr"}`,{exitCode:n.exitCode,stderr:n.stderr})}try{return JSON.parse(n.stdout)}catch(r){throw new D("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:n.stdout.slice(0,1e3),stderr:n.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}})("POST",e,t)}}),{filename:t,timeout:3e4})}catch(e){throw new D("COMMAND_FAILED",`Maestro runScript failed for ${t}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:t},e instanceof Error?e:void 0)}return function(e,t){for(let r of Object.keys(e))if(r.includes("."))throw new D("INVALID_ARGS",`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}(i,t),Object.fromEntries(Object.entries(i).map(([e,t])=>{var r;return[`output.${e}`,(r=t,"string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):JSON.stringify(r))]}))}({scriptPath:t,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}});return{ok:!0,data:{outputEnv:r}}}catch(t){let e=M(t);return v5(e.code,e.message,e.details)}}(e);default:return}}async function I8(e){let t=await e.invoke({...e.baseReq,command:"keyboard",positionals:["enter"]});return t.ok?t:await e.invoke({...e.baseReq,command:"type",positionals:["\n"]})}async function I6(e){var t;let{req:r,sessionName:n,action:i,scope:a,filePath:o,line:s,step:l,tracePath:u,invoke:d}=e,c=(t={file:o,line:s},{...i,positionals:(i.positionals??[]).map(e=>yH(e,a,t)),flags:yW(i.flags,a,t)??{},runtime:yW(i.runtime,a,t)}),p=Date.now();I7(u,{type:"replay_action_start",ts:new Date(p).toISOString(),replayPath:o,line:s,step:l,command:c.command,positionals:c.positionals??[]});let f=await I9({req:r,sessionName:n,resolved:c,scope:a,line:s,step:l,invoke:d,invokeReplayAction:e=>I6({req:r,sessionName:n,action:e.action,scope:a,filePath:o,line:e.line,step:e.step,tracePath:u,invoke:d})}),m=Date.now();return I7(u,{type:"replay_action_stop",ts:new Date(m).toISOString(),replayPath:o,line:s,step:l,command:c.command,ok:f.ok,durationMs:m-p,errorCode:f.ok?void 0:f.error.code}),f}async function I9(e){var t;let{req:r,sessionName:n,resolved:i,scope:a,line:o,step:s,invoke:l,invokeReplayAction:u}=e,d=(t=r.flags,ru(t,{...i.flags??{}})),c={token:r.token,session:n,flags:d,runtime:i.runtime,meta:r.meta},p=await I4({command:i.command,baseReq:c,positionals:i.positionals??[],batchSteps:i.flags?.batchSteps,scope:a,line:o,step:s,invoke:l,invokeReplayAction:u})??await l({...c,command:i.command,positionals:i.positionals??[]});if(p.ok){let e=function(e){if(!e||"object"!=typeof e)return null;let t=e.outputEnv;if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=Object.entries(t).filter(e=>"string"==typeof e[1]);return r.length>0?Object.fromEntries(r):null}(p.data);e&&Object.assign(a.values,e)}return p}function I7(e,t){e&&l.appendFileSync(e,`${JSON.stringify(t)}
89
- `)}async function be(e){let{req:t,sessionName:r,logPath:n,sessionStore:i,invoke:a}=e,o=t.positionals?.[0];if(!o)return cX("INVALID_ARGS","replay requires a path");let s="",u=new Set;try{var d,c;s=i4.expandHome(o,t.meta?.cwd);let e=l.readFileSync(s,"utf8"),p=e.trimStart()[0];if("{"===p||"["===p)return cX("INVALID_ARGS","replay accepts .ad script files. JSON replay payloads are no longer supported.");let m=function(e,t,r={}){var n;let i=function(e){let t=e?.replayBackend;if("string"!=typeof t)return;let r=vY[t];if(!r)throw new D("INVALID_ARGS",`Unsupported replay backend "${t}".`);return r}(t);return i?{...i.parse(e,{...r,platform:t?.platform,env:(n=t,{...yG(yj(n?.replayShellEnv)),...yq(yB(n?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...function(e){let t=[],r=[],n=e.split(/\r?\n/),i=!1;for(let[e,a]of n.entries()){let n=a.trim();if(0===n.length||n.startsWith("#"))continue;if(yX(n)){if(i)throw new D("INVALID_ARGS",`env directives must precede all actions (line ${e+1}).`);continue}let o=function(e){let t=e.trim();if(0===t.length||t.startsWith("#"))return null;let[r,...n]=function(e){let t=[],r=0;for(;r<e.length&&!((r=function(e,t){let r=t;for(;r<e.length&&/\s/.test(e.charAt(r));)r+=1;return r}(e,r))>=e.length);){let n='"'===e[r]?function(e,t){let r=!1,n=t+1;for(;n<e.length;n+=1){let t=e.charAt(n);if('"'===t&&!r)break;if(r){r=!1;continue}r="\\"===t}if(n>=e.length)throw new D("INVALID_ARGS",`Invalid replay script line: ${e}`);return{value:JSON.parse(e.slice(t,n+1)),nextCursor:n+1}}(e,r):function(e,t){let r=t;for(;r<e.length&&!/\s/.test(e.charAt(r));)r+=1;return{value:e.slice(t,r),nextCursor:r}}(e,r);t.push(n.value),r=n.nextCursor}return t}(t);if(void 0===r||"context"===r)return null;let i={ts:Date.now(),command:r,positionals:[],flags:{}};if("snapshot"===r){i.positionals=[];for(let e=0;e<n.length;e+=1){let t=n[e];if("-i"===t){i.flags.snapshotInteractiveOnly=!0;continue}if("-c"===t){i.flags.snapshotCompact=!0;continue}if("--raw"===t){i.flags.snapshotRaw=!0;continue}if("--force-full"===t){i.flags.snapshotForceFull=!0;continue}if(("-d"===t||"--depth"===t)&&e+1<n.length){let t=Number(n[e+1]);Number.isFinite(t)&&t>=0&&(i.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if(("-s"===t||"--scope"===t)&&e+1<n.length){i.flags.snapshotScope=n[e+1],e+=1;continue}if("--backend"===t&&e+1<n.length){e+=1;continue}}return i}if("open"===r){let e=function(e){var t;let r=[],n={};for(let t of e){if("--relaunch"===t){n.relaunch=!0;continue}r.push(t)}let i=iQ(r);return{positionals:i.positionals,flags:n,runtime:(t=i.flags).platform||t.metroHost||void 0!==t.metroPort||t.bundleUrl||t.launchUrl?i.flags:void 0}}(n);return i.positionals=e.positionals,Object.assign(i.flags,e.flags),i.runtime=e.runtime,i}if("runtime"===r){let e=iQ(n);return i.positionals=e.positionals,Object.assign(i.flags,e.flags),i}if(iq(r)){let e=iY(r,n);Object.assign(i.flags,e.flags);let t=e.positionals[0];if(void 0===t)return i;if(t.startsWith("@"))return i.positionals=[t],e.positionals[1]&&(i.result={refLabel:e.positionals[1]}),i;let a=e.positionals[0],o=e.positionals[1];return yY(a)&&yY(o)&&e.positionals.length>=2?i.positionals=[a,o]:i.positionals=[e.positionals.join(" ")],i}if("fill"===r){let e=iY(r,n);if(Object.assign(i.flags,e.flags),!(e.positionals.length>=2))return i.positionals=e.positionals,i;let[t,a,...o]=e.positionals;return t.startsWith("@")?(o.length>0?(i.positionals=[t,o.join(" ")],i.result={refLabel:a}):i.positionals=[t,a],i):(i.positionals=[t,[a,...o].join(" ")],i)}if("get"===r){let e=n[0],t=n[1];return void 0===e||void 0===t?i.positionals=n:t.startsWith("@")?(i.positionals=[e,t],n[2]&&(i.result={refLabel:n[2]})):i.positionals=[e,n.slice(1).join(" ")],i}if("swipe"===r||"type"===r){let e=iY(r,n);return Object.assign(i.flags,e.flags),i.positionals=e.positionals,i}if("record"===r){let e=[];for(let t=0;t<n.length;t+=1){let r=n[t];if("--hide-touches"===r){i.flags.hideTouches=!0;continue}if("--fps"===r&&t+1<n.length){let e=Number(n[t+1]);Number.isFinite(e)&&(i.flags.fps=Math.floor(e)),t+=1;continue}if("--quality"===r&&t+1<n.length){let e=Number(n[t+1]);Number.isFinite(e)&&(i.flags.quality=Math.floor(e)),t+=1;continue}e.push(r)}return i.positionals=e,i}if("screenshot"===r){let e=[];for(let t=0;t<n.length;t+=1){let r=n[t],a=eK({args:n,index:t,flags:i.flags});if(a.handled){t=a.nextIndex;continue}e.push(r)}return i.positionals=e,i}return i.positionals=n,i}(a);o&&(t.push(o),r.push(e+1),i=!0)}return{actions:t,actionLines:r}}(e),metadata:yJ(e)}}(e,t.flags,{sourcePath:s}),h=m.metadata,w=h.platform||h.target?{...t,flags:(d=t.flags,c=h,{...d??{},...void 0!==c.platform&&d?.platform===void 0?{platform:c.platform}:{},...void 0!==c.target&&d?.target===void 0?{target:c.target}:{}})}:t,g=m.actions,y=m.actionLines;if(t.flags?.replayUpdate===!0&&m.updateUnsupportedMessage)return cX("INVALID_ARGS",m.updateUnsupportedMessage);if(t.flags?.replayUpdate===!0&&h.env&&Object.keys(h.env).length>0)return cX("INVALID_ARGS","replay -u does not yet preserve env directives. Temporarily remove the env lines, run replay -u, then restore them.");if(t.flags?.replayUpdate===!0&&function(e){for(let t of e){for(let e of t.positionals??[])if("string"==typeof e&&e.includes("${"))return!0;if(bn(t.flags)||bn(t.runtime))return!0}return!1}(g))return cX("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let v=function(e){let t={};if(e.builtins)for(let[r,n]of Object.entries(e.builtins))t[r]=n;for(let r of[e.fileEnv,e.shellEnv,e.cliEnv])if(r)for(let[e,n]of Object.entries(r)){if(yU(e))throw yV(e);t[e]=n}return{values:t}}({builtins:function(e){let{req:t,sessionName:r,metadata:n,resolvedPath:i}=e,a=t.flags??{},o=t.meta?.cwd??process.cwd(),s={AD_SESSION:r,AD_FILENAME:f.relative(o,i)||i},l=a.platform??n.platform;l&&(s.AD_PLATFORM=l);let u=a.target??n.target;u&&(s.AD_TARGET=u);let d=a.device;"string"==typeof d&&d.length>0&&(s.AD_DEVICE=d);let c=a.artifactsDir;return"string"==typeof c&&c.length>0&&(s.AD_ARTIFACTS=c),s}({req:w,sessionName:r,metadata:h,resolvedPath:s}),fileEnv:h.env,shellEnv:yG(yj(t.flags?.replayShellEnv)),cliEnv:yq(yB(t.flags?.replayEnv))}),I=t.flags?.replayUpdate===!0,b=0;for(let e=0;e<g.length;e+=1){let t=g[e];if(!t||"replay"===t.command)continue;let o=await I6({req:w,sessionName:r,action:t,scope:v,filePath:s,line:y[e]??0,step:e+1,tracePath:i.get(r)?.trace?.outPath,invoke:a});if(o.ok){br(o).forEach(e=>u.add(e));continue}if(!I)return bt(o,t,e,s,[...u]);let l=await v0({action:t,sessionName:r,logPath:n,sessionStore:i});if(!l)return bt(o,t,e,s,[...u]);if(g[e]=l,!(o=await I6({req:w,sessionName:r,action:l,scope:v,filePath:s,line:y[e]??0,step:e+1,tracePath:i.get(r)?.trace?.outPath,invoke:a})).ok)return bt(o,l,e,s,[...u]);br(o).forEach(e=>u.add(e)),b+=1}return I&&b>0&&function(e,t,r){let n=[];if(r){let e=r.device.kind?` kind=${r.device.kind}`:"",t=r.device.target?` target=${r.device.target}`:"";n.push(`context platform=${r.device.platform}${t} device=${iW(r.device.name)}${e} theme=unknown`)}for(let e of t){var i;n.push((i=e,i1(i,{runtimeIncludeAllPositionals:!0})))}let a=`${n.join("\n")}
90
- `,o=`${e}.tmp-${process.pid}-${Date.now()}`;l.writeFileSync(o,a),l.renameSync(o,e)}(s,g,i.get(r)),{ok:!0,data:{replayed:g.length,healed:b,session:r,artifactPaths:[...u]}}}catch(t){let e=M(t);return cX(e.code,e.message,u.size>0?{artifactPaths:[...u]}:void 0)}}function bt(e,t,r,n,i=[]){let a;if(e.ok)return e;let o=r+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${o} (${a=(t.positionals??[]).map(e=>iH(e)),[t.command,...a].join(" ")}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:n,step:o,action:t.command,positionals:t.positionals??[],artifactPaths:i}}}}function br(e){if(!e.ok||!e.data)return[];let t=[];if("string"==typeof e.data.path&&t.push(e.data.path),"string"==typeof e.data.outPath&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let r of e.data.artifacts){if(!r||"object"!=typeof r)continue;let e="string"==typeof r.localPath?r.localPath:void 0,n="string"==typeof r.path?r.path:void 0;e?t.push(e):n&&t.push(n)}return[...new Set(t.filter(e=>(function(e){try{return l.statSync(e).isFile()}catch{return!1}})(e)))]}function bn(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(bn):!!e&&"object"==typeof e&&Object.values(e).some(bn)}async function bi(e){let{req:t,sessionName:r,logPath:n,sessionStore:i,invoke:a}=e;return"replay"===t.command?await be({req:t,sessionName:r,logPath:n,sessionStore:i,invoke:a}):"test"===t.command?await y8({req:t,sessionName:r,runReplay:async({filePath:e,sessionName:r,platform:o,target:s,requestId:l,artifactsDir:u,artifactPaths:d})=>{let c=function(e){let{parentFlags:t,platform:r,target:n,artifactsDir:i}=e;return void 0===r&&void 0===n&&void 0===i?t:{...t??{},...void 0!==r?{platform:r}:{},...void 0!==n?{target:n}:{},...void 0!==i?{artifactsDir:i}:{}}}({parentFlags:t.flags,platform:o,target:s,artifactsDir:u});return await be({req:{...t,command:"replay",session:r,positionals:[e],flags:c,meta:l?{...t.meta??{},requestId:l}:t.meta},sessionName:r,logPath:n,sessionStore:i,invoke:async e=>{var t;return t=await a(e),d&&br(t).forEach(e=>d.add(e)),t}})},cleanupSession:async e=>{i.get(e)&&await gP({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:n,sessionStore:i})}}):null}let ba=ek.inventory,bo=ek.state,bs=ek.observability,bl=ek.replay;async function bu(e){let{req:t,sessionName:r,logPath:n,sessionStore:i,command:a,positionals:o,recordPositionals:s,deriveNextSession:l}=e,u=i.get(r),d=t.flags??{},c=cZ(a,u,d);if(c)return c;let p=await c1({session:u,flags:d,ensureReady:!0});if(!pd(a,p))return cX("UNSUPPORTED_OPERATION",`${a} is not supported on this device`);let f=await cF(p,a,o,t.flags?.out,{...pg(n,t.flags,u?.appBundleId,u?.trace?.outPath)});if(u){let e=l?await l(u,f,p):u;i.recordAction(e,{command:a,positionals:s??o,flags:t.flags??{},result:f??{}}),e!==u&&i.set(r,e)}return{ok:!0,data:f??{}}}async function bd(e){let{req:t,sessionName:r,logPath:n,sessionStore:i}=e,a=i.get(r),o=t.flags??{},s=cZ(eD.clipboard,a,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return cX("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await c1({session:a,flags:o,ensureReady:!0});if(!pd(eD.clipboard,u))return cX("UNSUPPORTED_OPERATION","clipboard is not supported on this device");let d=await cF(u,eD.clipboard,t.positionals??[],t.flags?.out,{...pg(n,t.flags,a?.appBundleId,a?.trace?.outPath)});return a&&i.recordAction(a,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:d??{}}),{ok:!0,data:{platform:u.platform,...d??{}}}}async function bc(e){let{req:t,sessionName:r,logPath:n,sessionStore:i,invoke:a,invokeReplayAction:o,androidAdbExecutor:s}=e;if(ba.has(t.command))return await g$({req:t,sessionName:r,sessionStore:i});if("runtime"===t.command)return await w0({req:t,sessionName:r,sessionStore:i});if(bo.has(t.command))return await gq({req:t,sessionName:r,sessionStore:i});if(t.command===eD.clipboard)return await bd({req:t,sessionName:r,logPath:n,sessionStore:i});if(t.command===eD.keyboard){let e=i.get(r),a=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==a&&"enter"!==a&&"return"!==a||"ios"!==(t.flags??{}).platform?await bu({req:t,sessionName:r,logPath:n,sessionStore:i,command:eD.keyboard,positionals:t.positionals??[]}):cX("SESSION_NOT_FOUND","iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.")}if(bs.has(t.command))return await yk({req:t,sessionName:r,sessionStore:i,androidAdbExecutor:s});if(t.command===eD.install||t.command===eD.reinstall)return await gL({req:t,command:t.command,sessionName:r,sessionStore:i,deployOps:t.command===eD.install?gE:gC});if(t.command===eq.installSource)return await wx({req:t,sessionName:r,sessionStore:i});if(t.command===eq.releaseMaterializedPaths)return await w_({req:t});if(t.command===eD.push){let e,a=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return a&&o?await bu({req:t,sessionName:r,logPath:n,sessionStore:i,command:eD.push,positionals:[a,"file"===(e=cL(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>i4.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[a,o]}):cX("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===eD.triggerAppEvent?await bu({req:t,sessionName:r,logPath:n,sessionStore:i,command:eD.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,n=r?await gw(e.device,r,e.appBundleId,gm)??e.appBundleId:e.appBundleId;return{...e,appBundleId:n}}}):t.command===eD.open?await gN({req:t,sessionName:r,logPath:n,sessionStore:i}):bl.has(t.command)?await bi({req:t,sessionName:r,logPath:n,sessionStore:i,invoke:o??a}):t.command===eD.batch?await gT(t,r,a):t.command===eD.close?await gP({req:t,sessionName:r,logPath:n,sessionStore:i}):null}let bp=new Set(["com.android.permissioncontroller","com.google.android.permissioncontroller","com.google.android.packageinstaller","com.android.packageinstaller"]),bf=new Set(["android","com.android.systemui"]),bm=/^android:id\/(?:alertTitle|message|button[123]|parentPanel|buttonPanel|contentPanel)$/i,bh=/^android:id\/button[123]$/i,bw=/(?:^|:)id\/permission_/i,bg=/\b(?:is(?:n't| not) responding|keeps stopping|has stopped|close app|app info)\b/i,by=/^(?:ok|allow|allow all|while using the app|only this time|yes|continue|save|confirm|turn on|open settings)$/i,bv=/^(?:cancel|deny|don.t allow|don’t allow|not now|no|dismiss|close|close app|later|skip)$/i;function bI(e,t){let r=t[0];if(!r)return;let n=bb(e,r.index);for(let r of t.slice(1)){let t=new Set(bb(e,r.index));for(let e=n.length-1;e>=0;e-=1)t.has(n[e])||n.splice(e,1)}return n[n.length-1]}function bb(e,t){let r=new Map(e.map(e=>[e.index,e])),n=[],i=r.get(t);for(;i;)n.push(i.index),i=void 0===i.parentIndex?void 0:r.get(i.parentIndex);return n.reverse()}function bA(e,t){let r=new Map;for(let t of e){if(void 0===t.parentIndex)continue;let e=r.get(t.parentIndex)??[];e.push(t),r.set(t.parentIndex,e)}let n=new Set([t]),i=[t];for(let e of i)for(let t of r.get(e)??[])n.has(t.index)||(n.add(t.index),i.push(t.index));return e.filter(e=>n.has(e.index))}function bS(e){let t=e.type??"",r=e.identifier??"";return!!(e.hittable||/\bbutton\b/i.test(t)||bh.test(r)||/(?:^|:)id\/permission_(?:allow|deny)/i.test(r))}function bx(e){if(!e)return"";let t=[e.label,e.value].filter(e=>"string"==typeof e&&e.trim().length>0);return t[0]?.trim()??""}async function b_(e,t,r={}){if("wait"===t)return await bN(e,r.timeoutMs??1e4);if("get"===t){var n;let t=await bD(e);return{kind:"alertStatus",platform:"android",action:"get",alert:n=t?.alert??null,...n?eJ("Alert visible"):eJ("No alert visible")}}return await bM(e,t)}async function bN(e,t){let r=Date.now(),n=await bk(e,t);if(!n)throw new D("COMMAND_FAILED","alert wait timed out");return{kind:"alertWait",platform:"android",action:"wait",alert:n.alert,waitedMs:Date.now()-r,...eJ("Alert visible")}}async function bM(e,t){var r;let n,i,a=await bk(e,2e3);if(!a)throw new D("COMMAND_FAILED","alert not found",{hint:"If a sheet is visible in snapshot but alert reports no alert, it is likely app-owned UI. Use snapshot -i and press the visible label/ref."});let o=(r=a.buttons,n="accept"===t?"accept":"dismiss",(i=r.find(e=>e.role===n))||("dismiss"===t?r.find(e=>"neutral"===e.role)??null:1===r.length?r[0]??null:null));if(o)return await sQ(e,o.x,o.y),bO(t,a.alert,o.label);if("dismiss"===t)return await s1(e),bO(t,a.alert,"Back");throw new D("COMMAND_FAILED","alert accept found an alert but no accept button",{alert:a.alert,hint:"Inspect alert get --json for visible buttons, then use press by visible label/ref if needed."})}async function bk(e,t){let r=Date.now();for(;Date.now()-r<t;){let t=await bD(e);if(t)return t;await e8(300)}return null}async function bD(e){return function(e){var t,r,n,i;let a,o=function(e){let t=e.filter(e=>{var t;let r;return r=(t=e).bundleId??"",bp.has(r)||bw.test(t.identifier??"")});if(t.length)return{nodes:t,source:"permission"};let r=function(e){let t=e.filter(e=>{var t;let r;return r=(t=e).bundleId??"",bf.has(r)&&bg.test(bx(t))});if(0===t.length)return[];let r=bI(e,t);return void 0===r?t:bA(e,r).filter(e=>e.bundleId&&bf.has(e.bundleId))}(e);return r.length?{nodes:r,source:"system-dialog"}:{nodes:function(e){var t;let r,n,i=e.filter(e=>{var t;return t=e.type??"",/(?:^|[.$])[^.]*Dialog$/i.test(t)}),a=e.filter(e=>bm.test(e.identifier??"")),o=i.length?[...i,...a]:(r=(t=a).some(e=>bh.test(e.identifier??"")),n=t.some(e=>!bh.test(e.identifier??"")),r&&n?t:[]);if(0===o.length)return[];let s=bI(e,o);return void 0===s?o:bA(e,s)}(e),source:"native-dialog"}}(e),s=o.nodes;if(0===s.length)return null;let l=function(e){let t=new Set,r=[];for(let n of e){let e=bx(n);if(!e||!n.rect||!bS(n))continue;let i=e.trim().toLowerCase();if(!i||t.has(i))continue;t.add(i);let a=tZ(n.rect);r.push({label:e,x:a.x,y:a.y,role:function(e,t){var r;let n=(r=e.identifier??"",/(?:^|:)id\/button1$/i.test(r)?"accept":/(?:^|:)id\/button2$/i.test(r)?"dismiss":/(?:^|:)id\/button3$/i.test(r)?"neutral":/(?:^|:)id\/permission_allow/i.test(r)?"accept":/(?:^|:)id\/permission_deny/i.test(r)?"dismiss":null);return n||(by.test(t.trim())?"accept":bv.test(t.trim())?"dismiss":"neutral")}(n,e)})}return r}(s),u=s.filter(e=>bx(e)&&!bS(e)),d=bx((t=u).find(e=>/(?:^|:)id\/(?:alertTitle|permission_message)$/i.test(e.identifier??"")))||bx(t[0]),c=(r=u,n=d,(a=r.map(e=>bx(e)).filter(e=>e&&e!==n)).length?[...new Set(a)].join("\n"):void 0),p=(i=s,i.find(e=>e.bundleId)?.bundleId);return{alert:{...d?{title:d}:{},...c?{message:c}:{},buttons:l.map(e=>e.label),platform:"android",source:o.source,...p?{packageName:p}:{}},buttons:l}}((await e_("snapshot_capture",async()=>await sS(e,{helperWaitForIdleTimeoutMs:0,includeHiddenContentHints:!1}),{backend:"android",purpose:"alert"})).nodes)}function bO(e,t,r){return{kind:"alertHandled",platform:"android",action:e,handled:!0,alert:t,button:r,...eJ(`Alert ${e}ed`)}}async function bP(e){var t;let{req:r,logPath:n,session:i,device:a}=e,o="accept"===(t=r.positionals?.[0])||"dismiss"===t||"wait"===t?t:"get",s=i?"frontmost-app"===i.surface?{surface:"frontmost-app"}:{bundleId:i.appBundleId,surface:i.surface}:{};if(!pd("alert",a))return cX("UNSUPPORTED_OPERATION","alert is not supported on this device");if("android"===a.platform){let t=eC(r.positionals?.[1])??1e4;return bL(e,await b_(a,o,{timeoutMs:t}))}if("macos"===a.platform){let t=async e=>await ug(e,s);return await bR(e,o,t)}let l={verbose:r.flags?.verbose,logPath:n,traceLogPath:i?.trace?.outPath,requestId:r.meta?.requestId},u=async e=>await iP(a,{command:"alert",action:e,appBundleId:i?.appBundleId},l);return await bR(e,o,u)}async function bR(e,t,r){if("wait"===t)return await bC(e,r);let n="accept"===t||"dismiss"===t?t:"get";return"accept"===n||"dismiss"===n?await bE(e,n,r):bL(e,await r("get"))}async function bC(e,t){let r=eC(e.req.positionals?.[1])??1e4,n=Date.now();for(;Date.now()-n<r;){try{return bL(e,await t("get"))}catch{}await e8(300)}return cX("COMMAND_FAILED","alert wait timed out")}async function bE(e,t,r){var n,i;let a,o,s=Date.now();for(;Date.now()-s<2e3;){try{return bL(e,await r(t))}catch(t){o=t;let e=String(t?.message??"").toLowerCase();if(!e.includes("alert not found")&&!e.includes("no alert"))break}await e8(300)}throw(n=o)instanceof D&&(i=n,(a=String(i?.message??"").toLowerCase()).includes("alert not found")||a.includes("no alert"))?new D(n.code,n.message,{...n.details??{},hint:"If the permission sheet is visible in snapshot or screenshot but alert reports no alert, take a scoped snapshot around the visible button label and use press @ref."}):n}function bL(e,t){return f8(e.sessionStore,e.session,e.req,t),{ok:!0,data:t}}async function bT(e){let{req:t,logPath:r,sessionStore:n,session:i,device:a,parsed:o}=e,{setting:s,state:l,permissionTarget:u,latitude:d,longitude:c}=o;if(!pd("settings",a))return cX("UNSUPPORTED_OPERATION","settings is not supported on this device");if("macos"===a.platform&&!tg(s))return cX("INVALID_ARGS",tD(s));let p=i?.appBundleId,f="permission"===s?[s,l,u??"",t.positionals?.[3]??"",p??""]:"location"===s&&"set"===l?[s,l,d??"",c??"",p??""]:[s,l,p??""],m=await cF(a,"settings",f,t.flags?.out,{...pg(r,t.flags,p,i?.trace?.outPath)});return f8(n,i,t,m??{setting:s,state:l}),{ok:!0,data:m??{setting:s,state:l}}}async function b$(e){var t,r;let n;if("snapshot"!==e.command||"android"!==e.device.platform)return;let i=k(e.error);if("COMMAND_FAILED"===(t=i).code&&(r=t,n=`${r.message}
91
- ${r.hint??""}`,/Android UI hierarchy dump timed out/i.test(n)||/Stock UIAutomator fallback was skipped/i.test(n)||/Android accessibility snapshots can be blocked/i.test(n)||function(e){if(!e||"object"!=typeof e)return!1;let t=String(e.errorType??""),r=String(e.message??"");return/TimeoutException/i.test(t)||/timed out/i.test(r)}(t.details?.helper)||function(e){var t;if(!e)return!1;let r=e?.timeoutMs,n=e?.cmd,i=Array.isArray(t=e?.args)?t.map(String):"string"==typeof t?t.split(/\s+/):[];return"number"==typeof r&&"adb"===n&&i.includes("uiautomator")&&i.includes("dump")}(t.details)))return{ok:!1,error:{...i,details:{...i.details??{},androidSnapshotTimeoutScreenshot:await bF(e)}}}}async function bF(e){try{var t,r,n;let i=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-android-snapshot-timeout-")),a=f.join(i,"snapshot-timeout-overlay-refs.png"),o=(t=await cF(e.device,"screenshot",[a],void 0,{...pg(e.logPath,{screenshotNoStabilize:!0},e.session?.appBundleId,e.session?.trace?.outPath),surface:e.session?.surface}),r=a,(n=t,"object"==typeof n&&null!==n&&"path"in n&&"string"==typeof n.path)?t.path:r);await d.access(o);let s=await bU(o,e.session);return eN({level:"warn",phase:"android_snapshot_timeout_screenshot_captured",data:{path:o,overlayRefCount:"overlayRefCount"in s?s.overlayRefCount:void 0,overlayRefsAnnotated:"overlayRefsAnnotated"in s?s.overlayRefsAnnotated:void 0}}),s}catch(t){let e=k(t);return eN({level:"warn",phase:"android_snapshot_timeout_screenshot_failed",data:{error:e.message}}),{captureFailed:!0,error:e.message}}}async function bU(e,t){if(!t?.snapshot)return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:"unavailable",overlayRefCount:0};try{let r=await fg({screenshotPath:e,snapshot:t.snapshot});return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:r.length>0,overlayRefCount:r.length,overlayRefSource:"session-snapshot",overlayRefs:r}}catch(r){let t=k(r);return eN({level:"warn",phase:"android_snapshot_timeout_screenshot_overlay_failed",data:{path:e,error:t.message}}),{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:"session-snapshot",overlayRefCount:0,overlayAnnotationError:t.message}}}async function bV(e){return await bq({...e,command:"snapshot",unsupportedMessage:"snapshot is not supported on this device",execute:async({runtime:e,sessionName:t,req:r,snapshotScope:n})=>{let i=await e.capture.snapshot({session:t,interactiveOnly:r.flags?.snapshotInteractiveOnly,compact:r.flags?.snapshotCompact,depth:r.flags?.snapshotDepth,scope:n,raw:r.flags?.snapshotRaw,forceFull:r.flags?.snapshotForceFull});return{data:i,record:{kind:"snapshot",nodes:i.nodes.length,truncated:i.truncated}}}})}async function bG(e){return await bq({...e,command:"diff",unsupportedMessage:"diff is not supported on this device",execute:async({runtime:e,sessionName:t,req:r,snapshotScope:n})=>{let i=await e.capture.diffSnapshot({session:t,interactiveOnly:r.flags?.snapshotInteractiveOnly,compact:r.flags?.snapshotCompact,depth:r.flags?.snapshotDepth,scope:n,raw:r.flags?.snapshotRaw});return{data:i,record:{kind:"diff",mode:"snapshot",baselineInitialized:i.baselineInitialized,summary:i.summary}}}})}async function bq(e){let{req:t,sessionName:r,logPath:n,sessionStore:i}=e,{session:a,device:o}=await f5(i,r,t.flags);if(!pd(e.command,o))return cX("UNSUPPORTED_OPERATION",e.unsupportedMessage);let s=function(e,t){let r;if(!e||!e.trim().startsWith("@"))return{ok:!0,scope:e};if(!t?.snapshot)return cX("INVALID_ARGS","Ref scope requires an existing snapshot in session.");let n=tK(e.trim());if(!n)return cX("INVALID_ARGS",`Invalid ref scope: ${e}`);for(let e of[t.snapshot,...t.snapshotScopeSource?[t.snapshotScopeSource]:[]]){let t=tJ(e.nodes,n);if(r=t?t6(t,e.nodes):void 0)break}return r?{ok:!0,scope:r}:cX("COMMAND_FAILED",`Ref ${e} not found or has no label`)}(t.flags?.snapshotScope,a);return s.ok?await f4(a,o,async()=>{var l,u;let d,c,p=function(e){let{req:t,sessionName:r,logPath:n,sessionStore:i,session:a,device:o,snapshotScope:s}=e;return tG({backend:function(e){let{req:t,logPath:r,session:n,device:i,snapshotScope:a}=e;return{platform:i.platform,captureSnapshot:async(e,o)=>{let s=await pG({device:i,session:n,flags:t.flags,outPath:o?.outPath??t.flags?.out,logPath:r,snapshotScope:a});return{snapshot:s.snapshot,analysis:s.analysis,androidSnapshot:s.androidSnapshot,freshness:s.freshness,appName:n?.appBundleId?n.appName??n.appBundleId:void 0,appBundleId:n?.appBundleId}}}}({req:t,logPath:n,session:a,device:o,snapshotScope:s}),...ms("snapshot"),sessions:pY({sessionName:r,getSession:()=>i.get(r),recordOptions:{includeSnapshot:!0},setRecord:e=>{var n;let a=function(e){if(!e.snapshot)throw new D("UNKNOWN","snapshot runtime did not produce session state");return e}(e),s=i.get(r);i.set(r,function(e){var t,r;let{current:n,sessionName:i,device:a,record:o,refScopedSnapshot:s}=e,l=(t=n,r=o,s&&r.snapshot?.nodes.length===0&&t?.snapshot!==void 0),u=l?n.snapshot:o.snapshot,d=function(e){let{session:t,sessionName:r,device:n,snapshot:i,appBundleId:a}=e;return t?{...t,snapshot:i}:{name:r,device:n,createdAt:Date.now(),appBundleId:a,snapshot:i,actions:[]}}({session:n,sessionName:i,device:a,snapshot:u,appBundleId:o.appBundleId});return d.snapshotScopeSource=function(e){let{current:t,keepCurrentSnapshot:r,refScopedSnapshot:n}=e;if(n)return r?t?.snapshotScopeSource:t?.snapshotScopeSource??t?.snapshot}({current:n,keepCurrentSnapshot:l,refScopedSnapshot:s}),o.appName&&(d.appName=o.appName),d}({current:s,sessionName:r,device:o,record:a,refScopedSnapshot:(n=t,n.flags?.snapshotScope?.trim().startsWith("@")===!0)}))}})})}({req:t,sessionName:r,logPath:n,sessionStore:i,session:a,device:o,snapshotScope:s.scope});try{c=await e.execute({runtime:p,sessionName:r,req:t,snapshotScope:s.scope})}catch(r){let t=await b$({error:r,command:e.command,logPath:n,session:a,device:o});if(!t)throw r;return t}return(d=(l={req:t,sessionName:r,sessionStore:i,result:c.record}).sessionStore.get(l.sessionName))&&l.sessionStore.recordAction(d,{command:l.req.command,positionals:l.req.positionals??[],flags:l.req.flags??{},result:"snapshot"===(u=l.result).kind?{nodes:u.nodes,truncated:u.truncated}:{mode:u.mode,baselineInitialized:u.baselineInitialized,summary:u.summary}}),{ok:!0,data:c.data}}):s}let bB=ek.snapshot,bj={snapshot:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>await bV({req:e,sessionName:t,logPath:r,sessionStore:n}),diff:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>e.positionals?.[0]!=="snapshot"?cX("INVALID_ARGS","diff currently supports only: diff snapshot"):await bG({req:e,sessionName:t,logPath:r,sessionStore:n}),wait:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>await mS({req:e,sessionName:t,logPath:r,sessionStore:n}),alert:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>{let{session:i,device:a}=await f5(n,t,e.flags);return await f4(i,a,async()=>await bP({req:e,logPath:r,sessionStore:n,session:i,device:a}))},settings:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>{let i,a,o,s=(i=e.positionals?.[0]?.toLowerCase(),a=e.positionals?.[1]?.toLowerCase(),o=e.positionals?.[2]?.toLowerCase(),i&&a&&("permission"!==i||o)&&("location"!==i||"set"!==a||e.positionals?.[2]&&e.positionals?.[3])?{ok:!0,parsed:{setting:i,state:a,permissionTarget:o,latitude:e.positionals?.[2],longitude:e.positionals?.[3]}}:cX("INVALID_ARGS",tb));if(!s.ok)return s;let{session:l,device:u}=await f5(n,t,e.flags);return await f4(l,u,async()=>await bT({req:e,logPath:r,sessionStore:n,session:l,device:u,parsed:s.parsed}))}};async function bH(e){let t=e.req.command;if(!bB.has(t))return null;let r=bj[t];return r?await r(e):cX("COMMAND_FAILED",`Snapshot command has no handler: ${t}`)}async function bW(e){let{req:t,sessionName:r,logPath:n,sessionStore:i,leaseRegistry:a,invoke:o,invokeReplayAction:s,androidAdbExecutor:l,contextFromFlags:u}=e,d=await hm({req:t,leaseRegistry:a});if(d)return d;let c=await bc({req:t,sessionName:r,logPath:n,sessionStore:i,invoke:o,invokeReplayAction:s,androidAdbExecutor:l});if(c)return c;let p=await bH({req:t,sessionName:r,logPath:n,sessionStore:i});if(p)return p;let f=await hh({req:t,sessionName:r,logPath:n,sessionStore:i,contextFromFlags:u});if(f)return f;let m=await wh({req:t,sessionName:r,sessionStore:i,logPath:n});if(m)return m;let h=await m$({req:t,sessionName:r,logPath:n,sessionStore:i,invoke:o});if(h)return h;let w=await hu({req:t,sessionName:r,logPath:n,sessionStore:i,contextFromFlags:u});return w||null}function bz(e,t){if(!t)return[];let r=[],n=e.device,i=t.platform;if(i&&!ni(n.platform,i)&&r.push({key:"platform",value:t.platform}),t.target&&t.target!==(n.target??"mobile")&&r.push({key:"target",value:t.target}),t.udid&&("ios"!==n.platform||t.udid!==n.id)&&r.push({key:"udid",value:t.udid}),t.serial&&("android"!==n.platform||t.serial!==n.id)&&r.push({key:"serial",value:t.serial}),t.device&&t.device.trim().toLowerCase()!==n.name.trim().toLowerCase()&&r.push({key:"device",value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),i=n.simulatorSetPath?.trim();("ios"!==n.platform||"simulator"!==n.kind||e!==i)&&r.push({key:"iosSimulatorDeviceSet",value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=eo(t.androidDeviceAllowlist);"android"===n.platform&&e.has(n.id)||r.push({key:"androidDeviceAllowlist",value:t.androidDeviceAllowlist})}return r}function bK(e){return`${function(e){switch(e){case"iosSimulatorDeviceSet":return"--ios-simulator-device-set";case"androidDeviceAllowlist":return"--android-device-allowlist";default:return`--${e}`}}(e.key)}=${e.value}`}let bJ=["target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist"],bX=new Set([eD.apps,eD.devices]);function bZ(e){return"string"==typeof e&&e.trim().length>0}let bY=ek.selectorValidationExempt,bQ=ek.leaseAdmissionExempt,b0=new Set(bQ);async function b1(e){let{req:t,sessionName:r,sessionStore:n}=e,i=n.get(r);if(i)return`device:${i.device.id}`;if("open"===t.command||cY(t.flags))try{let e=await oW(t.flags??{});return`device:${e.id}`}catch{}return`session:${r}`}let b2=new WeakMap;async function b3(e){var t,r;let n,i,a,{sessionStore:o,leaseRegistry:s}=e,l=(n={...(t=function(e){let t=ej(e.meta?.sessionIsolation??e.flags?.sessionIsolation),r=e.meta?.tenantId??e.flags?.tenant,n=eP(r);if(r&&!n)throw new D("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if("tenant"!==t)return e;if(!n)throw new D("INVALID_ARGS","session isolation mode tenant requires --tenant (or meta.tenantId).");let i=e.session||"default";return i.startsWith(`${n}:`)?{...e,meta:{...e.meta,tenantId:n,sessionIsolation:t}}:{...e,session:`${n}:${i}`,meta:{...e.meta,tenantId:n,sessionIsolation:t}}}(e.req)).flags??{}},((i=tR(t.command,n))||!t.flags)&&i?{...t,flags:n}:t);eN({level:"info",phase:"request_start",data:{session:l.session,command:l.command,tenant:l.meta?.tenantId,isolation:l.meta?.sessionIsolation}});let u=l.command;!function(e,t){if(bQ.has(e.command)||e.meta?.sessionIsolation!=="tenant")return;let r=hf(e);t.assertLeaseAdmission({tenantId:r.tenantId,runId:r.runId,leaseId:r.leaseId,backend:r.leaseBackend})}(l,s);let d=function(e,t){var r;let n,i=e.session||"default";if(r=e,"string"==typeof(n=r.flags?.session)&&n.trim().length>0||"default"!==i||t.has(i))return i;let a=t.toArray(),o=a[0];return void 0!==o&&1===a.length?o.name:i}(l,o),c=b0.has(u)?null:await b1({req:l,sessionName:d,sessionStore:o}),p=(r=s,(a=b2.get(r))||(a=new Map,b2.set(r,a)),a);return{req:l,command:u,sessionName:d,throwIfCanceled:()=>r_(l.meta?.requestId),runLocked:async e=>(r_(l.meta?.requestId),c)?await nr(p,c,async()=>(r_(l.meta?.requestId),await e())):await e()}}function b5(e){var t,r;let{scope:n,logPath:i,sessionStore:a,trackDownloadableArtifact:o}=e;n.throwIfCanceled();let s=a.get(n.sessionName);s&&(!function(e){var t,r;let n,i;if(!((i=(r=e).recording)&&"ios"===r.device.platform&&"ios"!==i.platform&&!1!==i.showTouches))return;let a=e.recording,o=(t=e.device.id,(n=ic.get(t))?{sessionId:n.sessionId,alive:ib(n.child.pid)}:null);if(!a.runnerSessionId){o?.alive&&(a.runnerSessionId=o.sessionId);return}if(!o?.alive){a.invalidatedReason??="iOS runner session exited during recording";return}o.sessionId!==a.runnerSessionId&&(a.invalidatedReason??="iOS runner session restarted during recording")}(s),a.set(n.sessionName,s));let l=function(e,t){let r=e.meta?.lockPolicy;if(!r)return e;let n={...e.flags??{}},i=bX.has(e.command),a=i?[]:t?bz(t,n):function(e,t,r){var n,i;let a=[];if(void 0!==e.platform&&t&&(n=e.platform,i=t,n&&i&&n!==i&&("apple"===n?!nn(i):"apple"!==i||!nn(n)))&&a.push({key:"platform",value:e.platform}),"open"===r)return a;for(let t of bJ){let r=e[t];bZ(r)&&a.push({key:t,value:r})}return a}(n,e.meta?.lockPlatform,e.command),o=e.meta?.lockPlatform;if(0===a.length){var s,l,u;return s=i,l=t,u=n,!o||l||void 0!==u.platform||s&&bJ.some(e=>bZ(u[e]))||(n.platform=o),{...e,flags:n}}if("strip"===r)return function(e,t,r,n){if(n){(function(e,t){for(let r of t)delete e[r.key]})(e,t),e.platform=n.device.platform;return}var i=e,a=r;for(let e of bJ)delete i[e];a&&(i.platform=a)}(n,a,o,t),{...e,flags:n};throw new D("INVALID_ARGS",`${e.command} cannot override session lock policy with ${a.map(bK).join(", ")}. Unset those selectors or remove the request lock policy.`)}(n.req,s),u=e=>(function(e,t,r){let n=eS();if(!t.ok){eN({level:"error",phase:"request_failed",data:{code:t.error.code,message:t.error.message}});let e=ex({force:!0})??void 0;return{ok:!1,error:k(new D(N(t.error.code),t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath}),{diagnosticId:n.diagnosticId,logPath:e})}}return eN({level:"info",phase:"request_success"}),ex(),{ok:!0,data:function(e,t,r){var n,i;let a;if(!t)return t;let o=(n=e,a=Array.isArray((i=t).artifacts)?[...i.artifacts]:[],"screenshot"!==n.command||a.some(e=>e?.field==="path")||"string"!=typeof i.path||a.push({field:"path",path:i.path,localPath:n.meta?.clientArtifactPaths?.path,fileName:f.basename(n.meta?.clientArtifactPaths?.path??i.path)}),a.filter(e=>!!(e&&"string"==typeof e.field&&"string"==typeof e.path&&"string"==typeof e.localPath&&e.localPath.length>0)));return 0===o.length?t:{...t,artifacts:o.map(t=>{let n=t.path;return{field:t.field,artifactId:r({artifactPath:n,tenantId:e.meta?.tenantId,fileName:t.fileName}),fileName:t.fileName,localPath:t.localPath}})}}(e,t.data,r)}})(l,e,o);if(s?.recording?.invalidatedReason&&"record"!==(t=n.command)&&"close"!==t)return{type:"response",response:u({ok:!1,error:{code:"COMMAND_FAILED",message:s.recording.invalidatedReason}})};!s||l.meta?.lockPolicy||(r=n.command,bY.has(r))||function(e,t){let r=bz(e,t);if(0!==r.length){var n;let t,i,a;throw new D("INVALID_ARGS",`Session "${e.name}" is bound to ${(t=(n=e).device.platform,i=n.device.name.trim(),a=n.device.id,`${t} device "${i}" (${a})`)} and cannot be used with ${r.map(bK).join(", ")}. Use a different --session name or close this session first.`)}}(s,l.flags);let d=(e,t,r)=>{let n;return{...pg(i,e,t,r,n=eS().requestId),requestId:n}};return{type:"scope",scope:{req:l,sessionName:n.sessionName,existingSession:s,finalize:u,contextFromFlags:d,handlerContextFromFlags:(e,t,r)=>({...d(e,t,r),surface:a.get(n.sessionName)?.surface})}}}async function b4(e){let{lockedScope:t,logPath:r,sessionStore:n}=e,i=n.get(t.sessionName);if(!i)return t.finalize({ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}});let a=await fY({req:t.req,session:i,sessionName:t.sessionName,logPath:r,sessionStore:n,contextFromFlags:t.contextFromFlags});return t.finalize(a)}function b8(e){eN({level:"error",phase:"request_failed",data:{error:e instanceof Error?e.message:String(e)}});let t=eS(),r=ex({force:!0})??void 0;return{ok:!1,error:k(e,{diagnosticId:t.diagnosticId,logPath:r})}}async function b6(e,t=5e3){await Promise.all(e.map(async e=>{let r;await new Promise(n=>{r=setTimeout(()=>{!function(e){e.destroyConnections?.();let t="closeAllConnections"in e?e.closeAllConnections:void 0;if("function"==typeof t)return t.call(e);let r="closeIdleConnections"in e?e.closeIdleConnections:void 0;"function"==typeof r&&r.call(e)}(e),n()},t);try{e.close(()=>n())}catch{n()}}),r&&clearTimeout(r)}))}function b9(e){l.existsSync(e)&&l.unlinkSync(e)}function b7(e){if(!l.existsSync(e))return null;try{let t=JSON.parse(l.readFileSync(e,"utf8"));if(!Number.isInteger(t.pid)||t.pid<=0)return null;return t}catch{return null}}function Ae(e){let t=b7(e);if(!t||t.pid===process.pid)try{l.existsSync(e)&&l.unlinkSync(e)}catch{}}function At(e){if(void 0===e)return;let t=Number(e);if(Number.isInteger(t))return t}function Ar(e,t){return new Promise((r,n)=>{e.once("error",n),e.listen(0,"127.0.0.1",()=>{e.off("error",n);let i=e.address();"object"==typeof i&&i?.port?r(i.port):n(new D("COMMAND_FAILED",t))})})}(async function(e={}){let t,r,n=e.env??process.env,i=e.stdout??process.stdout,a=e.stderr??process.stderr,s=e.exit??(e=>process.exit(e)),{baseDir:u,infoPath:d,lockPath:c,logPath:p,sessionsDir:h}=eQ(n.AGENT_DEVICE_STATE_DIR),w=e0(n.AGENT_DEVICE_DAEMON_SERVER_MODE);var g,y,v,I=h;if(l.existsSync(I))for(let e of l.readdirSync(I,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=f.join(I,e.name,i8);if(l.existsSync(t))try{let e=i6(l.readFileSync(t,"utf8"));if(e&&function(e){let t,r=eh(e.pid);if(!r||e.startTime&&r!==e.startTime)return!1;let n=eg(e.pid);return!!n&&!!((t=n.toLowerCase().replaceAll("\\","/")).includes("log stream")||t.includes("logcat")||t.includes("devicectl device log stream"))&&(!e.command||n===e.command)}(e))try{process.kill(e.pid,"SIGTERM")}catch{}}catch{}finally{i7(t)}}let b=new i4(h),A=new ov({maxActiveSimulatorLeases:At(n.AGENT_DEVICE_MAX_SIMULATOR_LEASES),defaultLeaseTtlMs:At(n.AGENT_DEVICE_LEASE_TTL_MS),minLeaseTtlMs:At(n.AGENT_DEVICE_LEASE_MIN_TTL_MS),maxLeaseTtlMs:At(n.AGENT_DEVICE_LEASE_MAX_TTL_MS)}),S=eH(),x=o.randomBytes(24).toString("hex"),_=eh(process.pid)??void 0,N=eM(),O=function(e){let{logPath:t,token:r,androidAdbProvider:n,appleRunnerProvider:i,appleToolProvider:a,linuxToolProvider:o,appLogProvider:s,recordingProvider:l,deviceInventoryProvider:u,trackDownloadableArtifact:d}=e,{sessionStore:c,leaseRegistry:p}=e;async function f(e){let m=!!(e.meta?.debug||e.flags?.verbose);return await eA({session:e.session,requestId:e.meta?.requestId,command:e.command,debug:m,logPath:t},async()=>{if(e.token!==r)return{ok:!1,error:k(new D("UNAUTHORIZED","Invalid token"))};try{return await oJ(u,async()=>{let u=await b3({req:e,sessionStore:c,leaseRegistry:p});return await u.runLocked(async()=>{let e=b5({scope:u,logPath:t,sessionStore:c,trackDownloadableArtifact:d});if("response"===e.type)return e.response;let m=e.scope;return await c9({req:m.req,existingSession:m.existingSession,providers:{androidAdbProvider:n,appleRunnerProvider:i,appleToolProvider:a,linuxToolProvider:o,appLogProvider:s,recordingProvider:l}},async e=>{let n=await bW({req:m.req,sessionName:m.sessionName,logPath:t,sessionStore:c,leaseRegistry:p,invoke:f,invokeReplayAction:function(e){let{parentScope:t,providerScope:r,handleRequest:n,deps:i}=e;return async e=>{var a,o;if(a=e,o=t,!(a.session===o.sessionName&&ek.replayScopedAction.has(a.command)))return await n(e);if(e.token!==i.token)return{ok:!1,error:k(new D("UNAUTHORIZED","Invalid token"))};try{let a=await b3({req:e,sessionStore:i.sessionStore,leaseRegistry:i.leaseRegistry});if(a.sessionName!==t.sessionName)return await n(e);let o=b5({scope:a,logPath:i.logPath,sessionStore:i.sessionStore,trackDownloadableArtifact:i.trackDownloadableArtifact});if("response"===o.type)return o.response;let s=o.scope,l=await bW({req:s.req,sessionName:s.sessionName,logPath:i.logPath,sessionStore:i.sessionStore,leaseRegistry:i.leaseRegistry,invoke:n,androidAdbExecutor:r.androidAdbExecutor,contextFromFlags:s.handlerContextFromFlags});if(l)return s.finalize(l);return await b4({lockedScope:s,logPath:i.logPath,sessionStore:i.sessionStore})}catch(e){return b8(e)}}}({parentScope:m,providerScope:e,handleRequest:f,deps:{logPath:t,token:r,sessionStore:c,leaseRegistry:p,trackDownloadableArtifact:d}}),androidAdbExecutor:e.androidAdbExecutor,contextFromFlags:m.handlerContextFromFlags});return n?m.finalize(n):await b4({lockedScope:m,logPath:t,sessionStore:c})})})})}catch(e){return b8(e)}})}return f}({logPath:p,token:x,sessionStore:b,leaseRegistry:A,trackDownloadableArtifact:aH}),P=async e=>{await eA({command:"daemon",session:"daemon",logPath:p,debug:!0},async()=>{eN({level:"error",phase:"daemon_fatal",data:{error:e instanceof Error?e.message:String(e)}}),ex({force:!0})})},R=async e=>{let t=gO(e,e.name).catch(t=>{a.write(`Daemon session teardown error (${e.name}): ${t instanceof Error?t.message:String(t)}
92
- `)});await Promise.race([t,e8(5e3).then(()=>{a.write(`Daemon session teardown timed out (${e.name}).
93
- `)})]),b.writeSessionLog(e),b.delete(e.name)},C=async()=>{let e=b.toArray();await Promise.all(e.map(R))},E=async()=>{let e,t,r=[];if("http"!==w){let t,n,i=(t=new Set,(n=m.createServer(e=>{t.add(e),e.on("close",()=>t.delete(e));let r="",n=0,i=new Set,a=!1,o=()=>{if(!a&&0!==n){for(let e of(a=!0,i))rI(e);eN({level:"warn",phase:"request_client_disconnected",data:{inFlightRequests:n}}),(async()=>{try{let e=Date.now()+15e3;for(;n>0&&Date.now()<e&&(await iv(),!(n<=0));)await e8(200)}catch(e){eN({level:"error",phase:"request_client_disconnect_abort_failed",data:{message:e instanceof Error?e.message:String(e),inFlightRequests:n}})}})()}};e.setEncoding("utf8"),e.on("close",o),e.on("error",o),e.on("data",async t=>{let a=eR(r,t);for(let t of(r=a.buffer,a.lines)){let r,a;n+=1;let o=!1;try{let n=JSON.parse(t);if(o=eU(n),a=ry(n.meta?.requestId,"socket"),n.meta={...n.meta,requestId:a},i.add(a),rv(a),rA(a))throw rx();r=await a3(o?t=>{e.destroyed||e.write(e5(t))}:void 0,async()=>await O(n))}catch(e){r={ok:!1,error:k(e)}}finally{n-=1,a&&(i.delete(a),rb(a))}e.destroyed||e.write(o?eF(r):`${JSON.stringify(r)}
94
- `)}})})).destroyConnections=()=>{for(let e of t)e.destroy();t.clear()},n);r.push(i),e=await Ar(i,"Failed to bind socket server")}if("socket"!==w){let e=await oc({handleRequest:O,token:x});r.push(e),t=await Ar(e,"Failed to bind HTTP server")}return{servers:r,socketPort:e,httpPort:t}};if(!function(e,t,r){l.existsSync(e)||l.mkdirSync(e,{recursive:!0});let n=JSON.stringify(r,null,2),i=()=>{try{return l.writeFileSync(t,n,{flag:"wx",mode:384}),!0}catch(e){if("EEXIST"===e.code)return!1;throw e}};if(i())return!0;let a=b7(t);if(a?.pid&&a.pid!==process.pid&&eI(a.pid,a.processStartTime))return!1;try{l.unlinkSync(t)}catch{}return i()}(u,c,{pid:process.pid,version:S,startedAt:Date.now(),processStartTime:_}))return a.write("Daemon lock is held by another process; exiting.\n"),s(0),null;let L=[];try{let e,n=await E();L=n.servers,t=n.socketPort,r=n.httpPort,g=t,y=r,v={socketPort:g,httpPort:y,token:x,version:S,codeSignature:N,processStartTime:_},l.existsSync(u)||l.mkdirSync(u,{recursive:!0}),l.writeFileSync(p,""),e=v.socketPort&&v.httpPort?"dual":v.httpPort?"http":"socket",l.writeFileSync(d,JSON.stringify({port:v.socketPort,httpPort:v.httpPort,transport:e,token:v.token,pid:process.pid,version:v.version,codeSignature:v.codeSignature,processStartTime:v.processStartTime,stateDir:u},null,2),{mode:384}),g&&i.write(`AGENT_DEVICE_DAEMON_PORT=${g}
95
- `),y&&i.write(`AGENT_DEVICE_DAEMON_HTTP_PORT=${y}
96
- `)}catch(t){let e=M(t);for(let t of(a.write(`Daemon error: ${e.message}
97
- `),L))try{t.close(()=>{})}catch{}return b9(d),Ae(c),s(1),null}let T=!1,$=async(e={})=>{T||(T=!0,e.cause&&await P(e.cause),await b6(L),await C(),await iI(),b9(d),Ae(c),s(e.exitCode??0))};return!1!==e.registerProcessHandlers&&(process.on("SIGINT",()=>{$()}),process.on("SIGTERM",()=>{$()}),process.on("SIGHUP",()=>{$()}),process.on("uncaughtException",e=>{let t=e instanceof D?e:M(e);a.write(`Daemon error: ${t.message}
98
- `),$({exitCode:1,cause:e})}),process.on("unhandledRejection",e=>{let t=e instanceof Error?e:Error(String(e)),r=t instanceof D?t:M(t);a.write(`Daemon error: ${r.message}
99
- `),$({exitCode:1,cause:t})})),{httpPort:r,shutdown:$,socketPort:t,token:x}})().catch(e=>{let t=M(e);process.stderr.write(`Daemon error: ${t.message}
100
- `),process.exit(1)});
1
+ import"../2415.js";