agent-device 0.10.0 → 0.10.2

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 (76) hide show
  1. package/README.md +4 -607
  2. package/dist/src/331.js +3 -3
  3. package/dist/src/425.js +1 -0
  4. package/dist/src/bin.js +28 -28
  5. package/dist/src/core/dispatch.d.ts +2 -0
  6. package/dist/src/core/session-surface.d.ts +3 -0
  7. package/dist/src/core/settings-contract.d.ts +2 -1
  8. package/dist/src/daemon/android-system-dialog.d.ts +11 -0
  9. package/dist/src/daemon/app-log-ios.d.ts +2 -1
  10. package/dist/src/daemon/app-log-process.d.ts +1 -1
  11. package/dist/src/daemon/app-log.d.ts +1 -1
  12. package/dist/src/daemon/context.d.ts +2 -0
  13. package/dist/src/daemon/handlers/interaction-common.d.ts +30 -1
  14. package/dist/src/daemon/handlers/interaction-read.d.ts +14 -0
  15. package/dist/src/daemon/handlers/interaction-touch.d.ts +45 -0
  16. package/dist/src/daemon/handlers/interaction.d.ts +2 -0
  17. package/dist/src/daemon/handlers/record-trace-android.d.ts +18 -0
  18. package/dist/src/daemon/handlers/record-trace-ios.d.ts +52 -0
  19. package/dist/src/daemon/handlers/record-trace-recording.d.ts +32 -0
  20. package/dist/src/daemon/handlers/record-trace.d.ts +2 -7
  21. package/dist/src/daemon/handlers/snapshot-capture.d.ts +11 -4
  22. package/dist/src/daemon/record-trace-errors.d.ts +6 -0
  23. package/dist/src/daemon/recording-gestures.d.ts +3 -0
  24. package/dist/src/daemon/recording-telemetry.d.ts +20 -0
  25. package/dist/src/daemon/recording-timing.d.ts +24 -0
  26. package/dist/src/daemon/request-router.d.ts +6 -0
  27. package/dist/src/daemon/script-utils.d.ts +1 -0
  28. package/dist/src/daemon/snapshot-processing.d.ts +1 -0
  29. package/dist/src/daemon/touch-reference-frame.d.ts +7 -0
  30. package/dist/src/daemon/types.d.ts +65 -11
  31. package/dist/src/daemon.js +62 -36
  32. package/dist/src/platforms/android/index.d.ts +1 -1
  33. package/dist/src/platforms/android/input-actions.d.ts +5 -0
  34. package/dist/src/platforms/android/settings.d.ts +1 -1
  35. package/dist/src/platforms/ios/apps.d.ts +1 -1
  36. package/dist/src/platforms/ios/macos-helper.d.ts +69 -0
  37. package/dist/src/platforms/ios/runner-client.d.ts +2 -2
  38. package/dist/src/platforms/ios/runner-session.d.ts +5 -0
  39. package/dist/src/platforms/ios/runner-xctestrun.d.ts +3 -1
  40. package/dist/src/recording/overlay.d.ts +10 -0
  41. package/dist/src/utils/command-schema.d.ts +2 -0
  42. package/dist/src/utils/interactors.d.ts +8 -8
  43. package/dist/src/utils/snapshot-lines.d.ts +5 -2
  44. package/dist/src/utils/snapshot.d.ts +8 -1
  45. package/dist/src/utils/text-surface.d.ts +19 -0
  46. package/dist/src/utils/video.d.ts +9 -0
  47. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +196 -51
  48. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +133 -0
  49. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +1 -1
  50. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +33 -1
  51. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +4 -6
  52. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +1 -0
  53. package/ios-runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +571 -0
  54. package/ios-runner/AgentDeviceRunner/RecordingScripts/recording-trim.swift +140 -0
  55. package/macos-helper/Package.swift +18 -0
  56. package/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift +543 -0
  57. package/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +545 -0
  58. package/package.json +4 -1
  59. package/skills/agent-device/SKILL.md +25 -334
  60. package/skills/agent-device/references/bootstrap-install.md +167 -0
  61. package/skills/agent-device/references/coordinate-system.md +24 -4
  62. package/skills/agent-device/references/debugging.md +115 -0
  63. package/skills/agent-device/references/exploration.md +193 -0
  64. package/skills/agent-device/references/macos-desktop.md +55 -57
  65. package/skills/agent-device/references/remote-tenancy.md +56 -47
  66. package/skills/agent-device/references/verification.md +103 -0
  67. package/dist/src/274.js +0 -1
  68. package/dist/src/daemon/handlers/interaction-fill.d.ts +0 -3
  69. package/dist/src/daemon/handlers/interaction-press.d.ts +0 -3
  70. package/skills/agent-device/references/batching.md +0 -79
  71. package/skills/agent-device/references/logs-and-debug.md +0 -113
  72. package/skills/agent-device/references/perf-metrics.md +0 -53
  73. package/skills/agent-device/references/permissions.md +0 -70
  74. package/skills/agent-device/references/session-management.md +0 -101
  75. package/skills/agent-device/references/snapshot-refs.md +0 -102
  76. package/skills/agent-device/references/video-recording.md +0 -41
@@ -1,42 +1,68 @@
1
- let e,t;import r from"node:dns/promises";import a from"node:fs/promises";import{node_path as i,readProcessCommand as n,normalizeTenantId as o,isAgentDeviceDaemonProcess as s,runCmdDetached as l,runCmdBackground as d,node_crypto as u,runCmd as c,spawn as p,asAppError as f,expandUserHomePath as m,pathToFileURL as h,AppError as w,external_node_url_URL as g,whichCmd as I,fileURLToPath as A,runCmdStreaming as v,normalizeError as y,resolveSessionIsolationMode as b,resolveUserPath as S,readVersion as N,getDiagnosticsMeta as _,runCmdSync as D,withDiagnosticTimer as E,findProjectRoot as k,emitDiagnostic as L,promises as O,isProcessAlive as x,readProcessStartTime as M,withDiagnosticsScope as C,node_fs as R,flushDiagnosticsToSessionFile as P,node_os as T,node_net as $,resolveDaemonServerMode as F,resolveDaemonPaths as U,node_http as V}from"./331.js";import{buildSnapshotDisplayLines as G,DEFAULT_BATCH_MAX_STEPS as B,formatRole as j,validateAndNormalizeBatchSteps as q,SETTINGS_INVALID_ARGS_MESSAGE as H,displayLabel as W,TextDecoder as z,formatSnapshotLine as J}from"./274.js";let K=X(process.env.AGENT_DEVICE_RETRY_LOGS);function X(e){return["1","true","yes","on"].includes((e??"").toLowerCase())}let Z=2e4,Y=12e4,Q=1e4;class ee{startedAtMs;expiresAtMs;constructor(e,t){this.startedAtMs=e,this.expiresAtMs=e+Math.max(0,t)}static fromTimeoutMs(e,t=Date.now()){return new ee(t,e)}remainingMs(e=Date.now()){return Math.max(0,this.expiresAtMs-e)}elapsedMs(e=Date.now()){return Math.max(0,e-this.startedAtMs)}isExpired(e=Date.now()){return 0>=this.remainingMs(e)}}async function et(e,t={},r={}){let a,i={maxAttempts:t.maxAttempts??3,baseDelayMs:t.baseDelayMs??200,maxDelayMs:t.maxDelayMs??2e3,jitter:t.jitter??.2,shouldRetry:t.shouldRetry};for(let t=1;t<=i.maxAttempts;t+=1){if(r.signal?.aborted)throw new w("COMMAND_FAILED","request canceled",{reason:"request_canceled"});if(r.deadline?.isExpired()&&t>1)break;try{let a=await e({attempt:t,maxAttempts:i.maxAttempts,deadline:r.deadline});return r.onEvent?.({phase:r.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:r.deadline?.elapsedMs(),remainingMs:r.deadline?.remainingMs()}),ea({phase:r.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:r.deadline?.elapsedMs(),remainingMs:r.deadline?.remainingMs()}),a}catch(d){a=d;let e=r.classifyReason?.(d),n={phase:r.phase,event:"attempt_failed",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:r.deadline?.elapsedMs(),remainingMs:r.deadline?.remainingMs(),reason:e};if(r.onEvent?.(n),ea(n),t>=i.maxAttempts||i.shouldRetry&&!i.shouldRetry(d,t))break;let o=function(e,t,r,a){let i=Math.min(t,e*2**(a-1));return Math.max(0,i+i*r*(2*Math.random()-1))}(i.baseDelayMs,i.maxDelayMs,i.jitter,t),s=r.deadline?Math.min(o,r.deadline.remainingMs()):o;if(s<=0)break;let l={phase:r.phase,event:"retry_scheduled",attempt:t,maxAttempts:i.maxAttempts,delayMs:s,elapsedMs:r.deadline?.elapsedMs(),remainingMs:r.deadline?.remainingMs(),reason:e};r.onEvent?.(l),ea(l),await function(e,t){return new Promise(r=>{let a;if(t?.aborted)return void r();let i=!1,n=()=>{i||(i=!0,t&&a&&t.removeEventListener("abort",a),r())},o=setTimeout(n,e);a=()=>{clearTimeout(o),n()},t&&t.addEventListener("abort",a,{once:!0})})}(s,r.signal)}}let n={phase:r.phase,event:"exhausted",attempt:i.maxAttempts,maxAttempts:i.maxAttempts,elapsedMs:r.deadline?.elapsedMs(),remainingMs:r.deadline?.remainingMs(),reason:r.classifyReason?.(a)};if(r.onEvent?.(n),ea(n),a)throw a;throw new w("COMMAND_FAILED","retry failed")}async function er(e,t={}){return et(()=>e(),{maxAttempts:t.attempts,baseDelayMs:t.baseDelayMs,maxDelayMs:t.maxDelayMs,jitter:t.jitter,shouldRetry:t.shouldRetry})}function ea(e){L({level:"attempt_failed"===e.event||"exhausted"===e.event?"warn":"debug",phase:"retry",data:{...e}}),K&&process.stderr.write(`[agent-device][retry] ${JSON.stringify(e)}
2
- `)}let ei=new Set,en=new Map,eo="request_canceled",es="request canceled";function el(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",a=Math.random().toString(36).slice(2,10);return`req:${r}:${process.pid}:${Date.now()}:${a}`}function ed(e){if(!e)return;let t=new AbortController;en.set(e,t),ei.has(e)&&t.abort()}function eu(e){e&&(ei.add(e),en.get(e)?.abort())}function ec(e){e&&(ei.delete(e),en.delete(e))}function ep(e){return!!e&&ei.has(e)}function ef(e){if(e)return en.get(e)?.signal}function em(){return new w("COMMAND_FAILED",es,{reason:eo})}function eh(e){return e instanceof w&&"COMMAND_FAILED"===e.code&&(e.details?.reason===eo||e.message===es)}function ew(e){let t=e.error?f(e.error):null,r=e.context?.platform,a=e.context?.phase;if(t?.code==="TOOL_MISSING")return"android"===r?"ADB_TRANSPORT_UNAVAILABLE":"IOS_TOOL_MISSING";let i=t?.details??{},n="string"==typeof i.message?i.message:void 0,o="string"==typeof i.stdout?i.stdout:void 0,s="string"==typeof i.stderr?i.stderr:void 0,l=i.boot&&"object"==typeof i.boot?i.boot:null,d=i.bootstatus&&"object"==typeof i.bootstatus?i.bootstatus:null,u=[e.message,t?.message,e.stdout,e.stderr,n,o,s,"string"==typeof l?.stdout?l.stdout:void 0,"string"==typeof l?.stderr?l.stderr:void 0,"string"==typeof d?.stdout?d.stdout:void 0,"string"==typeof d?.stderr?d.stderr:void 0].filter(Boolean).join("\n").toLowerCase();return"ios"===r&&(u.includes("runner did not accept connection")||"connect"===a&&(u.includes("timed out")||u.includes("timeout")||u.includes("econnrefused")||u.includes("connection refused")||u.includes("fetch failed")||u.includes("socket hang up")))?"IOS_RUNNER_CONNECT_TIMEOUT":"ios"===r&&"boot"===a&&(u.includes("timed out")||u.includes("timeout"))?"IOS_BOOT_TIMEOUT":"android"===r&&"boot"===a&&(u.includes("timed out")||u.includes("timeout"))?"ANDROID_BOOT_TIMEOUT":u.includes("resource temporarily unavailable")||u.includes("killed: 9")||u.includes("cannot allocate memory")||u.includes("system is low on memory")?"CI_RESOURCE_STARVATION_SUSPECTED":"android"===r&&(u.includes("device not found")||u.includes("no devices")||u.includes("device offline")||u.includes("offline")||u.includes("unauthorized")||u.includes("not authorized")||u.includes("unable to locate device")||u.includes("invalid device"))?"ADB_TRANSPORT_UNAVAILABLE":t?.code==="COMMAND_FAILED"||u.length>0?"BOOT_COMMAND_FAILED":"UNKNOWN"}function eg(e){switch(e){case"IOS_BOOT_TIMEOUT":return"Retry simulator boot and inspect simctl bootstatus logs; in CI consider increasing AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS.";case"IOS_RUNNER_CONNECT_TIMEOUT":return"Retry runner startup, inspect xcodebuild logs, and verify simulator responsiveness before command execution.";case"ANDROID_BOOT_TIMEOUT":return"Retry emulator startup and verify sys.boot_completed reaches 1; consider increasing startup budget in CI.";case"ADB_TRANSPORT_UNAVAILABLE":return"Check adb server/device transport (adb devices -l), restart adb, and ensure the target device is online and authorized.";case"CI_RESOURCE_STARVATION_SUSPECTED":return"CI machine may be resource constrained; reduce parallel jobs or use a larger runner.";case"IOS_TOOL_MISSING":return"Xcode command-line tools are missing or not in PATH; run xcode-select --install and verify xcrun works.";case"BOOT_COMMAND_FAILED":return"Inspect command stderr/stdout for the failing boot phase and retry after environment validation.";default:return"Retry once and inspect verbose logs for the failing phase."}}function eI(e){return!(e instanceof w)||"COMMAND_FAILED"!==e.code||!String(e.message??"").toLowerCase().includes("xcodebuild exited early")}function eA(e){let{port:t,endpoints:r,logPath:a,lastError:i}=e,n="Runner did not accept connection";return new w("COMMAND_FAILED",n,{port:t,endpoints:r,logPath:a,lastError:i?String(i):void 0,reason:ew({error:i,message:n,context:{platform:"ios",phase:"connect"}}),hint:eg("IOS_RUNNER_CONNECT_TIMEOUT")})}async function ev(e){var t,r;let a,{session:i,port:n,logPath:o}=e,s=await i.testPromise,l="Runner did not accept connection (xcodebuild exited early)",d=ew({message:l,stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});return new w("COMMAND_FAILED",l,{port:n,logPath:o,xcodebuild:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr},reason:d,hint:(t=s.stdout,r=s.stderr,(a=`${l}
1
+ let e,t,r,a;import i from"node:dns/promises";import n from"node:fs/promises";import{node_path as o,readProcessCommand as s,normalizeTenantId as l,existsSync as d,runCmdDetached as u,runCmdBackground as c,isAgentDeviceDaemonProcess as p,node_crypto as f,runCmd as m,spawn as h,asAppError as w,expandUserHomePath as g,pathToFileURL as v,AppError as I,external_node_url_URL as A,whichCmd as y,fileURLToPath as b,runCmdStreaming as S,createHash as _,normalizeError as N,resolveSessionIsolationMode as D,resolveUserPath as E,readVersion as k,getDiagnosticsMeta as M,runCmdSync as x,withDiagnosticTimer as O,findProjectRoot as L,emitDiagnostic as C,promises as P,isProcessAlive as R,readProcessStartTime as T,withDiagnosticsScope as $,node_fs as F,flushDiagnosticsToSessionFile as U,node_os as V,node_net as G,resolveDaemonServerMode as B,resolveDaemonPaths as j,node_http as q}from"./331.js";import{formatSnapshotLine as H,DEFAULT_BATCH_MAX_STEPS as W,formatRole as z,validateAndNormalizeBatchSteps as J,extractReadableText as X,SETTINGS_INVALID_ARGS_MESSAGE as K,parseSessionSurface as Y,TextDecoder as Z,displayLabel as Q,buildSnapshotDisplayLines as ee}from"./425.js";let et=er(process.env.AGENT_DEVICE_RETRY_LOGS);function er(e){return["1","true","yes","on"].includes((e??"").toLowerCase())}let ea=2e4,ei=12e4,en=1e4;class eo{startedAtMs;expiresAtMs;constructor(e,t){this.startedAtMs=e,this.expiresAtMs=e+Math.max(0,t)}static fromTimeoutMs(e,t=Date.now()){return new eo(t,e)}remainingMs(e=Date.now()){return Math.max(0,this.expiresAtMs-e)}elapsedMs(e=Date.now()){return Math.max(0,e-this.startedAtMs)}isExpired(e=Date.now()){return 0>=this.remainingMs(e)}}async function es(e,t={},r={}){let a,i={maxAttempts:t.maxAttempts??3,baseDelayMs:t.baseDelayMs??200,maxDelayMs:t.maxDelayMs??2e3,jitter:t.jitter??.2,shouldRetry:t.shouldRetry};for(let t=1;t<=i.maxAttempts;t+=1){if(r.signal?.aborted)throw new I("COMMAND_FAILED","request canceled",{reason:"request_canceled"});if(r.deadline?.isExpired()&&t>1)break;try{let a=await e({attempt:t,maxAttempts:i.maxAttempts,deadline:r.deadline});return r.onEvent?.({phase:r.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:r.deadline?.elapsedMs(),remainingMs:r.deadline?.remainingMs()}),ed({phase:r.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:r.deadline?.elapsedMs(),remainingMs:r.deadline?.remainingMs()}),a}catch(d){a=d;let e=r.classifyReason?.(d),n={phase:r.phase,event:"attempt_failed",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:r.deadline?.elapsedMs(),remainingMs:r.deadline?.remainingMs(),reason:e};if(r.onEvent?.(n),ed(n),t>=i.maxAttempts||i.shouldRetry&&!i.shouldRetry(d,t))break;let o=function(e,t,r,a){let i=Math.min(t,e*2**(a-1));return Math.max(0,i+i*r*(2*Math.random()-1))}(i.baseDelayMs,i.maxDelayMs,i.jitter,t),s=r.deadline?Math.min(o,r.deadline.remainingMs()):o;if(s<=0)break;let l={phase:r.phase,event:"retry_scheduled",attempt:t,maxAttempts:i.maxAttempts,delayMs:s,elapsedMs:r.deadline?.elapsedMs(),remainingMs:r.deadline?.remainingMs(),reason:e};r.onEvent?.(l),ed(l),await function(e,t){return new Promise(r=>{let a;if(t?.aborted)return void r();let i=!1,n=()=>{i||(i=!0,t&&a&&t.removeEventListener("abort",a),r())},o=setTimeout(n,e);a=()=>{clearTimeout(o),n()},t&&t.addEventListener("abort",a,{once:!0})})}(s,r.signal)}}let n={phase:r.phase,event:"exhausted",attempt:i.maxAttempts,maxAttempts:i.maxAttempts,elapsedMs:r.deadline?.elapsedMs(),remainingMs:r.deadline?.remainingMs(),reason:r.classifyReason?.(a)};if(r.onEvent?.(n),ed(n),a)throw a;throw new I("COMMAND_FAILED","retry failed")}async function el(e,t={}){return es(()=>e(),{maxAttempts:t.attempts,baseDelayMs:t.baseDelayMs,maxDelayMs:t.maxDelayMs,jitter:t.jitter,shouldRetry:t.shouldRetry})}function ed(e){C({level:"attempt_failed"===e.event||"exhausted"===e.event?"warn":"debug",phase:"retry",data:{...e}}),et&&process.stderr.write(`[agent-device][retry] ${JSON.stringify(e)}
2
+ `)}let eu=new Set,ec=new Map,ep="request_canceled",ef="request canceled";function em(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",a=Math.random().toString(36).slice(2,10);return`req:${r}:${process.pid}:${Date.now()}:${a}`}function eh(e){if(!e)return;let t=new AbortController;ec.set(e,t),eu.has(e)&&t.abort()}function ew(e){e&&(eu.add(e),ec.get(e)?.abort())}function eg(e){e&&(eu.delete(e),ec.delete(e))}function ev(e){return!!e&&eu.has(e)}function eI(e){if(e)return ec.get(e)?.signal}function eA(){return new I("COMMAND_FAILED",ef,{reason:ep})}function ey(e){return e instanceof I&&"COMMAND_FAILED"===e.code&&(e.details?.reason===ep||e.message===ef)}function eb(e){let t=e.error?w(e.error):null,r=e.context?.platform,a=e.context?.phase;if(t?.code==="TOOL_MISSING")return"android"===r?"ADB_TRANSPORT_UNAVAILABLE":"IOS_TOOL_MISSING";let i=t?.details??{},n="string"==typeof i.message?i.message:void 0,o="string"==typeof i.stdout?i.stdout:void 0,s="string"==typeof i.stderr?i.stderr:void 0,l=i.boot&&"object"==typeof i.boot?i.boot:null,d=i.bootstatus&&"object"==typeof i.bootstatus?i.bootstatus:null,u=[e.message,t?.message,e.stdout,e.stderr,n,o,s,"string"==typeof l?.stdout?l.stdout:void 0,"string"==typeof l?.stderr?l.stderr:void 0,"string"==typeof d?.stdout?d.stdout:void 0,"string"==typeof d?.stderr?d.stderr:void 0].filter(Boolean).join("\n").toLowerCase();return"ios"===r&&(u.includes("runner did not accept connection")||"connect"===a&&(u.includes("timed out")||u.includes("timeout")||u.includes("econnrefused")||u.includes("connection refused")||u.includes("fetch failed")||u.includes("socket hang up")))?"IOS_RUNNER_CONNECT_TIMEOUT":"ios"===r&&"boot"===a&&(u.includes("timed out")||u.includes("timeout"))?"IOS_BOOT_TIMEOUT":"android"===r&&"boot"===a&&(u.includes("timed out")||u.includes("timeout"))?"ANDROID_BOOT_TIMEOUT":u.includes("resource temporarily unavailable")||u.includes("killed: 9")||u.includes("cannot allocate memory")||u.includes("system is low on memory")?"CI_RESOURCE_STARVATION_SUSPECTED":"android"===r&&(u.includes("device not found")||u.includes("no devices")||u.includes("device offline")||u.includes("offline")||u.includes("unauthorized")||u.includes("not authorized")||u.includes("unable to locate device")||u.includes("invalid device"))?"ADB_TRANSPORT_UNAVAILABLE":t?.code==="COMMAND_FAILED"||u.length>0?"BOOT_COMMAND_FAILED":"UNKNOWN"}function eS(e){switch(e){case"IOS_BOOT_TIMEOUT":return"Retry simulator boot and inspect simctl bootstatus logs; in CI consider increasing AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS.";case"IOS_RUNNER_CONNECT_TIMEOUT":return"Retry runner startup, inspect xcodebuild logs, and verify simulator responsiveness before command execution.";case"ANDROID_BOOT_TIMEOUT":return"Retry emulator startup and verify sys.boot_completed reaches 1; consider increasing startup budget in CI.";case"ADB_TRANSPORT_UNAVAILABLE":return"Check adb server/device transport (adb devices -l), restart adb, and ensure the target device is online and authorized.";case"CI_RESOURCE_STARVATION_SUSPECTED":return"CI machine may be resource constrained; reduce parallel jobs or use a larger runner.";case"IOS_TOOL_MISSING":return"Xcode command-line tools are missing or not in PATH; run xcode-select --install and verify xcrun works.";case"BOOT_COMMAND_FAILED":return"Inspect command stderr/stdout for the failing boot phase and retry after environment validation.";default:return"Retry once and inspect verbose logs for the failing phase."}}function e_(e){return!(e instanceof I)||"COMMAND_FAILED"!==e.code||!String(e.message??"").toLowerCase().includes("xcodebuild exited early")}function eN(e){let{port:t,endpoints:r,logPath:a,lastError:i}=e,n="Runner did not accept connection";return new I("COMMAND_FAILED",n,{port:t,endpoints:r,logPath:a,lastError:i?String(i):void 0,reason:eb({error:i,message:n,context:{platform:"ios",phase:"connect"}}),hint:eS("IOS_RUNNER_CONNECT_TIMEOUT")})}async function eD(e){var t,r;let a,{session:i,port:n,logPath:o}=e,s=await i.testPromise,l="Runner did not accept connection (xcodebuild exited early)",d=eb({message:l,stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});return new I("COMMAND_FAILED",l,{port:n,logPath:o,xcodebuild:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr},reason:d,hint:(t=s.stdout,r=s.stderr,(a=`${l}
3
3
  ${t}
4
- ${r}`.toLowerCase()).includes("device is busy")&&a.includes("connecting")?"Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.":eg("IOS_RUNNER_CONNECT_TIMEOUT"))})}function ey(e){if(ep(e))throw em()}function eb(e,t,r){if(!e)return t;let a=Number(e);return Number.isFinite(a)?Math.max(r,Math.floor(a)):t}let eS=["AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET","IOS_SIMULATOR_DEVICE_SET"],eN=["AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST","ANDROID_DEVICE_ALLOWLIST"];function e_(e){return e?.trim()||void 0}function eD(e,t){for(let r of e){let e=e_(t[r]);if(e)return e}}function eE(e,t=process.env){return e_(e)??eD(eS,t)}function ek(e){return new Set(e.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean))}function eL(e,t=process.env){let r=e_(e)??eD(eN,t);if(r)return ek(r)}function eO(e,t={}){let r=eE(t.simulatorSetPath);return r?["simctl","--set",r,...e]:["simctl",...e]}function ex(e,t){return"ios"!==e.platform||"simulator"!==e.kind?["simctl",...t]:eO(t,{simulatorSetPath:e.simulatorSetPath})}let eM=eb(process.env.AGENT_DEVICE_RUNNER_STARTUP_TIMEOUT_MS,45e3,5e3),eC=eb(process.env.AGENT_DEVICE_RUNNER_COMMAND_TIMEOUT_MS,45e3,1e3),eR=eb(process.env.AGENT_DEVICE_RUNNER_CONNECT_ATTEMPT_INTERVAL_MS,250,50),eP=eb(process.env.AGENT_DEVICE_RUNNER_CONNECT_RETRY_BASE_DELAY_MS,300,10),eT=eb(process.env.AGENT_DEVICE_RUNNER_CONNECT_RETRY_MAX_DELAY_MS,2e3,10),e$=eb(process.env.AGENT_DEVICE_RUNNER_CONNECT_REQUEST_TIMEOUT_MS,2e4,250),eF=eb(process.env.AGENT_DEVICE_IOS_DEVICE_INFO_TIMEOUT_MS,1e4,500),eU=eb(process.env.AGENT_DEVICE_RUNNER_DESTINATION_TIMEOUT_SECONDS,20,5);async function eV(e,t,r,a,i=eM,n,o){let s=ee.fromTimeoutMs(i),l=await eG(e,t,s.remainingMs()),d=null,u=Math.max(1,Math.ceil(i/eR));try{return await et(async({deadline:s})=>{if(s?.isExpired())throw new w("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:i});if(n&&null!==n.child.exitCode&&void 0!==n.child.exitCode)throw await ev({session:n,port:t,logPath:a});for(let a of("device"===e.kind&&(l=await eG(e,t,s?.remainingMs())),l))try{let e=s?.remainingMs()??i;if(e<=0)throw new w("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:i});return await eB(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},Math.min(e$,e),o)}catch(e){if(o?.aborted||eh(e))throw em();d=e}throw new w("COMMAND_FAILED","Runner endpoint probe failed",{port:t,endpoints:l,lastError:d?String(d):void 0})},{maxAttempts:u,baseDelayMs:eP,maxDelayMs:eT,jitter:.2,shouldRetry:eI},{deadline:s,phase:"ios_runner_connect",signal:o})}catch(e){if(o?.aborted||eh(e))throw em();d||(d=e)}if(o?.aborted)throw em();if("simulator"===e.kind){let i=s.remainingMs();if(i<=0)throw eA({port:t,endpoints:l,logPath:a,lastError:d});let n=await eq(e,t,r,i);return new Response(n.body,{status:n.status})}throw eA({port:t,endpoints:l,logPath:a,lastError:d})}async function eG(e,t,r){let a=[`http://127.0.0.1:${t}/command`];if("device"!==e.kind)return a;let i=await ej(e.id,r);return i&&a.unshift(`http://[${i}]:${t}/command`),a}async function eB(e,t,r,a){let i,n=new AbortController,o=setTimeout(()=>n.abort(),r);a&&(a.aborted?(clearTimeout(o),n.abort()):(i=()=>n.abort(),a.addEventListener("abort",i,{once:!0})));try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(o),i&&a&&a.removeEventListener("abort",i)}}async function ej(e,t){if("number"==typeof t&&t<=0)return null;let r="number"==typeof t?Math.max(1,Math.min(eF,t)):eF,a=i.join(T.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(r/1e3)),i=await c("xcrun",["devicectl","device","info","details","--device",e,"--json-output",a,"--timeout",String(t)],{allowFailure:!0,timeoutMs:r});if(0!==i.exitCode||!R.existsSync(a))return null;let n=JSON.parse(R.readFileSync(a,"utf8"));if(n.info?.outcome&&"success"!==n.info.outcome)return null;let o=(n.result?.connectionProperties?.tunnelIPAddress??n.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return o&&o.length>0?o:null}catch{return null}finally{ez(a)}}async function eq(e,t,r,a){let i=JSON.stringify(r),n=ex(e,["spawn",e.id,"/usr/bin/curl","-s","-X","POST","-H","Content-Type: application/json","--data",i,`http://127.0.0.1:${t}/command`]),o=await c("xcrun",n,{allowFailure:!0,timeoutMs:a}),s=o.stdout;if(0!==o.exitCode){let e=ew({message:"Runner did not accept connection (simctl spawn)",stdout:o.stdout,stderr:o.stderr,context:{platform:"ios",phase:"connect"}});throw new w("COMMAND_FAILED","Runner did not accept connection (simctl spawn)",{port:t,stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode,reason:e,hint:eg(e)})}return{status:200,body:s}}async function eH(){return await new Promise((e,t)=>{let r=$.createServer();r.listen(0,"127.0.0.1",()=>{let a=r.address();r.close(),"object"==typeof a&&a?.port?e(a.port):t(new w("COMMAND_FAILED","Failed to allocate port"))}),r.on("error",t)})}function eW(e,t,r,a){t&&R.appendFileSync(t,e),r&&R.appendFileSync(r,e),a&&process.stderr.write(e)}function ez(e){try{R.existsSync(e)&&R.unlinkSync(e)}catch{}}async function eJ(e,t,r){let a=(e.get(t)??Promise.resolve()).catch(()=>{}).then(r);return e.set(t,a),a.finally(()=>{e.get(t)===a&&e.delete(t)})}function eK(e){return"apple"===e||"ios"===e||"macos"===e}function eX(e,t){return!t||("apple"===t?eK(e):e===t)}function eZ(e){let{simulatorSetPath:t,platform:r,target:a}=e;if(t&&"macos"!==r&&"desktop"!==a)return t}async function eY(e,t,r={}){let a=e,i=e=>e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim();if(t.platform&&(a=a.filter(e=>eX(e.platform,t.platform))),t.target&&(a=a.filter(e=>(e.target??"mobile")===t.target)),t.udid){let e=a.find(e=>e.id===t.udid&&eK(e.platform));if(!e)throw new w("DEVICE_NOT_FOUND",`No Apple device with UDID ${t.udid}`);return e}if(t.serial){let e=a.find(e=>e.id===t.serial&&"android"===e.platform);if(!e)throw new w("DEVICE_NOT_FOUND",`No Android device with serial ${t.serial}`);return e}if(t.deviceName){let e=i(t.deviceName),r=a.find(t=>i(t.name)===e);if(!r)throw new w("DEVICE_NOT_FOUND",`No device named ${t.deviceName}`);return r}if(1===a.length)return a[0];if(0===a.length){var n;let e=r.simulatorSetPath;if(e&&(!(n=t.platform)||"apple"===n||"ios"===n))throw new w("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:
5
- xcrun simctl --set "${e}" create "iPhone 16" com.apple.CoreSimulator.SimDeviceType.iPhone-16 com.apple.CoreSimulator.SimRuntime.iOS-18-0`,selector:t});throw new w("DEVICE_NOT_FOUND","No devices found",{selector:t})}let o=a.filter(e=>"device"!==e.kind);o.length>0&&(a=o);let s=a.filter(e=>e.booted);return 1===s.length?s[0]:s[0]??a[0]}let eQ=new Set(["RUNNER_PRODUCT_MISSING","RUNNER_PRODUCT_REPAIR_FAILED"]);async function e0(e,t,r){if("macos"!==e.platform)return;if(0===t.length)throw new w("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",xctestrunPath:r});let a=Array.from(new Set(t)).sort((e,t)=>t.length-e.length);for(let e of a)if(!R.existsSync(e))throw new w("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",productPath:e,xctestrunPath:r});for(let e of a)if(0!==D("codesign",["--verify","--deep","--strict",e],{allowFailure:!0}).exitCode){await c("codesign",["--remove-signature",e],{allowFailure:!0});try{await c("codesign",["--force","--sign","-",e])}catch(a){let t=a instanceof w?a:new w("COMMAND_FAILED",String(a));throw new w("COMMAND_FAILED","Failed to repair macOS runner product signature",{reason:"RUNNER_PRODUCT_REPAIR_FAILED",productPath:e,xctestrunPath:r,error:t.message,details:t.details})}}}let e1=i.join(T.homedir(),".agent-device","ios-runner"),e2=new Map,e3=new Set;function e4(e){return e?.trim()??""}function e8(e=process.env){return e4(e.AGENT_DEVICE_IOS_BUNDLE_ID)||e4(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||"com.callstack.agentdevice.runner"}function e6(e=process.env){let t=e4(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID);return t||`${e8(e)}.uitests`}let e5=function(e=process.env){let t=e8(e),r=e6(e);return Array.from(new Set([e4(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${r}.xctrunner`,t].filter(e=>e.length>0)))}(process.env),e9={findProjectRoot:function(){let e=i.dirname(A(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=i.join(t,"package.json");if(R.existsSync(e))return t;t=i.dirname(t)}return e},findXctestrun:function(e){if(!R.existsSync(e))return null;let t=[],r=[e];for(;r.length>0;){let e=r.pop();for(let a of R.readdirSync(e,{withFileTypes:!0})){let n=i.join(e,a.name);if(a.isDirectory()){r.push(n);continue}if(a.isFile()&&a.name.endsWith(".xctestrun"))try{let e=R.statSync(n);t.push({path:n,mtimeMs:e.mtimeMs})}catch{}}}return 0===t.length?null:(t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path??null)},xctestrunReferencesProjectRoot:function(e,t){try{let r=R.readFileSync(e,"utf8"),a=new Set([t]);try{a.add(R.realpathSync(t))}catch{}for(let e of a)if(r.includes(e))return!0;return!1}catch{return!1}},resolveExistingXctestrunProductPaths:function(e){let t=function(e){let t=function(e){try{let t=D("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==t.exitCode||!t.stdout.trim())return null;return JSON.parse(t.stdout)}catch{return null}}(e);if(t){var r,a=t;let e=new Set,i=t=>{if(t&&"object"==typeof t)for(let r of function(e){let t=new Set(["ProductPaths","DependentProductPaths","TestHostPath","TestBundlePath","UITargetAppPath"]),r=new Set;for(let[a,i]of Object.entries(e))if(t.has(a)){if("string"==typeof i){r.add(i);continue}if(Array.isArray(i))for(let e of i)"string"==typeof e&&r.add(e)}return Array.from(r)}(t))e.add(r)};i(a);let n=a.TestConfigurations;if(Array.isArray(n))for(let e of n){if(!e||"object"!=typeof e)continue;let t=e.TestTargets;if(Array.isArray(t))for(let e of t)i(e)}for(let e of Object.values(a))e&&"object"==typeof e&&"TestBundlePath"in e&&i(e);return Array.from(e)}if("darwin"===process.platform)return null;try{return r=R.readFileSync(e,"utf8"),Array.from(new Set([...["ProductPaths","DependentProductPaths"].flatMap(e=>(function(e,t){let r,a=RegExp(`<key>${t}</key>\\s*<array>([\\s\\S]*?)</array>`,"g"),i=/<string>([\s\S]*?)<\/string>/g,n=new Set;for(;null!==(r=a.exec(e));){let e,t=r[1]??"";for(;null!==(e=i.exec(t));){let t=e[1]?.trim();t&&n.add(t)}}return Array.from(n)})(r,e)),...["TestHostPath","TestBundlePath","UITargetAppPath"].flatMap(e=>(function(e,t){let r,a=RegExp(`<key>${t}</key>\\s*<string>([\\s\\S]*?)</string>`,"g"),i=new Set;for(;null!==(r=a.exec(e));){let e=r[1]?.trim();e&&i.add(e)}return Array.from(i)})(r,e))]))}catch{return null}}(e);if(!t||0===t.length)return null;let r=i.dirname(e),a=new Set,n=new Set,o=[];for(let e of t){if(e.startsWith("__TESTROOT__/")){let t=e.slice(13),o=i.join(r,t);if(!R.existsSync(o))return null;a.add(o);let s=function(e){let t=/\.app(?:\/|$)/.exec(e);return t&&void 0!==t.index?e.slice(0,t.index+4):null}(t);s&&n.add(i.join(r,s));continue}e.startsWith("__TESTHOST__/")&&o.push(e.slice(13))}for(let e of o){let t=Array.from(n).find(t=>R.existsSync(i.join(t,e)));if(!t)return null;a.add(i.join(t,e))}return Array.from(a)},repairRunnerProductsIfNeeded:e0,assertSafeDerivedCleanup:function(e,t=process.env){if(t.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()&&!function(e=process.env){return X(e.AGENT_DEVICE_IOS_ALLOW_OVERRIDE_DERIVED_CLEAN)}(t))throw new w("COMMAND_FAILED","Refusing to clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH automatically",{derivedPath:e,hint:"Unset AGENT_DEVICE_IOS_CLEAN_DERIVED, or set AGENT_DEVICE_IOS_ALLOW_OVERRIDE_DERIVED_CLEAN=1 if you trust this path."})},cleanRunnerDerivedArtifacts:function(e){try{if(!R.existsSync(e))return;if("derived"!==i.basename(e))return void R.rmSync(e,{recursive:!0,force:!0});for(let r of R.readdirSync(e,{withFileTypes:!0})){var t;t=r.name,te.has(t)&&R.rmSync(i.join(e,r.name),{recursive:!0,force:!0})}}catch{}},buildRunnerXctestrun:tr};async function e7(e,t,r=e9){var a;let n,o=(a=e,(n=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim())?i.resolve(n):"macos"===a.platform?i.join(e1,"derived","macos"):"simulator"===a.kind?i.join(e1,"derived"):i.join(e1,"derived",a.kind)),s=r.findProjectRoot();return await eJ(e2,o,async()=>{X(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)&&(to("clean","forced_clean",{derived:o}),r.assertSafeDerivedCleanup(o),r.cleanRunnerDerivedArtifacts(o));let a=function(e){let t=e.findXctestrun(e.derived);if(!t)return{reason:"missing_xctestrun",xctestrunPath:null};let r=e.resolveExistingXctestrunProductPaths(t);return r?e.xctestrunReferencesProjectRoot(t,e.projectRoot)?{reason:"reuse_ready",xctestrunPath:t,productPaths:r}:{reason:"project_root_mismatch",xctestrunPath:t,productPaths:r}:{reason:"missing_products",xctestrunPath:t,productPaths:[]}}({derived:o,projectRoot:s,findXctestrun:r.findXctestrun,xctestrunReferencesProjectRoot:r.xctestrunReferencesProjectRoot,resolveExistingXctestrunProductPaths:r.resolveExistingXctestrunProductPaths});if("reuse_ready"!==a.reason&&to("rebuild",a.reason,{derived:o,xctestrunPath:a.xctestrunPath}),"reuse_ready"===a.reason)try{return await r.repairRunnerProductsIfNeeded(e,a.productPaths,a.xctestrunPath),to("reuse","reuse_ready",{derived:o,xctestrunPath:a.xctestrunPath}),a.xctestrunPath}catch(e){if(!function(e){if(!(e instanceof w))return!1;let t=e.details&&"object"==typeof e.details?e.details.reason:void 0;return"string"==typeof t&&eQ.has(t)}(e))throw e;to("rebuild","repair_failed",{derived:o,xctestrunPath:a.xctestrunPath})}a.xctestrunPath&&(r.assertSafeDerivedCleanup(o),r.cleanRunnerDerivedArtifacts(o));let n=i.join(s,"ios-runner","AgentDeviceRunner","AgentDeviceRunner.xcodeproj");if(!R.existsSync(n))throw new w("COMMAND_FAILED","iOS runner project not found",{projectPath:n});await r.buildRunnerXctestrun(e,n,o,t);let l=r.findXctestrun(o);if(!l)throw new w("COMMAND_FAILED","Failed to locate .xctestrun after build");let d=r.resolveExistingXctestrunProductPaths(l);if(!d)throw new w("COMMAND_FAILED","Runner build is missing expected products",{xctestrunPath:l});return await r.repairRunnerProductsIfNeeded(e,d,l),to("build","built_new",{derived:o,xctestrunPath:l}),l})}let te=new Set(["Build","BuildCache.noindex","Index.noindex","Logs","ModuleCache.noindex","SDKStatCaches.noindex","SourcePackages","TextBasedInstallAPI","info.plist"]);async function tt(e,t,r){let a,n=i.dirname(e),o=r.replace(/[^a-zA-Z0-9._-]/g,"_"),s=i.join(n,`AgentDeviceRunner.env.${o}.json`),l=i.join(n,`AgentDeviceRunner.env.${o}.xctestrun`),d=await c("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==d.exitCode||!d.stdout.trim())throw new w("COMMAND_FAILED","Failed to read xctestrun plist",{xctestrunPath:e,stderr:d.stderr});try{a=JSON.parse(d.stdout)}catch(t){throw new w("COMMAND_FAILED","Failed to parse xctestrun JSON",{xctestrunPath:e,error:String(t)})}let u=e=>{e.EnvironmentVariables={...e.EnvironmentVariables??{},...t},e.UITestEnvironmentVariables={...e.UITestEnvironmentVariables??{},...t},e.UITargetAppEnvironmentVariables={...e.UITargetAppEnvironmentVariables??{},...t},e.TestingEnvironmentVariables={...e.TestingEnvironmentVariables??{},...t}},p=a.TestConfigurations;if(Array.isArray(p))for(let e of p){if(!e||"object"!=typeof e)continue;let t=e.TestTargets;if(Array.isArray(t))for(let e of t)e&&"object"==typeof e&&u(e)}for(let[e,t]of Object.entries(a))t&&"object"==typeof t&&t.TestBundlePath&&(u(t),a[e]=t);R.writeFileSync(s,JSON.stringify(a,null,2));let f=await c("plutil",["-convert","xml1","-o",l,s],{allowFailure:!0});if(0!==f.exitCode)throw new w("COMMAND_FAILED","Failed to write xctestrun plist",{tmpXctestrunPath:l,stderr:f.stderr});return{xctestrunPath:l,jsonPath:s}}async function tr(e,t,r,a){let i=function(e=process.env){let t=e8(e),r=e6(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${r}`]}(process.env),n=function(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 a=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||"",i=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||"",n=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||"",o=["CODE_SIGN_STYLE=Automatic"];return a&&o.push(`DEVELOPMENT_TEAM=${a}`),i&&o.push(`CODE_SIGN_IDENTITY=${i}`),n&&o.push(`PROVISIONING_PROFILE_SPECIFIER=${n}`),o}(process.env,"device"===e.kind,e.platform),o="device"===e.kind?["-allowProvisioningUpdates"]:[];try{var s;let l;await v("xcodebuild",["build-for-testing","-project",t,"-scheme","AgentDeviceRunner","-parallel-testing-enabled","NO",tn(e),"1","-destination",(s=e,l=ta(s),"macOS"===l?`platform=macOS,arch=${ti()}`:"simulator"===s.kind?`platform=${l} Simulator,id=${s.id}`:`generic/platform=${l}`),"-derivedDataPath",r,"COMPILER_INDEX_STORE_ENABLE=NO","ENABLE_CODE_COVERAGE=NO",...i,...o,...n],{detached:!0,onSpawn:e=>{e3.add(e),e.on("close",()=>{e3.delete(e)})},onStdoutChunk:e=>{eW(e,a.logPath,a.traceLogPath,a.verbose)},onStderrChunk:e=>{eW(e,a.logPath,a.traceLogPath,a.verbose)}})}catch(n){let e,t,r=n instanceof w?n:new w("COMMAND_FAILED",String(n)),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);throw new w("COMMAND_FAILED","xcodebuild build-for-testing failed",{error:r.message,details:r.details,logPath:a.logPath,hint:i})}}function ta(e){var t;if("ios"!==e.platform&&"macos"!==e.platform)throw new w("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 ti(){return"arm64"===process.arch?"arm64":"x86_64"}function tn(e){return"macos"===e.platform||"device"===e.kind?"-maximum-concurrent-test-device-destinations":"-maximum-concurrent-test-simulator-destinations"}function to(e,t,r){L({level:"rebuild"===e?"warn":"info",phase:"runner_xctestrun_cache",data:{action:e,reason:t,...r}})}let ts=new Map,tl=new Map;async function td(e,t){return await eJ(tl,e.id,async()=>{var r,a;let i,n=ts.get(e.id);if(n){if((r=n.child.pid)&&x(r))return n;await tc(e.id,n)}await ("simulator"!==(a=e).kind?Promise.resolve():tw(a));let o=await e7(e,t),s=await eH(),{xctestrunPath:l,jsonPath:u}=await tt(o,{AGENT_DEVICE_RUNNER_PORT:String(s)},`session-${e.id}-${s}`),{child:c,wait:p}=d("xcodebuild",["test-without-building","-only-testing","AgentDeviceRunnerUITests/RunnerTests/testCommand","-parallel-testing-enabled","NO","-test-timeouts-enabled","NO","-collect-test-diagnostics","never",tn(e),"1","-destination-timeout",String(eU),"-xctestrun",l,"-destination","macOS"===(i=ta(e))?`platform=macOS,arch=${ti()}`:"simulator"===e.kind?`platform=${i} Simulator,id=${e.id}`:`platform=${i},id=${e.id}`],{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(s)},detached:!0});c.stdout?.on("data",e=>{eW(e,t.logPath,t.traceLogPath,t.verbose)}),c.stderr?.on("data",e=>{eW(e,t.logPath,t.traceLogPath,t.verbose)});let f={device:e,deviceId:e.id,port:s,xctestrunPath:l,jsonPath:u,testPromise:p,child:c,ready:!1};return ts.set(e.id,f),f})}async function tu(e){await eJ(tl,e.deviceId,async()=>{await tc(e.deviceId,e)})}async function tc(e,t){let r=t??ts.get(e);if(r){try{await eV(r.device,r.port,{command:"shutdown"},void 0,15e3)}catch{await th(r.child.pid,"SIGTERM")}try{await Promise.race([r.testPromise,new Promise(e=>setTimeout(e,1e4))])}catch{}await th(r.child.pid,"SIGKILL"),ez(r.xctestrunPath),ez(r.jsonPath),ts.get(e)===r&&ts.delete(e)}}async function tp(e){await eJ(tl,e,async()=>{await tc(e)})}async function tf(){let e=Array.from(ts.values()),t=Array.from(e3);await Promise.allSettled(e.map(async e=>{await th(e.child.pid,"SIGINT")})),await Promise.allSettled(t.map(async e=>{await th(e.pid,"SIGINT")})),await Promise.allSettled(e.map(async e=>{await th(e.child.pid,"SIGTERM")})),await Promise.allSettled(t.map(async e=>{await th(e.pid,"SIGTERM")})),await Promise.allSettled(e.map(async e=>{await th(e.child.pid,"SIGKILL")})),await Promise.allSettled(t.map(async e=>{await th(e.pid,"SIGKILL"),e3.delete(e)}))}async function tm(){await tf();let e=Array.from(ts.keys());await Promise.allSettled(e.map(async e=>{await tp(e)}));let t=Array.from(e3);await Promise.allSettled(t.map(async e=>{try{await th(e.pid,"SIGTERM"),await th(e.pid,"SIGKILL")}finally{e3.delete(e)}}))}async function th(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 c("pkill",[`-${r}`,"-P",String(e)],{allowFailure:!0})}catch{}}async function tw(e){await c("xcrun",ex(e,["bootstatus",e.id,"-b"]),{timeoutMs:eM})}async function tg(e,t,r,a,i,n){let o=await eV(e,t.port,r,a,i,t,n);return await tI(o,t,a)}async function tI(e,t,r){let a=await e.text(),i={};try{i=JSON.parse(a)}catch{throw new w("COMMAND_FAILED","Invalid runner response",{text:a})}if(!i.ok)throw new w("COMMAND_FAILED",i.error?.message??"Runner error",{runner:i,xcodebuild:{exitCode:1,stdout:"",stderr:""},logPath:r});return t.ready=!0,i.data??{}}async function tA(e,t,r={}){var a;if("ios"!==e.platform&&"macos"!==e.platform)throw new w("UNSUPPORTED_PLATFORM",`Unsupported platform for iOS runner: ${e.platform}`);if("simulator"!==e.kind&&"device"!==e.kind)throw new w("UNSUPPORTED_OPERATION",`Unsupported iOS device kind for runner: ${e.kind}`);return(ey(r.requestId),"snapshot"===(a=t.command)||"screenshot"===a||"findText"===a||"alert"===a)?er(()=>(ey(r.requestId),tv(e,t,r)),{shouldRetry:e=>{ey(r.requestId);if(!(e instanceof w)||"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"))}}):tv(e,t,r)}async function tv(e,t,r={}){let a;ey(r.requestId);let i=ef(r.requestId);try{let n=(a=await td(e,r)).ready?eC:eM;return await tg(e,a,t,r.logPath,n,i)}catch(o){let n=o instanceof w?o:new w("COMMAND_FAILED",String(o));if("COMMAND_FAILED"===n.code&&"string"==typeof n.message&&n.message.includes("Runner did not accept connection")&&eI(n)&&a?.ready){ey(r.requestId),a?await tu(a):await tp(e.id),a=await td(e,r);let n=await eV(a.device,a.port,t,r.logPath,eM,void 0,i);return await tI(n,a,r.logPath)}throw o}}function ty(e){let t=e.result?.text;if("string"==typeof t&&t.trim().length>0)return t;let r=e.positionals??[];return 0===r.length?"":r[0].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 tb(e){let t=new Set,r=[];for(let a of e)t.has(a)||(t.add(a),r.push(a));return r}let tS=/^-?\d+(\.\d+)?$/,tN=new Map([["--count","count"],["--interval-ms","intervalMs"],["--hold-ms","holdMs"],["--jitter-px","jitterPx"]]),t_=new Map([["--count","count"],["--pause-ms","pauseMs"]]);function tD(e){return"click"===e||"press"===e}function tE(e){let t=e.trim();return t.startsWith("@")||tS.test(t)?t:JSON.stringify(t)}function tk(e){let t=e.trim();return/\s/.test(t)?JSON.stringify(t):t}function tL(e,t){let r=t.flags??{};if(tD(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}"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))}function tO(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",tk(t.metroHost)),"number"==typeof t.metroPort&&e.push("--metro-port",String(t.metroPort)),"string"==typeof t.bundleUrl&&t.bundleUrl.length>0&&e.push("--bundle-url",tk(t.bundleUrl)),"string"==typeof t.launchUrl&&t.launchUrl.length>0&&e.push("--launch-url",tk(t.launchUrl)))}function tx(e,t){let r=[],a={},i=tD(e)?tN:"swipe"===e?t_:void 0;for(let n=0;n<t.length;n+=1){let o=t[n];if(tD(e)&&"--double-tap"===o){a.doubleTap=!0;continue}if(tD(e)&&"--button"===o&&n+1<t.length){let e=t[n+1];("primary"===e||"secondary"===e||"middle"===e)&&(a.clickButton=e),n+=1;continue}let s=i?.get(o);if(s&&n+1<t.length){let e=tC(t[n+1]);null!==e&&(a[s]=e),n+=1;continue}if("swipe"===e&&"--pattern"===o&&n+1<t.length){let e=t[n+1];("one-way"===e||"ping-pong"===e)&&(a.pattern=e),n+=1;continue}r.push(o)}return{positionals:r,flags:a}}function tM(e){let t=[],r={};for(let a=0;a<e.length;a+=1){let i=e[a];if("--platform"===i&&a+1<e.length){let t=e[a+1];("ios"===t||"android"===t)&&(r.platform=t),a+=1;continue}if("--metro-host"===i&&a+1<e.length){r.metroHost=e[a+1],a+=1;continue}if("--metro-port"===i&&a+1<e.length){let t=tC(e[a+1]);null!==t&&(r.metroPort=t),a+=1;continue}if("--bundle-url"===i&&a+1<e.length){r.bundleUrl=e[a+1],a+=1;continue}if("--launch-url"===i&&a+1<e.length){r.launchUrl=e[a+1],a+=1;continue}t.push(i)}return{positionals:t,flags:r}}function tC(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function tR(e,t){for(let r of t.positionals??[])e.push(tE(r));t.flags?.relaunch&&e.push("--relaunch"),tO(e,t.runtime)}class tP{sessions=new Map;runtimeHints=new Map;sessionsDir;constructor(e){this.sessionsDir=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=tP.expandHome(t.flags.saveScript))),e.actions.push({ts:Date.now(),command:t.command,positionals:t.positionals,runtime:t.runtime,flags:function(e){if(!e)return{};let{platform:t,device:r,udid:a,serial:i,out:n,verbose:o,metroHost:s,metroPort:l,bundleUrl:d,launchUrl:u,snapshotInteractiveOnly:c,snapshotCompact:p,snapshotDepth:f,snapshotScope:m,snapshotRaw:h,relaunch:w,saveScript:g,noRecord:I,count:A,intervalMs:v,holdMs:y,jitterPx:b,doubleTap:S,clickButton:N,pauseMs:_,pattern:D}=e;return{platform:t,device:r,udid:a,serial:i,out:n,verbose:o,metroHost:s,metroPort:l,bundleUrl:d,launchUrl:u,snapshotInteractiveOnly:c,snapshotCompact:p,snapshotDepth:f,snapshotScope:m,snapshotRaw:h,relaunch:w,saveScript:g,noRecord:I,count:A,intervalMs:v,holdMs:y,jitterPx:b,doubleTap:S,clickButton:N,pauseMs:_,pattern:D}}(t.flags),result:t.result}),L({level:"debug",phase:"record_action",data:{command:t.command,session:e.name}}))}writeSessionLog(e){try{if(!e.recordSession)return;let t=this.resolveScriptPath(e),r=i.dirname(t);R.existsSync(r)||R.mkdirSync(r,{recursive:!0});let a=function(e,t){let r=[],a=e.device.name.replace(/"/g,'\\"'),i=e.device.kind?` kind=${e.device.kind}`:"";for(let n of(r.push(`context platform=${e.device.platform} device="${a}"${i} theme=unknown`),t))n.flags?.noRecord||r.push(function(e){let t=[e.command];if(tD(e.command)){let r=e.positionals?.[0];if(r){if(r.startsWith("@")){t.push(tE(r));let a=e.result?.refLabel;return"string"==typeof a&&a.trim().length>0&&t.push(tE(a)),tL(t,e),t.join(" ")}if(1===e.positionals.length)return t.push(tE(r)),tL(t,e),t.join(" ")}}if("fill"===e.command){let r=e.positionals?.[0];if(r&&r.startsWith("@")){t.push(tE(r));let a=e.result?.refLabel,i=e.positionals.slice(1).join(" ");return"string"==typeof a&&a.trim().length>0&&t.push(tE(a)),i&&t.push(tE(i)),t.join(" ")}}if("get"===e.command){let r=e.positionals?.[0],a=e.positionals?.[1];if(r&&a){if(t.push(tE(r)),t.push(tE(a)),a.startsWith("@")){let r=e.result?.refLabel;"string"==typeof r&&r.trim().length>0&&t.push(tE(r))}return t.join(" ")}}if("snapshot"===e.command)return e.flags?.snapshotInteractiveOnly&&t.push("-i"),e.flags?.snapshotCompact&&t.push("-c"),"number"==typeof e.flags?.snapshotDepth&&t.push("-d",String(e.flags.snapshotDepth)),e.flags?.snapshotScope&&t.push("-s",tE(e.flags.snapshotScope)),e.flags?.snapshotRaw&&t.push("--raw"),t.join(" ");if("open"===e.command)return tR(t,e),t.join(" ");if("runtime"===e.command){let r=e.positionals?.[0];return r&&t.push(tk(r)),tO(t,e.flags),t.join(" ")}for(let r of e.positionals??[])t.push(tE(r));return tL(t,e),t.join(" ")}(n));return`${r.join("\n")}
7
- `}(e,this.buildOptimizedActions(e));R.writeFileSync(t,a)}catch{}}defaultTracePath(e){let t=tP.safeSessionName(e.name),r=new Date().toISOString().replace(/[:.]/g,"-");return i.join(this.sessionsDir,`${t}-${r}.trace.log`)}resolveAppLogPath(e){return i.join(this.sessionsDir,tP.safeSessionName(e),"app.log")}resolveAppLogPidPath(e){return i.join(this.sessionsDir,tP.safeSessionName(e),"app-log.pid")}static safeSessionName(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}static expandHome(e,t){return S(e,{cwd:t})}resolveScriptPath(e){if(e.saveScriptPath)return tP.expandHome(e.saveScriptPath);R.existsSync(this.sessionsDir)||R.mkdirSync(this.sessionsDir,{recursive:!0});let t=tP.safeSessionName(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,"-");return i.join(this.sessionsDir,`${t}-${r}.ad`)}buildOptimizedActions(e){let t=[];for(let r of e.actions){if("snapshot"===r.command)continue;let a=Array.isArray(r.result?.selectorChain)&&r.result?.selectorChain.every(e=>"string"==typeof e)?r.result.selectorChain:[];if(a.length>0&&(tD(r.command)||"fill"===r.command||"get"===r.command)){let e=a.join(" || ");if(tD(r.command)){t.push({...r,positionals:[e]});continue}if("fill"===r.command){let a=ty(r);if(a.length>0){t.push({...r,positionals:[e,a]});continue}}if("get"===r.command){let a=r.positionals?.[0];if("text"===a||"attrs"===a){t.push({...r,positionals:[a,e]});continue}}}if(tD(r.command)||"fill"===r.command||"get"===r.command){let a=r.result?.refLabel;"string"==typeof a&&a.trim().length>0&&t.push({ts:r.ts,command:"snapshot",positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotCompact:!0,snapshotScope:a.trim()},result:{scope:a.trim()}})}t.push(r)}return t}}function tT(e,t){if(!e)return;let r=i.dirname(e);R.existsSync(r)||R.mkdirSync(r,{recursive:!0});let a={pid:t,startTime:M(t)??void 0,command:n(t)??void 0};R.writeFileSync(e,`${JSON.stringify(a)}
8
- `)}function t$(e){if(e&&R.existsSync(e))try{R.unlinkSync(e)}catch{}}async function tF(e,t=2e3){await Promise.race([e.then(()=>void 0).catch(()=>void 0),new Promise(e=>setTimeout(e,t))])}async function tU(e){await new Promise(t=>setTimeout(t,e))}function tV(e,t){let r=t.includeTokens?.filter(e=>e.length>0)??[],a="",i=a=>{(!(r.length>0)||r.some(e=>a.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}(a,t.redactionPatterns))};return{onChunk:e=>{let t=`${a}${e}`.split("\n");for(let e of(a=t.pop()??"",t))i(`${e}
9
- `)},flush:()=>{a&&(i(a),a="")}}}function tG(e,t,r){let a=e.stdout,i=e.stderr;return a&&i?(a.setEncoding("utf8"),i.setEncoding("utf8"),a.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(a=>{e.on("close",e=>{r.writer.flush(),r.endStreamOnClose&&t.end(),a({stdout:"",stderr:"",exitCode:e??1})})})):Promise.resolve({stdout:"",stderr:"missing stdio pipes",exitCode:1})}async function tB(e,t){let r=(await c("adb",["-s",e,"shell","pidof",t],{allowFailure:!0})).stdout.trim().split(/\s+/)[0];return r&&/^\d+$/.test(r)?r:null}async function tj(e,t,r,a,i){let n,o,s="active",l=!1,d=(async()=>{try{for(;!l;){let d=await tB(e,t);if(!d){await tU(1e3);continue}let u=p("adb",["-s",e,"logcat","-v","time","--pid",d],{stdio:["ignore","pipe","pipe"]});n=u;let c=tV(r,{redactionPatterns:a});o=tG(u,r,{endStreamOnClose:!1,writer:c}),"number"==typeof u.pid&&tT(i,u.pid);let f=await o;if(t$(i),n=void 0,o=void 0,l)break;0!==f.exitCode&&(s="failed"),await tU(500)}return{stdout:"",stderr:"",exitCode:0}}finally{r.end(),t$(i)}})();return{backend:"android",getState:()=>s,startedAt:Date.now(),wait:d,stop:async()=>{l=!0,n&&!n.killed&&n.kill("SIGINT"),o&&await tF(o),n&&!n.killed&&n.kill("SIGKILL"),await tF(d),t$(i)}}}async function tq(e,t,r,a){let i="active",n=p("log",["stream","--style","compact","--predicate",`subsystem == "${e}" OR processImagePath ENDSWITH[c] "/${e}" OR senderImagePath ENDSWITH[c] "/${e}" OR eventMessage CONTAINS[c] "${e}"`],{stdio:["ignore","pipe","pipe"]}),o=tV(t,{redactionPatterns:r});"number"==typeof n.pid&&tT(a,n.pid);let s=tG(n,t,{endStreamOnClose:!0,writer:o}).then(e=>(0!==e.exitCode&&(i="failed"),t$(a),e));return{backend:"ios-simulator",getState:()=>i,startedAt:Date.now(),wait:s,stop:async()=>{n.killed||n.kill("SIGINT"),await tF(s),n.killed||n.kill("SIGKILL"),await tF(s),t$(a)}}}async function tH(e,t,r,a){let i="active",n=p("xcrun",["devicectl","device","log","stream","--device",e],{stdio:["ignore","pipe","pipe"]}),o=tV(t,{redactionPatterns:r});"number"==typeof n.pid&&tT(a,n.pid);let s=tG(n,t,{endStreamOnClose:!0,writer:o}).then(e=>(0!==e.exitCode&&(i="failed"),t$(a),e));return{backend:"ios-device",getState:()=>i,startedAt:Date.now(),wait:s,stop:async()=>{n.killed||n.kill("SIGINT"),await tF(s),n.killed||n.kill("SIGKILL"),await tF(s),t$(a)}}}function tW(e,t){let r=process.env[e];if(!r)return t;let a=Number.parseInt(r,10);return Number.isInteger(a)&&a>0?a:t}function tz(e){let t=i.dirname(e);R.existsSync(t)||R.mkdirSync(t,{recursive:!0}),function(e,t){if(R.existsSync(e)&&!(R.statSync(e).size<t.maxBytes))for(let r=t.maxRotatedFiles;r>=1;r-=1){let t=1===r?e:`${e}.${r-1}`,a=`${e}.${r}`;R.existsSync(t)&&(R.existsSync(a)&&R.unlinkSync(a),R.renameSync(t,a))}}(e,{maxBytes:tW("AGENT_DEVICE_APP_LOG_MAX_BYTES",5242880),maxRotatedFiles:tW("AGENT_DEVICE_APP_LOG_MAX_FILES",1)})}async function tJ(e,t,r,a){tz(r);let i=R.createWriteStream(r,{flags:"a"}),n=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 tH(e.id,i,n,a):await tq(t,i,n,a);if("android"===e.platform){if(!/^[a-zA-Z0-9._:-]+$/.test(t))throw new w("INVALID_ARGS",`Invalid Android package name for logs: ${t}`);return await tj(e.id,t,i,n,a)}throw i.end(),new w("UNSUPPORTED_PLATFORM",`unsupported platform: ${e.platform}`)}async function tK(e){await e.stop(),await tF(e.wait)}async function tX(e,t){let r={},a=[];if(t||a.push("No app bundle is tracked in this session. Run open <app> first for app-scoped logs."),"android"===e.platform){try{let e=await c("adb",["version"],{allowFailure:!0});r.adbAvailable=0===e.exitCode}catch{r.adbAvailable=!1}if(t)try{r.androidPidVisible=(await c("adb",["-s",e.id,"shell","pidof",t],{allowFailure:!0})).stdout.trim().length>0}catch{r.androidPidVisible=!1}}if("ios"===e.platform&&"simulator"===e.kind)try{let e=await c("xcrun",["simctl","help"],{allowFailure:!0});r.simctlAvailable=0===e.exitCode}catch{r.simctlAvailable=!1}if("ios"===e.platform&&"device"===e.kind)try{let e=await c("xcrun",["devicectl","--version"],{allowFailure:!0});r.devicectlAvailable=0===e.exitCode}catch{r.devicectlAvailable=!1}return{checks:r,notes:a}}function tZ(e){let t=i.dirname(e),r=i.basename(e);R.existsSync(t)||R.mkdirSync(t,{recursive:!0}),R.existsSync(e)?R.truncateSync(e,0):R.writeFileSync(e,"","utf8");let a=0;for(let e of R.readdirSync(t)){if(!e.startsWith(`${r}.`))continue;let n=e.slice(r.length+1);if(/^\d+$/.test(n))try{R.unlinkSync(i.join(t,e)),a+=1}catch{}}return{path:e,cleared:!0,removedRotatedFiles:a}}let tY=new Map;function tQ(e){let t=tY.get(e);if(t&&(clearTimeout(t.timer),tY.delete(e),t.deleteAfterDownload))try{R.rmSync(t.artifactPath,{force:!0})}catch{}}let t0=new Map;function t1(e,t){let r=t0.get(e);if(!r)throw new w("INVALID_ARGS",`Uploaded artifact not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new w("UNAUTHORIZED","Uploaded artifact belongs to a different tenant");return clearTimeout(r.timer),r.artifactPath}function t2(e){let t=t0.get(e);t&&(clearTimeout(t.timer),t0.delete(e),R.rmSync(t.tempDir,{recursive:!0,force:!0}))}async function t3(e){let t=await t4(e);await c("tar",["xf",e.archivePath,"-C",e.tempDir]);let r=i.join(e.tempDir,t);if(!R.existsSync(r))throw new w("INVALID_ARGS",`Expected extracted bundle "${t}" not found in archive`);return r}async function t4(e){let t=await c("tar",["-tf",e.archivePath],{allowFailure:!0});if(0!==t.exitCode)throw new w("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 w("INVALID_ARGS","Uploaded app bundle archive is empty");let a=r.map(e=>(function(e){if(e.includes("\0"))throw new w("INVALID_ARGS",`Invalid archive entry: ${e}`);if(i.posix.isAbsolute(e))throw new w("INVALID_ARGS",`Archive entry must be relative: ${e}`);let t=i.posix.normalize(e).replace(/^(\.\/)+/,"");if(!t||"."===t||t.startsWith("../"))throw new w("INVALID_ARGS",`Archive entry escapes bundle root: ${e}`);return t})(e)),n=e.expectedRootName??function(e,t){let r=new Set;for(let t of e){let[e]=t.split("/");e&&r.add(e)}let a=[...r];if("ios"===t){let e=a.filter(e=>e.toLowerCase().endsWith(".app"));if(1===e.length)return e[0];if(0===e.length)throw new w("INVALID_ARGS","iOS app bundle archives must contain a single top-level .app directory");throw new w("INVALID_ARGS",`iOS app bundle archives must contain exactly one top-level .app directory, found: ${e.join(", ")}`)}if(1===a.length)return a[0];throw new w("INVALID_ARGS",`Archive must contain a single top-level bundle, found: ${a.join(", ")}`)}(a,e.platform);if(!a.some(e=>e===n||e.startsWith(`${n}/`)))throw new w("INVALID_ARGS",`Uploaded archive must contain a top-level "${n}" bundle`);for(let e of a){var o=e,s=n;if(o!==s&&!o.startsWith(`${s}/`))throw new w("INVALID_ARGS",`Archive entry must stay inside top-level "${s}" bundle: ${o}`)}for(let t of(await c("tar",["-tvf",e.archivePath])).stdout.split(/\r?\n/).filter(Boolean)){let e=t[0];if("l"===e||"h"===e)throw new w("INVALID_ARGS","Uploaded app bundle archive cannot contain symlinks or hard links")}return n}let t8=eb(process.env.AGENT_DEVICE_ARTIFACT_IDLE_TIMEOUT_MS,6e4,1e3);function t6(e,t){return new Promise((r,a)=>{let i,n=R.createWriteStream(t),o=t=>{"destroy"in e&&"function"==typeof e.destroy&&e.destroy(t)},s=!1,l=0,d=e=>{if(!s){if(s=!0,i&&clearTimeout(i),e){n.destroy(),R.rmSync(t,{force:!0}),a(e);return}r()}},u=()=>{i&&clearTimeout(i),i=setTimeout(()=>{let e=new w("COMMAND_FAILED","Artifact transfer timed out due to inactivity",{timeoutMs:t8});o(e),n.destroy(e),d(e)},t8)};e.on("data",e=>{u();let t=Buffer.isBuffer(e)?e.length:Buffer.byteLength(e);if((l+=t)>0x80000000){let e=new w("INVALID_ARGS","Upload exceeds maximum size of 2147483648 bytes");o(e),n.destroy(e),d(e)}}),e.on("error",d),e.on("aborted",()=>{d(new w("COMMAND_FAILED","Artifact transfer was interrupted"))}),n.on("error",d),n.on("finish",()=>d()),u(),e.pipe(n)})}async function t5(e){let t,r=e.headers["x-artifact-type"],a=e.headers["x-artifact-filename"];if(!r||!a)throw new w("INVALID_ARGS","Missing required headers: x-artifact-type and x-artifact-filename");if("file"!==r&&"app-bundle"!==r)throw new w("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 w("INVALID_ARGS","Upload exceeds maximum size of 2147483648 bytes")}(e.headers["content-length"]);let n=function(e){let t=e.trim(),r=i.basename(t);if(!r||"."===r||".."===r)throw new w("INVALID_ARGS",`Invalid artifact filename: ${e}`);return r}(a),o=(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"),R.mkdtempSync(i.join(T.tmpdir(),`agent-device-artifact-${t}-`)));try{if("file"===r){let t=i.join(o,n);return await t6(e,t),{artifactPath:t,tempDir:o}}let t=i.join(o,"artifact.tar");await t6(e,t);let a=await t3({archivePath:t,tempDir:o,platform:"ios",expectedRootName:n});return R.rmSync(t,{force:!0}),{artifactPath:a,tempDir:o}}catch(e){throw R.rmSync(o,{recursive:!0,force:!0}),e}}let t9=new Set(["agent_device.command","agent-device.command"]),t7=new Set(["agent_device.install_from_source","agent-device.install_from_source"]),re=new Set(["agent_device.release_materialized_paths","agent-device.release_materialized_paths"]),rt={"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"},rr=new Set([...t9,...t7,...re,...Object.keys(rt)]);function ra(e,t,r,a){return{jsonrpc:"2.0",id:e,error:{code:t,message:r,data:a}}}function ri(e,t,r=200){e.statusCode=r,e.setHeader("content-type","application/json"),e.end(JSON.stringify(t))}function rn(e){switch(e){case"INVALID_ARGS":return 400;case"UNAUTHORIZED":return 401;case"SESSION_NOT_FOUND":return 404;default:return 500}}function ro(e,t){let r="string"==typeof t.authorization?t.authorization:"",a=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??a??""}function rs(e,t){let r=e[t];return"string"==typeof r?r:void 0}function rl(e,t){let r=e[t];return Number.isInteger(r)?Number(r):void 0}async function rd(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=y(new w("UNAUTHORIZED","Request rejected by auth hook"));return{ok:!1,statusCode:401,response:ra(t.rpcRequest.id??null,-32001,e.message,e)}}if(!1===r.ok){let e=y(new w(r.code??"UNAUTHORIZED",r.message??"Request rejected by auth hook",r.details));return{ok:!1,statusCode:401,response:ra(t.rpcRequest.id??null,-32001,e.message,e)}}if("string"==typeof r.tenantId&&r.tenantId.length>0){let e=o(r.tenantId);if(!e){let e=y(new w("INVALID_ARGS","Auth hook returned invalid tenantId"));return{ok:!1,statusCode:500,response:ra(t.rpcRequest.id??null,-32e3,e.message,e)}}return{ok:!0,tenantId:e}}return{ok:!0}}async function ru(){let e,t=process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;if(!t)return null;let r=process.env.AGENT_DEVICE_HTTP_AUTH_EXPORT||"default",a=i.isAbsolute(t)?t:i.resolve(t);try{e=await import(h(a).href)}catch(e){throw new w("COMMAND_FAILED","Failed to load AGENT_DEVICE_HTTP_AUTH_HOOK module",{hookPath:a,error:e instanceof Error?e.message:String(e)})}let n=e[r];if("function"!=typeof n)throw new w("INVALID_ARGS",`Auth hook export ${r} is not a function`,{hookPath:a,exportName:r});return n}async function rc(e){let t=await ru(),{handleRequest:r,token:a}=e;return V.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 rp(e,i,t,a);if("GET"===e.method&&e.url?.startsWith("/upload/"))return void rf(e,i,t,a);if("POST"!==e.method||"/rpc"!==e.url){i.statusCode=404,i.end("Not found");return}let n="";e.setEncoding("utf8"),e.on("data",t=>{(n+=t).length>1048576&&e.destroy(Error("request too large"))}),e.on("error",()=>{i.headersSent||ri(i,ra(null,-32700,"Parse error"),400)}),e.on("end",async()=>{let a,o;try{a=JSON.parse(n)}catch{ri(i,ra(null,-32700,"Parse error"),400);return}if("2.0"!==a.jsonrpc||"string"!=typeof a.method)return void ri(i,ra(a.id??null,-32600,"Invalid Request"),400);if(!rr.has(a.method))return void ri(i,ra(a.id??null,-32601,`Method not found: ${a.method}`),404);if(!a.params||"object"!=typeof a.params)return void ri(i,ra(a.id??null,-32602,"Invalid params"),400);try{var s;let n=a.params,l=function(e,t,r){if(t9.has(e))return{token:ro(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(t7.has(e)){let e,a=rs(t,"platform");if("ios"!==a&&"android"!==a)throw new w("INVALID_ARGS",'Invalid params: platform must be "ios" or "android"');return{token:ro(t,r),session:rs(t,"session")??"default",command:"install_source",positionals:[],flags:{platform:a},meta:{requestId:rs(t,"requestId"),installSource:function(e){let t=e.source;if(!t||"object"!=typeof t)throw new w("INVALID_ARGS","Invalid params: source is required");if("url"===t.kind){let e="string"==typeof t.url?t.url.trim():"";if(!e)throw new w("INVALID_ARGS","Invalid params: source.url is required for url sources");let r=t.headers,a={};if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw new w("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 w("INVALID_ARGS","Invalid params: source.headers values must be strings");a[e]=t}}return Object.keys(a).length>0?{kind:"url",url:e,headers:a}:{kind:"url",url:e}}if("path"===t.kind){let e="string"==typeof t.path?t.path.trim():"";if(!e)throw new w("INVALID_ARGS","Invalid params: source.path is required for path sources");return{kind:"path",path:e}}throw new w("INVALID_ARGS",'Invalid params: source.kind must be "url" or "path"')}(t),retainMaterializedPaths:(e=t.retainPaths,"boolean"==typeof e?e:void 0),materializedPathRetentionMs:rl(t,"retentionMs")}}}if(re.has(e)){let e=rs(t,"materializationId")?.trim();if(!e)throw new w("INVALID_ARGS","Invalid params: materializationId is required");return{token:ro(t,r),session:rs(t,"session")??"default",command:"release_materialized_paths",positionals:[],meta:{requestId:rs(t,"requestId"),materializationId:e}}}let a=rt[e];if(a)return{token:ro(t,r),session:rs(t,"session")??"default",command:a,positionals:[],meta:{tenantId:rs(t,"tenantId")??rs(t,"tenant"),runId:rs(t,"runId"),leaseId:rs(t,"leaseId"),leaseTtlMs:rl(t,"ttlMs"),leaseBackend:rs(t,"backend")}};throw new w("INVALID_ARGS",`Method not found: ${e}`)}(a.method,n,e.headers);if(s=a.method,t9.has(s)&&("string"!=typeof l.command||0===l.command.length))return void ri(i,ra(a.id??null,-32602,"Invalid params: command is required"),400);o=el(l.meta?.requestId,a.id),l.meta={...l.meta,requestId:o},ed(o);let d=()=>{i.writableFinished||eu(o)};e.on("aborted",d),i.on("close",d);let u=await rd(t,{headers:e.headers,rpcRequest:a,daemonRequest:l});if(!u.ok)return void ri(i,u.response,u.statusCode);u.tenantId&&(l.meta={...l.meta,tenantId:u.tenantId,sessionIsolation:l.meta?.sessionIsolation??l.flags?.sessionIsolation??"tenant"});let c=await r(l);if(c.ok)return void ri(i,{jsonrpc:"2.0",id:a.id??null,result:c});ri(i,ra(a.id??null,-32e3,c.error.message,c.error),rn(c.error.code))}catch(t){let e=y(t);ri(i,ra(a.id??null,-32e3,e.message,e),rn(e.code))}finally{ec(o)}})})}async function rp(e,t,r,a){try{var i;let n,o,s=ro({},e.headers),l=rm(s,a);if(l){t.statusCode=rn(l.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:l.message,code:l.code}));return}let d=await rd(r,{headers:e.headers,rpcRequest:{jsonrpc:"2.0",id:null,method:"agent_device.command"},daemonRequest:{token:s,session:"default",command:"upload",positionals:[]}});if(!d.ok){t.statusCode=d.statusCode,t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:d.response.error?.data?.message??d.response.error?.message??"Unauthorized"}));return}let c=await t5(e),p=(i={artifactPath:c.artifactPath,tempDir:c.tempDir,tenantId:d.tenantId},n=u.randomUUID(),o=setTimeout(()=>{t2(n)},3e5),t0.set(n,{artifactPath:i.artifactPath,tempDir:i.tempDir,tenantId:i.tenantId,timer:o}),n);t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!0,uploadId:p}))}catch(r){let e=y(r);t.statusCode=rn(e.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:e.message,code:e.code}))}}async function rf(e,t,r,a){let i=e.url?.slice("/upload/".length)??"";if(!i){t.statusCode=400,t.end("Missing artifact id");return}try{let n=ro({},e.headers),o=rm(n,a);if(o){t.statusCode=rn(o.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:o.message,code:o.code}));return}let s=await rd(r,{headers:e.headers,rpcRequest:{jsonrpc:"2.0",id:null,method:"agent_device.command"},daemonRequest:{token:n,session:"default",command:"download_artifact",positionals:[i]}});if(!s.ok){t.statusCode=s.statusCode,t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:s.response.error?.data?.message??s.response.error?.message??"Unauthorized"}));return}let l=function(e,t){let r=tY.get(e);if(!r)throw new w("INVALID_ARGS",`Artifact not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new w("UNAUTHORIZED","Artifact belongs to a different tenant");if(!R.existsSync(r.artifactPath))throw tQ(e),new w("COMMAND_FAILED",`Artifact file is missing: ${r.artifactPath}`);return{artifactPath:r.artifactPath,fileName:r.fileName,deleteAfterDownload:r.deleteAfterDownload}}(i,s.tenantId),d=R.createReadStream(l.artifactPath);t.statusCode=200,t.setHeader("content-type","application/octet-stream"),l.fileName&&t.setHeader("content-disposition",`attachment; filename="${l.fileName.replace(/"/g,"")}"`),d.on("error",e=>{if(t.headersSent)t.destroy(e);else{let r=y(e);t.statusCode=rn(r.code),t.end(r.message)}}),t.on("close",()=>{t.writableFinished&&tQ(i)}),d.pipe(t)}catch(r){let e=y(r);t.statusCode=rn(e.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:e.message,code:e.code}))}}function rm(e,t){return t&&e!==t?y(new w("UNAUTHORIZED","Invalid token")):null}function rh(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}function rw(e){if(!e)return;let t=e.trim();if(t&&/^[a-f0-9]{16,128}$/i.test(t))return t.toLowerCase()}function rg(e){let t=(e??"").trim().toLowerCase();if(!t||"ios-simulator"===t)return"ios-simulator";throw new w("INVALID_ARGS",`Unsupported lease backend: ${e??""}`)}class rI{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=rg(e.backend),r=o(e.tenantId);if(!r)throw new w("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");let a=rh(e.runId);if(!a)throw new w("INVALID_ARGS","Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");this.cleanupExpiredLeases();let i=this.resolveLeaseTtlMs(e.ttlMs),n=this.bindingKey(r,a,t),s=this.runBindings.get(n);if(s){let e=this.leases.get(s);if(e)return this.refreshLease(e,i);this.runBindings.delete(n)}this.enforceCapacity(t);let l=this.now(),d={leaseId:u.randomBytes(16).toString("hex"),tenantId:r,runId:a,backend:t,createdAt:l,heartbeatAt:l,expiresAt:l+i};return this.leases.set(d.leaseId,d),this.runBindings.set(n,d.leaseId),{...d}}heartbeatLease(e){let t=rw(e.leaseId);if(!t)throw new w("INVALID_ARGS","Invalid lease id.");this.cleanupExpiredLeases();let r=this.leases.get(t);if(!r)throw new w("UNAUTHORIZED","Lease is not active",{reason:"LEASE_NOT_FOUND"});this.assertOptionalScopeMatch(r,e.tenantId,e.runId);let a=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(r,a)}releaseLease(e){let t=rw(e.leaseId);if(!t)throw new w("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=rg(e.backend),r=o(e.tenantId);if(!r)throw new w("INVALID_ARGS","tenant isolation requires tenant id.");let a=rh(e.runId);if(!a)throw new w("INVALID_ARGS","tenant isolation requires run id.");let i=rw(e.leaseId);if(!i)throw new w("INVALID_ARGS","tenant isolation requires lease id.");this.cleanupExpiredLeases();let n=this.leases.get(i);if(!n)throw new w("UNAUTHORIZED","Lease is not active",{reason:"LEASE_NOT_FOUND"});if(n.backend!==t||n.tenantId!==r||n.runId!==a)throw new w("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 w("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 w("INVALID_ARGS",`Lease ttlMs must be between ${this.minLeaseTtlMs} and ${this.maxLeaseTtlMs}.`);return t}refreshLease(e,t){let r=this.now(),a={...e,heartbeatAt:r,expiresAt:r+t};return this.leases.set(a.leaseId,a),this.runBindings.set(this.bindingKey(a.tenantId,a.runId,a.backend),a.leaseId),{...a}}bindingKey(e,t,r){return`${e}:${t}:${r}`}assertOptionalScopeMatch(e,t,r){let a=o(t),i=rh(r);if(t&&!a)throw new w("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if(r&&!i)throw new w("INVALID_ARGS","Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if(a&&e.tenantId!==a||i&&e.runId!==i)throw new w("UNAUTHORIZED","Lease does not match tenant/run scope",{reason:"LEASE_SCOPE_MISMATCH"})}}let rA=["emulator","platform-tools",i.join("cmdline-tools","latest","bin"),i.join("cmdline-tools","tools","bin")];function rv(e){let t=new Set,r=[];for(let a of e){let e=a.trim();!e||t.has(e)||(t.add(e),r.push(e))}return r}function ry(e=process.env){let t=e.ANDROID_SDK_ROOT?.trim(),r=e.ANDROID_HOME?.trim(),a=e.HOME?.trim()||T.homedir();return rv([t??"",r??"",a?i.join(a,"Android","Sdk"):""])}async function rb(e){try{return await O.access(e,O.constants.X_OK),!0}catch{return!1}}async function rS(e=process.env){let t,r=[];for(let a of ry(e)){let e=[];for(let t of rA){let r=i.join(a,t);await rb(r)&&e.push(r)}0!==e.length&&(t||(t=a),r.push(...e))}if(t&&(e.ANDROID_SDK_ROOT=e.ANDROID_SDK_ROOT?.trim()||t,e.ANDROID_HOME=e.ANDROID_HOME?.trim()||t),0===r.length)return;let a=(e.PATH??"").split(i.delimiter).map(e=>e.trim()).filter(e=>e.length>0);e.PATH=rv([...r,...a]).join(i.delimiter)}function rN(e,t){return["-s",e.id,...t]}async function r_(){if(await rS(),!await I("adb"))throw new w("TOOL_MISSING","adb not found in PATH")}function rD(e,t){let r=`${e}
10
- ${t}`.toLowerCase();return r.includes("no shell command implementation")||r.includes("unknown command")}async function rE(e){await new Promise(t=>setTimeout(t,e))}function rk(e){let t=e.trim();if(!t||/\s/.test(t))return!1;let r=/^([A-Za-z][A-Za-z0-9+.-]*):(.+)$/.exec(t);if(!r)return!1;let a=r[1]?.toLowerCase(),i=r[2]??"";return"http"!==a&&"https"!==a&&"ws"!==a&&"wss"!==a&&"ftp"!==a&&"ftps"!==a||i.startsWith("//")}function rL(e,t){let r,a=e?.trim();return a?a:"http"===(r=t.trim().split(":")[0]?.toLowerCase())||"https"===r?"com.apple.mobilesafari":void 0}let rO=["android.software.leanback","android.software.leanback_only","android.hardware.type.television"];function rx(e){return`${e.stdout}
11
- ${e.stderr}`}function rM(e,t){return["-s",e,...t]}function rC(e){return e.startsWith("emulator-")}function rR(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function rP(e){let t=e.split("\n").map(e=>e.trim()).filter(e=>e.length>0);if(0!==t.length)return"OK"===t.at(-1)&&t.pop(),t.join("\n").trim()||void 0}async function rT(e,t=Q){return c("adb",rM(e,["shell","getprop","sys.boot_completed"]),{allowFailure:!0,timeoutMs:t})}async function r$(e,t){let r=t.replace(/_/g," ").trim();if(!rC(e))return r||e;let a=await rU(e);return a?a.replace(/_/g," "):r||e}async function rF(e,t,r){try{return await r("adb",rM(e,t),{allowFailure:!0,timeoutMs:1e4})}catch(e){var a;if("COMMAND_FAILED"===(a=f(e)).code&&"number"==typeof a.details?.timeoutMs)return;throw e}}async function rU(e,t=c){for(let r of["ro.boot.qemu.avd_name","persist.sys.avd_name"]){let a=await rF(e,["shell","getprop",r],t);if(!a)continue;let i=a.stdout.trim();if(0===a.exitCode&&i.length>0)return i}let r=await rF(e,["emu","avd","name"],t);if(!r)return;let a=rP(r.stdout);if(0===r.exitCode&&a)return a}function rV(e){let t=e.toLowerCase();return t.includes("tv")||t.includes("leanback")?"tv":null}function rG(e){return/feature:android\.(software\.leanback(_only)?|hardware\.type\.television)\b/i.test(e)}async function rB(e,t){let r=rx(await c("adb",rM(e,["shell","cmd","package","has-feature",t]),{allowFailure:!0,timeoutMs:Q})).toLowerCase();return!!r.includes("true")||!r.includes("false")&&null}async function rj(e){return(await Promise.all(rO.map(async t=>await rB(e,t)))).some(e=>!0===e)}async function rq(e){return"tv"===rV(rx(await c("adb",rM(e,["shell","getprop","ro.build.characteristics"]),{allowFailure:!0,timeoutMs:Q})))||await rj(e)||rG(rx(await c("adb",rM(e,["shell","pm","list","features"]),{allowFailure:!0,timeoutMs:Q})))?"tv":"mobile"}async function rH(e={}){if(await rS(),!await I("adb"))throw new w("TOOL_MISSING","adb not found in PATH");let t=e.serialAllowlist??eL(void 0),r=(await rW()).filter(e=>!t||t.has(e.serial));return await Promise.all(r.map(async({serial:e,rawModel:t})=>{let[r,a,i]=await Promise.all([r$(e,t),rY(e),rq(e)]);return{platform:"android",id:e,name:r,kind:rC(e)?"emulator":"device",target:i,booted:a}}))}async function rW(){return(await c("adb",["devices","-l"],{timeoutMs:Q})).stdout.split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith("List of devices")).map(e=>e.split(/\s+/)).filter(e=>"device"===e[1]).map(e=>({serial:e[0],rawModel:(e.find(e=>e.startsWith("model:"))??"").replace("model:","")}))}function rz(e){return e.split("\n").map(e=>e.trim()).filter(e=>e.length>0)}function rJ(e,t){let r=e.find(e=>e===t);if(r)return r;let a=rR(t);return e.find(e=>rR(e)===a)}async function rK(){let e=await c("emulator",["-list-avds"],{allowFailure:!0,timeoutMs:Q});if(0!==e.exitCode)throw new w("COMMAND_FAILED","Failed to list Android emulator AVDs",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,hint:"Verify Android emulator tooling is installed and available in PATH."});return rz(e.stdout)}async function rX(e){let t=Date.now();for(;Date.now()-t<e.timeoutMs;){try{let t=await rZ(e.avdName,e.serial);if(t)return{platform:"android",id:t,name:e.avdName,kind:"emulator",target:"mobile",booted:!1}}catch{}await new Promise(e=>setTimeout(e,1e3))}throw new w("COMMAND_FAILED","Android emulator did not appear in time",{avdName:e.avdName,serial:e.serial,timeoutMs:e.timeoutMs,hint:"Check emulator logs and verify the AVD can start from command line."})}async function rZ(e,t){let r=rR(e);for(let e of(await rW()).filter(e=>(!t||e.serial===t)&&rC(e.serial)))if(rR(e.rawModel)===r||rR(await r$(e.serial,e.rawModel))===r)return e.serial}async function rY(e){try{let t=await rT(e);return"1"===t.stdout.trim()}catch{return!1}}async function rQ(e){var t,r;let a;await rS();let i=e.avdName.trim();if(!i)throw new w("INVALID_ARGS","Android emulator boot requires a non-empty AVD name.");let n=e.timeoutMs??12e4;if(!await I("adb"))throw new w("TOOL_MISSING","adb not found in PATH");if(!await I("emulator"))throw new w("TOOL_MISSING","emulator not found in PATH");let o=await rK(),s=rJ(o,i);if(!s)throw new w("DEVICE_NOT_FOUND",`No Android emulator AVD named ${e.avdName}`,{requestedAvdName:i,availableAvds:o,hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."});let d=Date.now(),u=(t=await rH(),r=e.serial,a=rR(s),t.find(e=>"android"===e.platform&&"emulator"===e.kind&&(!r||e.id===r)&&rR(e.name)===a));if(!u){let t=["-avd",s];e.headless&&t.push("-no-window","-no-audio"),l("emulator",t)}let c=u??await rX({avdName:s,serial:e.serial,timeoutMs:n}),p=Math.max(1e3,n-(Date.now()-d));await r1(c.id,p);let f=(await rH()).find(e=>e.id===c.id);return f?{...f,name:s,booted:!0}:{...c,name:s,booted:!0}}async function r0(e){return await rQ({...e,headless:!0})}async function r1(e,t=6e4){let r,a=ee.fromTimeoutMs(t),i=Math.max(1,Math.ceil(t/1e3)),n=!1;try{await et(async({deadline:i})=>{if(i?.isExpired())throw n=!0,new w("COMMAND_FAILED","Android boot deadline exceeded",{serial:e,timeoutMs:t,elapsedMs:a.elapsedMs(),message:"timeout"});let o=Math.max(1e3,i?.remainingMs()??t),s=await rT(e,Math.min(o,Q));if(r=s,"1"!==s.stdout.trim())throw new w("COMMAND_FAILED","Android device is still booting",{serial:e,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode})},{maxAttempts:i,baseDelayMs:1e3,maxDelayMs:1e3,jitter:0,shouldRetry:e=>{let t=ew({error:e,stdout:r?.stdout,stderr:r?.stderr,context:{platform:"android",phase:"boot"}});return"ADB_TRANSPORT_UNAVAILABLE"!==t&&"ANDROID_BOOT_TIMEOUT"!==t}},{deadline:a,phase:"boot",classifyReason:e=>ew({error:e,stdout:r?.stdout,stderr:r?.stderr,context:{platform:"android",phase:"boot"}})})}catch(c){let i=f(c),o=r?.stdout,s=r?.stderr,l=r?.exitCode,d=ew({error:c,stdout:o,stderr:s,context:{platform:"android",phase:"boot"}});"BOOT_COMMAND_FAILED"===d&&"Android device is still booting"===i.message&&(d="ANDROID_BOOT_TIMEOUT");let u={serial:e,timeoutMs:t,elapsedMs:a.elapsedMs(),reason:d,hint:eg(d),stdout:o,stderr:s,exitCode:l};if(n||"ANDROID_BOOT_TIMEOUT"===d)throw new w("COMMAND_FAILED","Android device did not finish booting in time",u);if("TOOL_MISSING"===i.code)throw new w("TOOL_MISSING",i.message,{...u,...i.details??{}});if("ADB_TRANSPORT_UNAVAILABLE"===d)throw new w("COMMAND_FAILED",i.message,{...u,...i.details??{}});throw new w(i.code,i.message,{...u,...i.details??{}},i.cause)}}let r2=/\.(?:apk|aab)$/i,r3=/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)+$/;function r4(e){var t,r;let a=e.trim();return 0===a.length?"other":r2.test(a)?a.includes("/")||a.includes("\\")||a.startsWith(".")||a.startsWith("~")||(t=a,!r3.test(t))?"binary":"package":(r=a,r3.test(r))?"package":"other"}function r8(e){return`Android runtime hints require an installed package name, not "${e}". Install or reinstall the app first, then relaunch by package.`}let r6=[".zip",".tar",".tar.gz",".tgz"],r5=eb(process.env.AGENT_DEVICE_SOURCE_DOWNLOAD_TIMEOUT_MS,12e4,1e3),r9=["1","true","yes","on"];async function r7(e){let t=[];try{let r=await ae(e.source,{signal:e.signal,downloadTimeoutMs:e.downloadTimeoutMs});t.push(r.cleanup);let a=await an(r.localPath,{archivePath:void 0,isInstallablePath:e.isInstallablePath,installableLabel:e.installableLabel,allowArchiveExtraction:!1!==e.allowArchiveExtraction,registerCleanup:e=>{t.push(e)}});return{archivePath:a.archivePath,installablePath:a.installablePath,cleanup:async()=>{await ad(t)}}}catch(e){throw await ad(t),e}}async function ae(e,t){if("path"===e.kind)return{localPath:m(e.path),cleanup:async()=>{}};let r=await O.mkdtemp(i.join(T.tmpdir(),"agent-device-source-"));try{return{localPath:await at(r,e.url,e.headers,t),cleanup:async()=>{await O.rm(r,{recursive:!0,force:!0})}}}catch(e){throw await O.rm(r,{recursive:!0,force:!0}),e}}async function at(e,t,r,a){let n;try{n=new URL(t)}catch{throw new w("INVALID_ARGS",`Invalid source URL: ${t}`)}await ar(n);let o=a?.signal;if(o?.aborted)throw new w("COMMAND_FAILED","request canceled",{reason:"request_canceled"});let s=new AbortController,l=()=>{s.abort(o?.reason)};o?.addEventListener("abort",l,{once:!0});let d=a?.downloadTimeoutMs??r5,u=setTimeout(()=>{s.abort(Error("download timeout"))},d);try{let t=await fetch(n,{headers:r,redirect:"follow",signal:s.signal});if(!t.ok)throw new w("COMMAND_FAILED",`Failed to download app source: ${t.status} ${t.statusText}`,{status:t.status,statusText:t.statusText,url:n.toString()});let a=function(e,t){let r=e.headers.get("content-disposition"),a=r?.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i),n=a?.[1]?.trim();if(n)return i.basename(n);let o=i.basename(t.pathname);return o||"downloaded-artifact.bin"}(t,n),o=i.join(e,a),l=t.body;if(!l)throw new w("COMMAND_FAILED","Download response body was empty",{url:n.toString()});let d=await O.open(o,"w");try{for await(let e of l)await d.write(e)}finally{await d.close()}return o}catch(e){if(o?.aborted)throw new w("COMMAND_FAILED","request canceled",{reason:"request_canceled"},e);if(s.signal.aborted)throw new w("COMMAND_FAILED",`App source download timed out after ${d}ms`,{timeoutMs:d,url:n.toString()},e);throw e}finally{o?.removeEventListener("abort",l),clearTimeout(u)}}async function ar(e){if("http:"!==e.protocol&&"https:"!==e.protocol)throw new w("INVALID_ARGS",`Unsupported source URL protocol: ${e.protocol}`);if(!r9.includes((process.env.AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS??"").toLowerCase())){var t;if(!(t=e.hostname.toLowerCase())||"localhost"===t||t.endsWith(".localhost")||ai(t))throw new w("INVALID_ARGS",`Source URL host is not allowed: ${e.hostname}`,{hint:"Use a public artifact URL, or set AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS=1 for trusted private-network daemons."});if((await r.lookup(e.hostname,{all:!0,verbatim:!0}).catch(()=>[])).some(e=>ai(e.address)))throw new w("INVALID_ARGS",`Source URL host resolved to a private or loopback address: ${e.hostname}`,{hint:"Use a public artifact URL, or set AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS=1 for trusted private-network daemons."})}}function aa(e){var t,r,a,i;let n=e instanceof URL?e:new URL(e),o=n.hostname.toLowerCase();if(!o)return!1;let s=n.pathname;return t=o,r=s,("api.github.com"===t?/^\/repos\/[^/]+\/[^/]+\/actions\/artifacts\/\d+\/zip$/i.test(r):"github.com"===t&&/^\/[^/]+\/[^/]+\/(?:actions\/runs\/\d+\/artifacts\/\d+|suites\/\d+\/artifacts\/\d+)$/i.test(r))||(a=o,i=s,("expo.dev"===a||!!a.endsWith(".expo.dev"))&&/^\/(?:artifacts\/eas\/|accounts\/[^/]+\/projects\/[^/]+\/builds\/)/i.test(i))}function ai(e){let t,r=$.isIP(e);return 4===r?function(e){let t=e.split(".").map(e=>Number.parseInt(e,10));if(4!==t.length||t.some(e=>Number.isNaN(e)||e<0||e>255))return!1;let[r,a]=t;return 10===r||127===r||169===r&&254===a||172===r&&!!(a>=16)&&!!(a<=31)||192===r&&168===a}(e):6===r&&!!("::1"===(t=e.toLowerCase())||t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80:"))}async function an(e,t){let r=await O.stat(e).catch(()=>null);if(!r)throw new w("INVALID_ARGS",`App source not found: ${e}`);if(t.isInstallablePath(e,r))return{archivePath:t.archivePath,installablePath:e};if(r.isFile()&&al(e)){if(!t.allowArchiveExtraction)throw new w("INVALID_ARGS",`URL sources must point directly to a ${t.installableLabel}; archive extraction is not allowed`,{path:e});let r=await as(e);return t.registerCleanup(r.cleanup),await an(r.outputPath,{...t,archivePath:t.archivePath??e})}if(r.isDirectory()){let r=await ao(e,t.isInstallablePath);if(1===r.length)return{archivePath:t.archivePath,installablePath:r[0]};if(r.length>1)throw new w("INVALID_ARGS",`Found multiple ${t.installableLabel} candidates under ${e}`,{matches:r});let a=await ao(e,(e,t)=>t.isFile()&&al(e));if(1===a.length){if(!t.allowArchiveExtraction)throw new w("INVALID_ARGS",`URL sources must point directly to a ${t.installableLabel}; nested archives are not allowed`,{path:a[0]});let e=await as(a[0]);return t.registerCleanup(e.cleanup),await an(e.outputPath,{...t,archivePath:t.archivePath??a[0]})}if(a.length>1)throw new w("INVALID_ARGS",`Found multiple nested archives under ${e}; expected one ${t.installableLabel} source`,{matches:a})}throw new w("INVALID_ARGS",`Expected ${t.installableLabel} source, but got ${e}`)}async function ao(e,t){let r=[],a=[{path:e,depth:0}];for(;a.length>0;){let e=a.shift();if(!e)continue;let n=await O.readdir(e.path,{withFileTypes:!0});for(let o of(n.sort((e,t)=>e.name.localeCompare(t.name)),n)){let n=i.join(e.path,o.name);if(t(n,o)){r.push(n);continue}o.isDirectory()&&e.depth<5&&a.push({path:n,depth:e.depth+1})}}return r}async function as(e){let t=await O.mkdtemp(i.join(T.tmpdir(),"agent-device-archive-"));try{return e.toLowerCase().endsWith(".zip")?await c("ditto",["-x","-k",e,t]):e.toLowerCase().endsWith(".tar.gz")||e.toLowerCase().endsWith(".tgz")?await c("tar",["-xzf",e,"-C",t]):await c("tar",["-xf",e,"-C",t]),{outputPath:t,cleanup:async()=>{await O.rm(t,{recursive:!0,force:!0})}}}catch(e){throw await O.rm(t,{recursive:!0,force:!0}),e}}function al(e){let t=e.toLowerCase();return r6.some(e=>t.endsWith(e))}async function ad(e){for(let t=e.length-1;t>=0;t-=1)await e[t]()}let au=new z("utf-16le");async function ac(e){for(let r of["AndroidManifest.xml","base/manifest/AndroidManifest.xml"]){var t;let a=await ap(e,r);if(!a)continue;let i=(t=a).subarray(0,Math.min(t.length,128)).toString("utf8").trimStart().startsWith("<")?function(e){let t=e.match(/<manifest\b[^>]*\bpackage\s*=\s*["']([^"']+)["']/i);return t?.[1]}(t.toString("utf8")):function(e){let t;if(!(e.length<8)&&3===e.readUInt16LE(0))for(let r=e.readUInt16LE(2);r+8<=e.length;){let a=e.readUInt16LE(r),i=e.readUInt16LE(r+2),n=e.readUInt32LE(r+4);if(n<=0||r+n>e.length)break;if(1===a)t=function(e){if(e.length<28)return[];let t=e.readUInt32LE(8),r=e.readUInt32LE(16),a=e.readUInt32LE(20),i=(256&r)!=0,n=[];for(let r=0;r<t;r+=1){let t=28+4*r;if(t+4>e.length)break;let o=a+e.readUInt32LE(t);n.push(i?function(e,t){let[,r]=af(e,t),[a,i]=af(e,t+r),n=t+r+i;return e.subarray(n,n+a).toString("utf8")}(e,o):function(e,t){let[r,a]=function(e,t){let r=e.readUInt16LE(t);return(32768&r)==0?[r,2]:[(32767&r)<<16|e.readUInt16LE(t+2),4]}(e,t),i=t+a;return au.decode(e.subarray(i,i+2*r))}(e,o))}return n}(e.subarray(r,r+n));else if(258===a&&t){let a=function(e,t,r,a){if(r<36||t+r>e.length||"manifest"!==a[e.readUInt32LE(t+20)])return;let i=e.readUInt16LE(t+24),n=e.readUInt16LE(t+26),o=e.readUInt16LE(t+28),s=t+i;for(let t=0;t<o;t+=1){let r=s+t*n;if(r+20>e.length)break;if("package"!==a[e.readUInt32LE(r+4)])continue;let i=e.readUInt32LE(r+8);if(0xffffffff!==i)return a[i];let o=e.readUInt8(r+15),l=e.readUInt32LE(r+16);if(3===o)return a[l];break}}(e,r,i,t);if(a)return a}r+=n}}(t);if(i)return i}return await am(e)}async function ap(e,t){try{let r=await c("unzip",["-p",e,t],{allowFailure:!0,binaryStdout:!0});if(0!==r.exitCode||!r.stdoutBuffer||0===r.stdoutBuffer.length)return;return r.stdoutBuffer}catch{return}}function af(e,t){let r=e.readUInt8(t);return(128&r)==0?[r,1]:[(127&r)<<8|e.readUInt8(t+1),2]}async function am(e){let t=await ah();if(!t)return;let r=await c(t,["dump","badging",e],{allowFailure:!0});if(0!==r.exitCode)return;let a=r.stdout.match(/package:\s+name='([^']+)'/);return a?.[1]}async function ah(){if(void 0!==e)return e??void 0;try{for(let t of ry()){let r=i.join(t,"build-tools");try{for(let t of(await a.readdir(r)).sort((e,t)=>t.localeCompare(e,void 0,{numeric:!0}))){let n=i.join(r,t,"aapt");try{return await a.access(n),e=n,n}catch{}}}catch{}}}catch{}e=null}async function aw(e,t){let r="url"===e.kind&&aa(e.url),a=await r7({source:e,isInstallablePath:(e,t)=>{var r;let a;return t.isFile()&&(r=e,".apk"===(a=i.extname(r).toLowerCase())||".aab"===a)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==e.kind||r,signal:t?.signal}),n=t?.resolveIdentity===!1?{}:await ag(a.installablePath);return{archivePath:a.archivePath,installablePath:a.installablePath,packageName:n.packageName,cleanup:a.cleanup}}async function ag(e){let t=i.extname(e).toLowerCase();return".apk"!==t&&".aab"!==t?{}:{packageName:await ac(e)}}let aI={settings:{type:"intent",value:"android.settings.SETTINGS"}},aA="android.intent.category.LAUNCHER",av="android.intent.category.LEANBACK_LAUNCHER",ay="android.intent.category.DEFAULT";async function ab(e,t){let r=t.trim();if("package"===r4(r))return{type:"package",value:r};let a=aI[r.toLowerCase()];if(a)return a;let i=(await c("adb",rN(e,["shell","pm","list","packages"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean).filter(e=>e.toLowerCase().includes(r.toLowerCase()));if(1===i.length)return{type:"package",value:i[0]};if(i.length>1)throw new w("INVALID_ARGS",`Multiple packages matched "${t}"`,{matches:i});throw new w("APP_NOT_INSTALLED",`No package found matching "${t}"`)}async function aS(e,t="all"){let r=await aN(e);return("user-installed"===t?(await aD(e)).filter(e=>r.has(e)):Array.from(r)).sort((e,t)=>e.localeCompare(t)).map(e=>({package:e,name:aE(e)}))}async function aN(e){let t=new Set;for(let r of a_(e,{includeFallbackWhenUnknown:!0})){let a=await c("adb",rN(e,["shell","cmd","package","query-activities","--brief","-a","android.intent.action.MAIN","-c",r]),{allowFailure:!0});if(0===a.exitCode&&0!==a.stdout.trim().length)for(let e of a.stdout.split("\n")){let r=e.trim();if(!r)continue;let a=r.split(/\s+/)[0],i=a.includes("/")?a.split("/")[0]:a;i&&t.add(i)}}return t}function a_(e,t={}){return"tv"===e.target?[av]:"mobile"===e.target?[aA]:t.includeFallbackWhenUnknown?[aA,av]:[aA]}async function aD(e){return(await c("adb",rN(e,["shell","pm","list","packages","-3"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean)}function aE(e){let t=new Set(["com","android","google","app","apps","service","services","mobile","client"]),r=e.split(".").flatMap(e=>e.split(/[_-]+/)).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0),a=r[r.length-1]??e;for(let e=r.length-1;e>=0;e-=1){let i=r[e];if(!t.has(i)){a=i;break}}return a.split(/[^a-z0-9]+/i).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async function ak(e){let t=await aL(e,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]]);if(t)return t;let r=await aL(e,[["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]);return r||{}}async function aL(e,t){for(let r of t){let t=function(e){for(let t of[/mCurrentFocus=Window\{[^}]*\s([\w.]+)\/([\w.$]+)/,/mFocusedApp=AppWindowToken\{[^}]*\s([\w.]+)\/([\w.$]+)/,/mResumedActivity:.*?\s([\w.]+)\/([\w.$]+)/,/ResumedActivity:.*?\s([\w.]+)\/([\w.$]+)/]){let r=t.exec(e);if(r)return{package:r[1],activity:r[2]}}return null}((await c("adb",rN(e,r),{allowFailure:!0})).stdout??"");if(t)return t}return null}async function aO(e,t,r){e.booted||await r1(e.id);let a=t.trim();if(rk(a)){if(r)throw new w("INVALID_ARGS","Activity override is not supported when opening a deep link URL");await c("adb",rN(e,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",a]));return}let i=await ab(e,t),n=a_(e)[0]??aA;if("intent"===i.type){if(r)throw new w("INVALID_ARGS","Activity override requires a package name, not an intent");await c("adb",rN(e,["shell","am","start","-W","-a",i.value]));return}if(r){let t=r.includes("/")?r:`${i.value}/${r.startsWith(".")?r:`.${r}`}`;await c("adb",rN(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",ay,"-c",n,"-n",t]));return}let o=await c("adb",rN(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",ay,"-c",n,"-p",i.value]),{allowFailure:!0});if(0===o.exitCode&&!aM(o.stdout,o.stderr))return;let s=await ax(e,i.value);if(!s)throw new w("COMMAND_FAILED",`Failed to launch ${i.value}`,{stdout:o.stdout,stderr:o.stderr});await c("adb",rN(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",ay,"-c",n,"-n",s]))}async function ax(e,t){for(let r of Array.from(new Set(a_(e,{includeFallbackWhenUnknown:!0})))){let a=await c("adb",rN(e,["shell","cmd","package","resolve-activity","--brief","-a","android.intent.action.MAIN","-c",r,t]),{allowFailure:!0});if(0!==a.exitCode)continue;let i=aC(a.stdout);if(i)return i}return null}function aM(e,t){let r=`${e}
12
- ${t}`;return/Error:.*(?:Activity not started|unable to resolve Intent)/i.test(r)}function aC(e){let t=e.split("\n").map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.includes("/"))return r.split(/\s+/)[0]}return null}async function aR(e){e.booted||await r1(e.id)}async function aP(e,t){if("settings"===t.trim().toLowerCase())return void await c("adb",rN(e,["shell","am","force-stop","com.android.settings"]));let r=await ab(e,t);if("intent"===r.type)throw new w("INVALID_ARGS","Close requires a package name, not an intent");await c("adb",rN(e,["shell","am","force-stop",r.value]))}async function aT(e,t){let r=await ab(e,t);if("intent"===r.type)throw new w("INVALID_ARGS","App uninstall requires a package name, not an intent");let a=await c("adb",rN(e,["uninstall",r.value]),{allowFailure:!0});if(0!==a.exitCode){let e=`${a.stdout}
13
- ${a.stderr}`.toLowerCase();if(!e.includes("unknown package")&&!e.includes("not installed"))throw new w("COMMAND_FAILED",`adb uninstall failed for ${r.value}`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode})}return{package:r.value}}let a$=null;async function aF(){let e=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(a$?.key===e)return a$.invocation;if(await I("bundletool")){let t={cmd:"bundletool",prefixArgs:[]};return a$={key:e,invocation:t},t}let t=process.env.AGENT_DEVICE_BUNDLETOOL_JAR?.trim();if(!t)throw new w("TOOL_MISSING","bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.");try{await O.access(t)}catch{throw new w("TOOL_MISSING",`AGENT_DEVICE_BUNDLETOOL_JAR points to a missing file: ${t}`)}let r={cmd:"java",prefixArgs:["-jar",t]};return a$={key:e,invocation:r},r}async function aU(e){let t=await aF();await c(t.cmd,[...t.prefixArgs,...e])}async function aV(e,t){let r,a=await O.mkdtemp(i.join(T.tmpdir(),"agent-device-aab-")),n=i.join(a,"bundle.apks"),o=(r=process.env.AGENT_DEVICE_ANDROID_BUNDLETOOL_MODE?.trim())&&r.length>0?r:"universal";try{await aU(["build-apks","--bundle",t,"--output",n,"--mode",o]),await aU(["install-apks","--apks",n,"--device-id",e.id])}finally{await O.rm(a,{recursive:!0,force:!0})}}async function aG(e,t){".aab"===i.extname(t).toLowerCase()?await aV(e,t):await c("adb",rN(e,["install","-r",t]))}async function aB(e){return new Set((await c("adb",rN(e,["shell","pm","list","packages"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean))}async function aj(e,t){let r=Array.from(await aB(e)).filter(e=>!t.has(e));if(1===r.length)return r[0]}async function aq(e,t){e.booted||await r1(e.id),await aG(e,t)}async function aH(e,t,r){let a=r?void 0:await aB(e);return await aq(e,t),r??(a?await aj(e,a):void 0)}async function aW(e,t){e.booted||await r1(e.id);let r=await aw({kind:"path",path:t});try{let t=await aH(e,r.installablePath,r.packageName),a=t?aE(t):void 0;return{archivePath:r.archivePath,installablePath:r.installablePath,packageName:t,appName:a,launchTarget:t}}finally{await r.cleanup()}}async function az(e,t,r){e.booted||await r1(e.id);let{package:a}=await aT(e,t),i=await aw({kind:"path",path:r},{resolveIdentity:!1});try{return await aq(e,i.installablePath),{package:a}}finally{await i.cleanup()}}function aJ(e){let t=aK(e),r=e=>{let r=aX(t,e);if(null!==r)return"true"===r};return{text:aX(t,"text"),desc:aX(t,"content-desc"),resourceId:aX(t,"resource-id"),className:aX(t,"class"),bounds:aX(t,"bounds"),clickable:r("clickable"),enabled:r("enabled"),focusable:r("focusable"),focused:r("focused")}}function aK(e){let t=new Map,r=e.indexOf(" "),a=e.lastIndexOf(">");if(r<0||a<=r)return t;let i=/([^\s=/>]+)\s*=\s*(["'])([\s\S]*?)\2/y,n=r;for(;n<a;){for(;n<a;){let t=e[n];if(" "!==t&&"\n"!==t&&"\r"!==t&&" "!==t)break;n+=1}if(n>=a)break;let r=e[n];if("/"===r||">"===r)break;i.lastIndex=n;let o=i.exec(e);if(!o)break;t.set(o[1],o[3]),n=i.lastIndex}return t}function aX(e,t){return e.get(t)??null}function aZ(e){if(!e)return;let t=/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/.exec(e);if(!t)return;let r=Number(t[1]),a=Number(t[2]);return{x:r,y:a,width:Math.max(0,Number(t[3])-r),height:Math.max(0,Number(t[4])-a)}}function aY(e){return e?e.toLowerCase():""}function aQ(e){let t=e.trim();return!!t&&/^[\w.]+:id\/[\w.-]+$/i.test(t)}async function a0(e,t={}){return function(e,t,r){let a=function(e){let t={type:null,label:null,value:null,identifier:null,depth:-1,children:[]},r=[t],a=/<node\b[^>]*>|<\/node>/g,i=a.exec(e);for(;i;){let t=i[0];if(t.startsWith("</node")){r.length>1&&r.pop(),i=a.exec(e);continue}let n=aJ(t),o=aZ(n.bounds),s=r[r.length-1],l={type:n.className,label:n.text||n.desc,value:n.text,identifier:n.resourceId,rect:o,enabled:n.enabled,hittable:n.clickable??n.focusable,depth:s.depth+1,parentIndex:void 0,children:[]};s.children.push(l),t.endsWith("/>")||r.push(l),i=a.exec(e)}return t}(e),i=[],n=!1,o=r.depth??1/0,s=r.scope?function(e,t){let r=t.toLowerCase(),a=[...e.children];for(;a.length>0;){let e=a.shift(),t=e.label?.toLowerCase()??"",i=e.value?.toLowerCase()??"",n=e.identifier?.toLowerCase()??"";if(t.includes(r)||i.includes(r)||n.includes(r))return e;a.push(...e.children)}return null}(a,r.scope):null,l=s?[s]:a.children,d=new Map,u=e=>{let t=d.get(e);if(void 0!==t)return t;for(let t of e.children)if(t.hittable||u(t))return d.set(e,!0),!0;return d.set(e,!1),!1},c=(e,t,a,s=!1,l=!1)=>{var d,p,f,m,h,w;let g,I,A,v,y,b,S,N;if(i.length>=800){n=!0;return}if(t>o)return;let _=!!r.raw||(d=e,p=r,f=s,m=u(e),h=l,I=aY(d.type),A=!!(d.label&&d.label.trim().length>0),v=!!(d.identifier&&d.identifier.trim().length>0),y=A&&!aQ(d.label??""),b=v&&!aQ(d.identifier??""),S=(g=(w=I).split(".").pop()??w).includes("layout")||"viewgroup"===g||"view"===g,N="imageview"===I||"imagebutton"===I,p.interactiveOnly?!!d.hittable||!!(y||b)&&!N&&(!S||!!h)&&(f||m||h):p.compact?y||b||!!d.hittable:!S&&!N||!!d.hittable||!!y||!!b&&!!m||m),D=a;_&&(D=i.length,i.push({index:D,type:e.type??void 0,label:e.label??void 0,value:e.value??void 0,identifier:e.identifier??void 0,rect:e.rect,enabled:e.enabled,hittable:e.hittable,depth:t,parentIndex:a}));let E=s||!!e.hittable,k=l||function(e){if(!e)return!1;let t=aY(e);return t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")}(e.type);for(let r of e.children)if(c(r,t+1,D,E,k),n)return};for(let e of l)if(c(e,0,void 0,!1,!1),n)break;return n?{nodes:i,truncated:n}:{nodes:i}}(await a1(e),0,t)}async function a1(e){return er(()=>a2(e),{shouldRetry:a4})}async function a2(e){var t,r,a;let i,n,o=await c("adb",rN(e,["exec-out","uiautomator","dump","/dev/tty"]),{allowFailure:!0});if(0===o.exitCode){let e=a3(o.stdout,o.stderr);if(e)return e}let s="/sdcard/window_dump.xml",l=await c("adb",rN(e,["shell","uiautomator","dump",s])),d=(t=s,r=l.stdout,a=l.stderr,i=`${r}
14
- ${a}`,n=/dumped to:\s*(\S+)/i.exec(i),n?.[1]??t),u=await c("adb",rN(e,["shell","cat",d])),p=a3(u.stdout,u.stderr);if(!p)throw new w("COMMAND_FAILED","uiautomator dump did not return XML",{stdout:u.stdout,stderr:u.stderr});return p}function a3(e,t){let r=`${e}
15
- ${t}`,a=r.indexOf("<?xml"),i=a>=0?a:r.indexOf("<hierarchy");if(i<0)return null;let n=r.lastIndexOf("</hierarchy>");if(n<0||n<i)return null;let o=r.slice(i,n+12).trim();return o.length>0?o:null}function a4(e){if(!(e instanceof w)||"COMMAND_FAILED"!==e.code)return!1;let t=`${e.details?.stderr??""}`.toLowerCase();return!!(t.includes("device offline")||t.includes("device not found")||t.includes("transport error")||t.includes("connection reset")||t.includes("broken pipe")||t.includes("timed out")||t.includes("no such file or directory"))}async function a8(e,t,r){await c("adb",rN(e,["shell","input","tap",String(t),String(r)]))}async function a6(e,t,r,a,i,n=250){await c("adb",rN(e,["shell","input","swipe",String(t),String(r),String(a),String(i),String(n)]))}async function a5(e){await c("adb",rN(e,["shell","input","keyevent","4"]))}async function a9(e){await c("adb",rN(e,["shell","input","keyevent","3"]))}async function a7(e){await c("adb",rN(e,["shell","input","keyevent","187"]))}async function ie(e,t,r,a=800){await c("adb",rN(e,["shell","input","swipe",String(t),String(r),String(t),String(r),String(a)]))}async function it(e,t){let r=id(t);if(!r||"ok"!==await iu(e,t))try{let r=t.replace(/ /g,"%s");await c("adb",rN(e,["shell","input","text",r]))}catch(e){if(r&&function(e){if(!(e instanceof w)||"COMMAND_FAILED"!==e.code)return!1;let t=String(e.details?.stderr??"").toLowerCase();return!!(t.includes("exception occurred while executing 'text'")||t.includes("nullpointerexception")&&t.includes("inputshellcommand.sendtext"))}(e))throw new w("COMMAND_FAILED","Non-ASCII text input is not supported on this Android shell. Install an ADB keyboard IME or use ASCII input.",{textPreview:t.slice(0,32)},e instanceof Error?e:void 0);throw e}}async function ir(e,t,r){await a8(e,t,r)}async function ia(e,t,r,a){let i=Array.from(a).length,n=id(a),o=[{strategy:"input_text",clearPadding:12,minClear:8,maxClear:48}];n||(o.push({strategy:"clipboard_paste",clearPadding:12,minClear:8,maxClear:48}),o.push({strategy:"chunked_input",clearPadding:24,minClear:16,maxClear:96}));let s=null;for(let n of o){var l,d;await ir(e,t,r);let o=(l=i+n.clearPadding,d=n.minClear,Math.max(d,Math.min(n.maxClear,l)));if(await ic(e,o),"input_text"===n.strategy)await it(e,a);else if("clipboard_paste"===n.strategy){if("ok"!==await iu(e,a))continue}else await il(e,a,1,15);if((s=await ip(e,t,r))===a)return}throw new w("COMMAND_FAILED","Android fill verification failed",{expected:a,actual:s??null})}async function ii(e,t,r=.6){let{width:a,height:i}=await is(e),n=Math.floor(a*r),o=Math.floor(i*r),s=Math.floor(a/2),l=Math.floor(i/2),d=s,u=l,p=s,f=l;switch(t){case"up":u=l-Math.floor(o/2),f=l+Math.floor(o/2);break;case"down":u=l+Math.floor(o/2),f=l-Math.floor(o/2);break;case"left":d=s-Math.floor(n/2),p=s+Math.floor(n/2);break;case"right":d=s+Math.floor(n/2),p=s-Math.floor(n/2);break;default:throw new w("INVALID_ARGS",`Unknown direction: ${t}`)}await c("adb",rN(e,["shell","input","swipe",String(d),String(u),String(p),String(f),"300"]))}async function io(e,t){for(let r=0;r<8;r+=1){let r="";try{r=await a1(e)}catch(t){let e=t instanceof Error?t.message:String(t);throw new w("UNSUPPORTED_OPERATION",`uiautomator dump failed: ${e}`)}if(function(e,t){let r=t.toLowerCase(),a=/<node[^>]+>/g,i=a.exec(e);for(;i;){let t=aK(i[0]),n=(aX(t,"text")??"").toLowerCase(),o=(aX(t,"content-desc")??"").toLowerCase();if(n.includes(r)||o.includes(r)){let e=aZ(aX(t,"bounds"));if(e)return{x:Math.floor(e.x+e.width/2),y:Math.floor(e.y+e.height/2)};return{x:0,y:0}}i=a.exec(e)}return null}(r,t))return;await ii(e,"down",.5)}throw new w("COMMAND_FAILED",`Could not find element containing "${t}" after scrolling`)}async function is(e){let t=(await c("adb",rN(e,["shell","wm","size"]))).stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(!t)throw new w("COMMAND_FAILED","Unable to read screen size");return{width:Number(t[1]),height:Number(t[2])}}async function il(e,t,r,a){let i=Math.max(1,Math.floor(r)),n=Array.from(t);for(let t=0;t<n.length;t+=i){let r=n.slice(t,t+i).join("");await it(e,r),a>0&&t+i<n.length&&await rE(a)}}function id(e){for(let t of e){let e=t.codePointAt(0);if(void 0!==e&&(e<32||e>126))return!0}return!1}async function iu(e,t){let r=await c("adb",rN(e,["shell","cmd","clipboard","set","text",t]),{allowFailure:!0});return 0!==r.exitCode?"failed":rD(r.stdout,r.stderr)?"unsupported":0===(await c("adb",rN(e,["shell","input","keyevent","KEYCODE_PASTE"]),{allowFailure:!0})).exitCode||0===(await c("adb",rN(e,["shell","input","keyevent","279"]),{allowFailure:!0})).exitCode?"ok":"failed"}async function ic(e,t){let r=Math.max(0,t);await c("adb",rN(e,["shell","input","keyevent","KEYCODE_MOVE_END"]),{allowFailure:!0});for(let t=0;t<r;t+=24){let a=Math.min(24,r-t);await c("adb",rN(e,["shell","input","keyevent",...Array(a).fill("KEYCODE_DEL")]),{allowFailure:!0})}}async function ip(e,t,r){let a,i=await a1(e),n=/<node\b[^>]*>/g,o=null,s=null,l=null;for(;null!==(a=n.exec(i));){let e=aJ(a[0]),i=aZ(e.bounds);if(!i)continue;let n=e.className??"",d=(e.text??"").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),u=e.focused??!1;if(!d)continue;let c=Math.max(1,i.width*i.height),p=t>=i.x&&t<=i.x+i.width&&r>=i.y&&r<=i.y+i.height;if(u&&im(n)){(!o||c<=o.area)&&(o={text:d,area:c});continue}if(p&&im(n)){(!s||c<=s.area)&&(s={text:d,area:c});continue}p&&(!l||c<=l.area)&&(l={text:d,area:c})}return o?.text??s?.text??l?.text??null}function im(e){let t=e.toLowerCase();return t.includes("edittext")||t.includes("textfield")}async function ih(e){let t=await c("adb",rN(e,["shell","dumpsys","input_method"]),{allowFailure:!0});if(0!==t.exitCode)throw new w("COMMAND_FAILED","Failed to query Android keyboard state",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});return function(e){let t=function(e){let t=new Map;for(let r of e.matchAll(/\b(mInputShown|mIsInputViewShown|isInputViewShown)=([a-zA-Z]+)\b/g)){let e=r[1],a=r[2]?.toLowerCase();e&&("true"===a||"false"===a)&&t.set(e,"true"===a)}if(0===t.size)return null;for(let e of t.values())if(e)return!0;return!1}(e),r=t??!1;if(null===t){let t=e.match(/\bmImeWindowVis=0x([0-9a-fA-F]+)\b/);if(t?.[1]){let e=Number.parseInt(t[1],16);Number.isNaN(e)||(r=(1&e)!=0)}}let a=Array.from(e.matchAll(/\binputType=0x([0-9a-fA-F]+)\b/gi)),i=a.length>0?a[a.length-1]?.[1]:void 0,n=i?`0x${i.toLowerCase()}`:void 0;return{visible:r,inputType:n,type:n?function(e){let t=Number.parseInt(e.replace(/^0x/i,""),16);if(Number.isNaN(t))return"unknown";let r=15&t;if(2===r)return"number";if(3===r)return"phone";if(4===r)return"datetime";if(1!==r)return"unknown";let a=4080&t;return 32===a||208===a?"email":128===a||224===a||144===a?"password":"text"}(n):void 0}}(t.stdout)}async function iw(e){let t=await ih(e),r=t,a=0;for(;r.visible&&a<2;)await a5(e),a+=1,await rE(120),r=await ih(e);return{attempts:a,wasVisible:t.visible,dismissed:t.visible&&!r.visible,visible:r.visible,inputType:r.inputType,type:r.type}}async function ig(e){let t,r;return(r=(t=(await iA(e,["shell","cmd","clipboard","get","text"],"read")).replace(/\r\n/g,"\n").replace(/\n$/,"")).match(/^clipboard text:\s*(.*)$/i))?r[1]??"":"null"===t.trim().toLowerCase()?"":t}async function iI(e,t){await iA(e,["shell","cmd","clipboard","set","text",t],"write")}async function iA(e,t,r){let a=await c("adb",rN(e,t),{allowFailure:!0});if(rD(a.stdout,a.stderr))throw new w("UNSUPPORTED_OPERATION",`Android shell clipboard ${r} is not supported on this device.`);if(0!==a.exitCode)throw new w("COMMAND_FAILED",`Failed to ${r} Android clipboard text`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return a.stdout}let iv=["camera","microphone","photos","contacts","contacts-limited","notifications","calendar","location","location-always","media-library","motion","reminders","siri"];function iy(e){let t=e.trim().toLowerCase();if("grant"===t)return"grant";if("deny"===t)return"deny";if("reset"===t)return"reset";throw new w("INVALID_ARGS",`Invalid permission action: ${e}. Use grant|deny|reset.`)}function ib(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 w("INVALID_ARGS",`permission setting requires a target: ${iv.join("|")}`)}function iS(e){let t=e.trim().toLowerCase();if("light"===t)return"light";if("dark"===t)return"dark";if("toggle"===t)return"toggle";throw new w("INVALID_ARGS",`Invalid appearance state: ${e}. Use light|dark|toggle.`)}async function iN(e,t,r,a,i){switch(t.toLowerCase()){case"wifi":{let t=iD(r);await c("adb",rN(e,["shell","svc","wifi",t?"enable":"disable"]));return}case"airplane":{let t=iD(r);await c("adb",rN(e,["shell","settings","put","global","airplane_mode_on",t?"1":"0"])),await c("adb",rN(e,["shell","am","broadcast","-a","android.intent.action.AIRPLANE_MODE","--ez","state",t?"true":"false"]));return}case"location":{let t=iD(r);await c("adb",rN(e,["shell","settings","put","secure","location_mode",t?"3":"0"]));return}case"appearance":{let t=await iE(e,r);await c("adb",rN(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 w("INVALID_ARGS",`Invalid fingerprint state: ${e}. Use match|nonmatch.`)}(r);await i_(e,t);return}case"permission":{if(!a)throw new w("INVALID_ARGS","permission setting requires an active app in session");let t=iy(r),n=function(e,t){let r=ib(e);if(t?.trim())throw new w("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 w("INVALID_ARGS",`Unsupported permission target on Android: ${e}. Use camera|microphone|photos|contacts|notifications.`)}(i?.permissionTarget,i?.permissionMode);if("notifications"===n.kind)return void await iL(e,a,t,n);let o="grant"===t?"grant":"revoke";if("photos"===n.type)return void await ik(e,a,o);await c("adb",rN(e,["shell","pm",o,a,n.value]));return}default:throw new w("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function i_(e,t){var r;let a,i,n=(r=e,i=[["shell","cmd","fingerprint","touch",a="match"===t?"1":"9999"],["shell","cmd","fingerprint","finger",a]],"emulator"===r.kind&&i.push(["emu","finger","touch",a]),i),o=[];for(let t of n){let r=await c("adb",rN(e,t),{allowFailure:!0});if(0===r.exitCode)return;o.push({args:t,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}let s=o.map(e=>({args:e.args.join(" "),exitCode:e.exitCode,stderr:e.stderr.slice(0,400)}));if(o.length>0&&o.every(e=>{var t,r;let a;return t=e.stdout,r=e.stderr,(a=`${t}
16
- ${r}`.toLowerCase()).includes("unknown command")||a.includes("can't find service: fingerprint")||a.includes("service fingerprint was not found")||a.includes("fingerprint cmd unavailable")||a.includes("emu command is not supported")||a.includes("emulator console is not running")||a.includes("fingerprint")&&a.includes("not found")}))throw new w("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 w("COMMAND_FAILED","Failed to simulate Android fingerprint.",{deviceId:e.id,action:t,attempts:s})}function iD(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 w("INVALID_ARGS",`Invalid setting state: ${e}`)}async function iE(e,t){let r=iS(t);if("toggle"!==r)return r;let a=await c("adb",rN(e,["shell","cmd","uimode","night"]),{allowFailure:!0});if(0!==a.exitCode)throw new w("COMMAND_FAILED","Failed to read current Android appearance",{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});let i=function(e,t){let r=/night mode:\s*(yes|no|auto)\b/i.exec(`${e}
17
- ${t}`);if(!r)return null;let a=r[1].toLowerCase();return"yes"===a?"dark":"no"===a?"light":"auto"===a?"auto":null}(a.stdout,a.stderr);if(!i)throw new w("COMMAND_FAILED","Unable to determine current Android appearance for toggle",{stdout:a.stdout,stderr:a.stderr});return"auto"===i?"dark":"dark"===i?"light":"dark"}async function ik(e,t,r){let a=await iO(e),i=[];for(let n of null!==a&&a>=33?["android.permission.READ_MEDIA_IMAGES","android.permission.READ_EXTERNAL_STORAGE"]:["android.permission.READ_EXTERNAL_STORAGE","android.permission.READ_MEDIA_IMAGES"]){let a=await c("adb",rN(e,["shell","pm",r,t,n]),{allowFailure:!0});if(0===a.exitCode)return;i.push({permission:n,stderr:a.stderr,exitCode:a.exitCode})}throw new w("COMMAND_FAILED",`Failed to ${r} Android photos permission`,{appPackage:t,sdkInt:a,attempts:i})}async function iL(e,t,r,a){"grant"===r?await c("adb",rN(e,["shell","pm","grant",t,a.permission]),{allowFailure:!0}):(await c("adb",rN(e,["shell","pm","revoke",t,a.permission]),{allowFailure:!0}),"reset"===r&&(await c("adb",rN(e,["shell","pm","clear-permission-flags",t,a.permission,"user-set"]),{allowFailure:!0}),await c("adb",rN(e,["shell","pm","clear-permission-flags",t,a.permission,"user-fixed"]),{allowFailure:!0}))),await c("adb",rN(e,["shell","appops","set",t,a.appOps,"grant"===r?"allow":"deny"===r?"deny":"default"]))}async function iO(e){let t=await c("adb",rN(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}async function ix(e,t,r){let a="string"==typeof r.action&&r.action.trim()?r.action.trim():`${t}.TEST_PUSH`,i=["shell","am","broadcast","-a",a,"-p",t],n="string"==typeof r.receiver?r.receiver.trim():"";n&&i.push("-n",n);let o=r.extras;if(void 0!==o&&("object"!=typeof o||null===o||Array.isArray(o)))throw new w("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 w("INVALID_ARGS",`Unsupported Android broadcast extra type for "${t}". Use string, boolean, or number.`)}(i,e,t),s+=1);return await c("adb",rN(e,i)),{action:a,extrasCount:s}}let iM=Buffer.from([137,80,78,71,13,10,26,10]),iC={enableDemoMode:iP,settle:rE,capture:i$,disableDemoMode:iT};async function iR(e,t,r=iC){await r.enableDemoMode(e);try{await r.settle(1e3),await r.capture(e,t)}finally{await r.disableDemoMode(e).catch(()=>{})}}async function iP(e){let t=t=>c("adb",rN(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 iT(e){await c("adb",rN(e,["shell","am broadcast -a com.android.systemui.demo -e command exit"]),{allowFailure:!0})}async function i$(e,t){let r=await c("adb",rN(e,["exec-out","screencap","-p"]),{binaryStdout:!0});if(!r.stdoutBuffer)throw new w("COMMAND_FAILED","Failed to capture screenshot");let a=r.stdoutBuffer.indexOf(iM);if(a<0)throw new w("COMMAND_FAILED","Screenshot data does not contain a valid PNG header");let i=function(e,t){let r=t+iM.length;for(;r+8<=e.length;){let t=e.readUInt32BE(r),a=r+4,i=e.toString("ascii",a,a+4),n=r+12+t;if(n>e.length)break;if("IEND"===i)return n;r=n}return null}(r.stdoutBuffer,a);if(!i)throw new w("COMMAND_FAILED","Screenshot data does not contain a complete PNG payload");await O.writeFile(t,r.stdoutBuffer.subarray(a,i))}let iF=eb(process.env.AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS,Y,5e3),iU=eb(process.env.AGENT_DEVICE_IOS_SIMCTL_LIST_TIMEOUT_MS,Z,1e3),iV=eb(process.env.AGENT_DEVICE_IOS_APP_LAUNCH_TIMEOUT_MS,3e4,5e3),iG=eb(process.env.AGENT_DEVICE_IOS_DEVICECTL_TIMEOUT_MS,2e4,1e3),iB=eb(process.env.AGENT_DEVICE_IOS_SIMULATOR_FOCUS_TIMEOUT_MS,1e4,1e3),ij=eb(process.env.AGENT_DEVICE_IOS_SIMULATOR_SCREENSHOT_TIMEOUT_MS,2e4,1e3),iq=eb(process.env.AGENT_DEVICE_IOS_RUNNER_SCREENSHOT_COPY_TIMEOUT_MS,2e4,1e3);async function iH(e,t){let r=["devicectl",...e],a=await c("xcrun",r,{allowFailure:!0,timeoutMs:iG});if(0===a.exitCode)return;let i=String(a.stdout??""),n=String(a.stderr??"");throw new w("COMMAND_FAILED",`Failed to ${t.action}`,{cmd:"xcrun",args:r,exitCode:a.exitCode,stdout:i,stderr:n,deviceId:t.deviceId,hint:iK(i,n)??iJ})}async function iW(e,t){let r=i.join(T.tmpdir(),`agent-device-ios-apps-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),a=["devicectl","device","info","apps","--device",e.id,"--include-all-apps","--json-output",r],n=await c("xcrun",a,{allowFailure:!0,timeoutMs:iG});try{var o,s;if(0!==n.exitCode){let t=String(n.stdout??""),r=String(n.stderr??"");throw new w("COMMAND_FAILED","Failed to list iOS apps",{cmd:"xcrun",args:a,exitCode:n.exitCode,stdout:t,stderr:r,deviceId:e.id,hint:iK(t,r)??iJ})}let i=await O.readFile(r,"utf8");return o=iz(JSON.parse(i)),s=t,"user-installed"===s?o.filter(e=>!e.bundleId.startsWith("com.apple.")):o}catch(t){if(t instanceof w)throw t;throw new w("COMMAND_FAILED","Failed to parse iOS apps list",{deviceId:e.id,cause:String(t)})}finally{await O.unlink(r).catch(()=>{})}}function iz(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 a="string"==typeof e.name&&e.name.trim().length>0?e.name.trim():t;r.push({bundleId:t,name:a})}return r}let iJ="Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.";function iK(e,t){let r=`${e}
18
- ${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}function iX(e){if(!(e instanceof w)||"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 iZ(e,t){let r=await c("xcrun",ex(e,["get_app_container",e.id,t]),{allowFailure:!0});if(0!==r.exitCode)return{installed:!1};let a=r.stdout.trim();if(!a)return{installed:!1};let i=await c("plutil",["-extract","CFBundleExecutable","raw","-o","-",`${a}/Info.plist`],{allowFailure:!0});if(0!==i.exitCode||!i.stdout.trim())return{installed:!0};let n=i.stdout.trim(),o=`${a}/${n}`,s=await c("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 iY(e,t){if("simulator"!==e.kind)throw new w("UNSUPPORTED_OPERATION",`${t} is only supported on iOS simulators`)}async function iQ(){await c("open",["-a","Simulator"],{allowFailure:!0,timeoutMs:iB})}async function i0(e){let t,r;if("simulator"!==e.kind||"Booted"===await i2(e))return;let a=ee.fromTimeoutMs(iF);try{await et(async({deadline:a})=>{if(a?.isExpired())throw new w("COMMAND_FAILED","iOS simulator boot deadline exceeded",{timeoutMs:iF});let i=Math.max(1e3,a?.remainingMs()??iF),n=await c("xcrun",ex(e,["boot",e.id]),{allowFailure:!0,timeoutMs:i});t={stdout:String(n.stdout??""),stderr:String(n.stderr??""),exitCode:n.exitCode};let o=`${t.stdout}
19
- ${t.stderr}`.toLowerCase(),s=o.includes("already booted")||o.includes("current state: booted");if(0!==t.exitCode&&!s)throw new w("COMMAND_FAILED","simctl boot failed",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let l=await c("xcrun",ex(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 w("COMMAND_FAILED","simctl bootstatus failed",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});let d=await i2(e);if("Booted"!==d)throw new w("COMMAND_FAILED","Simulator is still booting",{state:d})},{maxAttempts:3,baseDelayMs:500,maxDelayMs:2e3,jitter:.2,shouldRetry:e=>{let a=ew({error:e,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});return"IOS_BOOT_TIMEOUT"!==a&&"CI_RESOURCE_STARVATION_SUSPECTED"!==a}},{deadline:a,phase:"boot",classifyReason:e=>ew({error:e,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}})})}catch(n){let i=ew({error:n,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});throw new w("COMMAND_FAILED","iOS simulator failed to boot",{platform:"ios",deviceId:e.id,timeoutMs:iF,elapsedMs:a.elapsedMs(),reason:i,hint:eg(i),boot:t,bootstatus:r})}}async function i1(e){let t=ex(e,["shutdown",e.id]),r=await c("xcrun",t,{allowFailure:!0,timeoutMs:15e3});return{success:0===r.exitCode,exitCode:r.exitCode,stdout:String(r.stdout??""),stderr:String(r.stderr??"")}}async function i2(e){let t="string"==typeof e?e:e.id,r="string"==typeof e?eO(["list","devices","-j"]):ex(e,["list","devices","-j"]),a=await c("xcrun",r,{allowFailure:!0,timeoutMs:iU});if(0!==a.exitCode)return null;try{let e=JSON.parse(String(a.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 i3(e,t){try{let r=await c("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{let r=await O.readFile(e,"utf8");return function(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=e.match(RegExp(`<key>\\s*${r}\\s*<\\/key>\\s*<string>([\\s\\S]*?)<\\/string>`,"i"));if(!a?.[1])return;let i=a[1].trim().replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&amp;/g,"&");return i.length>0?i:void 0}(r,t)}catch{return}}async function i4(e,t){if("url"===e.kind&&!aa(e.url))throw new w("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 r=await r7({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||aa(e.url),signal:t?.signal}),a=await i6(r.installablePath,t),i=await i8(a.installPath);return{archivePath:r.archivePath??(r.installablePath.toLowerCase().endsWith(".ipa")?r.installablePath:void 0),installablePath:a.installPath,bundleId:i.bundleId,appName:i.appName,cleanup:async()=>{await a.cleanup(),await r.cleanup()}}}async function i8(e){let t=i.join(e,"Info.plist"),[r,a,n]=await Promise.all([i3(t,"CFBundleIdentifier"),i3(t,"CFBundleDisplayName"),i3(t,"CFBundleName")]);return{bundleId:r,appName:a??n}}async function i6(e,t){if(!e.toLowerCase().endsWith(".ipa"))return{installPath:e,cleanup:async()=>{}};let r=await O.mkdtemp(i.join(T.tmpdir(),"agent-device-ios-ipa-")),a=async()=>{await O.rm(r,{recursive:!0,force:!0})};try{await c("ditto",["-x","-k",e,r]);let n=i.join(r,"Payload"),o=(await O.readdir(n,{withFileTypes:!0}).catch(()=>{throw new w("INVALID_ARGS","Invalid IPA: missing Payload directory")})).filter(e=>e.isDirectory()&&e.name.toLowerCase().endsWith(".app")).map(e=>({installPath:i.join(n,e.name),bundleName:e.name.replace(/\.app$/i,"")}));if(1===o.length)return{installPath:o[0].installPath,cleanup:a};if(0===o.length)throw new w("INVALID_ARGS","Invalid IPA: expected at least one .app under Payload, found 0");await i5(o);let s=t?.appIdentifierHint?.trim();if(s){let e=function(e,t){let r=t.toLowerCase(),a=e.filter(e=>e.bundleName.toLowerCase()===r);if(1===a.length)return a[0];if(a.length>1)throw new w("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]}}(o,s);if(e)return{installPath:e.installPath,cleanup:a};throw new w("INVALID_ARGS",`Invalid IPA: found ${o.length} .app bundles under Payload and none matched "${s}". Available bundles: ${o.map(i9).join(", ")}`)}throw new w("INVALID_ARGS",`Invalid IPA: found ${o.length} .app bundles under Payload. Pass an app identifier or bundle name matching one of: ${o.map(i9).join(", ")}`)}catch(e){throw await a(),e}}async function i5(e){await Promise.all(e.map(async e=>{if(e.bundleId&&e.appName)return;let t=await i8(e.installPath);e.bundleId=e.bundleId??t.bundleId,e.appName=e.appName??t.appName}))}function i9(e){let t=e.bundleId??e.appName;return t?`${e.bundleName}.app (${t})`:`${e.bundleName}.app`}function i7(e,t){return"user-installed"===t?e.filter(e=>!e.bundleId.startsWith("com.apple.")):e}let ne={settings:"com.apple.systempreferences"},nt=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/;function nr(e){return e.replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/"/g,'\\"')}function na(e,t){let r=["-b",e];return t&&r.push(t),r}async function ni(e){for(let t of[i.join(e,"Contents","Info.plist"),i.join(e,"Info.plist")]){let[e,r,a]=await Promise.all([i3(t,"CFBundleIdentifier"),i3(t,"CFBundleDisplayName"),i3(t,"CFBundleName")]);if(e||r||a)return{bundleId:e,appName:r??a}}return{}}async function nn(e){let t=e.trim(),r=ne[t.toLowerCase()];if(r)return r;let a=`id of app "${nr(t)}"`,i=await c("osascript",["-e",a],{allowFailure:!0});if(0===i.exitCode){let e=i.stdout.trim();if(e)return e}let n=(await np("all")).filter(e=>e.name.toLowerCase()===t.toLowerCase());if(1===n.length)return n[0].bundleId;if(n.length>1)throw new w("INVALID_ARGS",`Multiple apps matched "${e}"`,{matches:n});if(nt.test(t))return t;throw new w("APP_NOT_INSTALLED",`No app found matching "${e}"`)}async function no(e,t,r){let a=r?.url?.trim();if(a){if(!rk(a))throw new w("INVALID_ARGS","open <app> <url> requires a valid URL target");let e=r?.appBundleId??await nn(t);await c("open",na(e,a));return}let i=t.trim();if(rk(i))return void await c("open",[i]);let n=r?.appBundleId??await nn(i);await c("open",na(n))}async function ns(e,t){let r=await nn(t),a=`tell application id "${nr(r)}" to quit`,i=await c("osascript",["-e",a],{allowFailure:!0});if(0===i.exitCode)return;let n=`${i.stdout}
20
- ${i.stderr}`.toLowerCase();if(!(n.includes("isn’t running")||n.includes("isn't running")))throw new w("COMMAND_FAILED",`Failed to close macOS app ${t}`,{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode})}async function nl(){let e=await c("pbpaste",[],{allowFailure:!0});if(0!==e.exitCode)throw new w("COMMAND_FAILED","Failed to read macOS clipboard",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode});return e.stdout.replace(/\r\n/g,"\n").replace(/\n$/,"")}async function nd(e){let t=await c("pbcopy",[],{allowFailure:!0,stdin:e});if(0!==t.exitCode)throw new w("COMMAND_FAILED","Failed to write macOS clipboard",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode})}async function nu(){let e=await c("osascript",["-e",'tell application "System Events" to tell appearance preferences to get dark mode'],{allowFailure:!0});if(0!==e.exitCode)throw new w("COMMAND_FAILED","Failed to read macOS appearance",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode});let t=e.stdout.trim().toLowerCase();if("true"===t)return!0;if("false"===t)return!1;throw new w("COMMAND_FAILED",`Unable to determine current macOS appearance from osascript output: ${e.stdout.trim()}`)}async function nc(e){let t=iS(e),r="toggle"===t?!await nu():"dark"===t,a=`tell application "System Events" to tell appearance preferences to set dark mode to ${r?"true":"false"}`,i=await c("osascript",["-e",a],{allowFailure:!0});if(0!==i.exitCode)throw new w("COMMAND_FAILED","Failed to set macOS appearance",{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode})}async function np(e="all"){let t=["/Applications","/System/Applications",i.join(T.homedir(),"Applications")],r=new Set;for(let e of t){let t=await O.stat(e).catch(()=>null);if(!t?.isDirectory())continue;let a=await c("find",[e,"-maxdepth","4","-type","d","-name","*.app"],{allowFailure:!0});if(0===a.exitCode)for(let e of a.stdout.split("\n")){let t=e.trim();t&&r.add(t)}}return i7((await Promise.all(Array.from(r).map(async e=>{let t=await ni(e).catch(()=>({})),r=t.bundleId;return r?{bundleId:r,name:t.appName??i.basename(e,".app")}:null}))).filter(e=>null!==e).sort((e,t)=>e.name.localeCompare(t.name)),e)}let nf=["--time","9:41","--dataNetwork","wifi","--wifiMode","active","--wifiBars","3","--batteryState","charged","--batteryLevel","100"],nm={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"},nh={1:"searching",2:"failed",3:"active"},nw={0:"notSupported",1:"searching",2:"failed",3:"active"};function ng(e,t,r){return c("xcrun",ex(e,t),r)}async function nI(e,t){var r,a;let i;await nv(e),t&&await ny(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||(a=r.dataNetwork)&&"hide"!==a&&"wifi"!==a||void 0!==r.operatorName)&&i.push("--cellularBars",r.cellularBars),void 0!==r.operatorName&&i.push("--operatorName",r.operatorName),i))}async function nA(e){let t=await ng(e,["status_bar",e.id,"list"],{allowFailure:!0});if(0!==t.exitCode)throw new w("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]),a=nm[r];if(!a)throw new w("COMMAND_FAILED",`Unsupported simulator data network type: ${r}`);t.dataNetwork=a;continue}let a=/^WiFi Mode:\s+(\d+),\s+WiFi Bars:\s+(\d+)$/.exec(r);if(a){let e=nh[Number(a[1])];e&&(t.wifiMode=e),t.wifiBars=a[2];continue}let i=/^Cell Mode:\s+(\d+),\s+Cell Bars:\s+(\d+)$/.exec(r);if(i){let e=Number(i[1]),r=nw[e];if(!r)throw new w("COMMAND_FAILED",`Unsupported simulator cellular mode: ${e}`);t.cellularMode=r,t.cellularBars=i[2];continue}let n=/^Operator Name:\s*(.*)$/.exec(r);if(n){t.operatorName=n[1]??"";continue}}return 0===Object.keys(t).length?null:t}(t.stdout)}async function nv(e){await ng(e,["status_bar",e.id,"clear"])}async function ny(e,t){0!==t.length&&await ng(e,["status_bar",e.id,"override",...t])}function nb(e,t,r){L({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...function(e){if(!(e instanceof w))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}}(r)}})}function nS(e,t,r){return c("xcrun",ex(e,t),r)}let nN={ensureBooted:i0,prepareStatusBarForScreenshot:async function e(e){let t=null,r=!1;try{t=await nA(e),r=!0}catch(t){nb(e,"snapshot_failed",t)}try{await nv(e),await ny(e,nf)}catch(t){nb(e,"prepare_failed",t)}return async()=>{await nI(e,r?t:null)}},captureWithRetry:nE,captureWithRunner:nk,shouldFallbackToRunner:nP};async function n_(e,t,r){if("macos"===e.platform)return void await nk(e,t,r);if("simulator"===e.kind)return void await nD(e,t,r);try{await iH(["device","screenshot","--device",e.id,t],{action:"capture iOS screenshot",deviceId:e.id});return}catch(t){if(!function(e){if(!(e instanceof w)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},r="string"==typeof t.stdout?t.stdout:"",a="string"==typeof t.stderr?t.stderr:"",i=`${e.message}
4
+ ${r}`.toLowerCase()).includes("device is busy")&&a.includes("connecting")?"Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.":eS("IOS_RUNNER_CONNECT_TIMEOUT"))})}function eE(e){if(ev(e))throw eA()}function ek(e,t,r){if(!e)return t;let a=Number(e);return Number.isFinite(a)?Math.max(r,Math.floor(a)):t}let eM=["AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET","IOS_SIMULATOR_DEVICE_SET"],ex=["AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST","ANDROID_DEVICE_ALLOWLIST"];function eO(e){return e?.trim()||void 0}function eL(e,t){for(let r of e){let e=eO(t[r]);if(e)return e}}function eC(e,t=process.env){return eO(e)??eL(eM,t)}function eP(e){return new Set(e.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean))}function eR(e,t=process.env){let r=eO(e)??eL(ex,t);if(r)return eP(r)}function eT(e,t={}){let r=eC(t.simulatorSetPath);return r?["simctl","--set",r,...e]:["simctl",...e]}function e$(e,t){return"ios"!==e.platform||"simulator"!==e.kind?["simctl",...t]:eT(t,{simulatorSetPath:e.simulatorSetPath})}let eF=ek(process.env.AGENT_DEVICE_RUNNER_STARTUP_TIMEOUT_MS,45e3,5e3),eU=ek(process.env.AGENT_DEVICE_RUNNER_COMMAND_TIMEOUT_MS,45e3,1e3),eV=ek(process.env.AGENT_DEVICE_RUNNER_CONNECT_ATTEMPT_INTERVAL_MS,250,50),eG=ek(process.env.AGENT_DEVICE_RUNNER_CONNECT_RETRY_BASE_DELAY_MS,300,10),eB=ek(process.env.AGENT_DEVICE_RUNNER_CONNECT_RETRY_MAX_DELAY_MS,2e3,10),ej=ek(process.env.AGENT_DEVICE_RUNNER_CONNECT_REQUEST_TIMEOUT_MS,2e4,250),eq=ek(process.env.AGENT_DEVICE_IOS_DEVICE_INFO_TIMEOUT_MS,1e4,500),eH=ek(process.env.AGENT_DEVICE_RUNNER_DESTINATION_TIMEOUT_SECONDS,20,5);async function eW(e,t,r,a,i=eF,n,o){let s=eo.fromTimeoutMs(i),l=await ez(e,t,s.remainingMs()),d=null,u=Math.max(1,Math.ceil(i/eV));try{return await es(async({deadline:s})=>{if(s?.isExpired())throw new I("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:i});if(n&&null!==n.child.exitCode&&void 0!==n.child.exitCode)throw await eD({session:n,port:t,logPath:a});for(let a of("device"===e.kind&&(l=await ez(e,t,s?.remainingMs())),l))try{let e=s?.remainingMs()??i;if(e<=0)throw new I("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:i});return await eJ(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},Math.min(ej,e),o)}catch(e){if(o?.aborted||ey(e))throw eA();d=e}throw new I("COMMAND_FAILED","Runner endpoint probe failed",{port:t,endpoints:l,lastError:d?String(d):void 0})},{maxAttempts:u,baseDelayMs:eG,maxDelayMs:eB,jitter:.2,shouldRetry:e_},{deadline:s,phase:"ios_runner_connect",signal:o})}catch(e){if(o?.aborted||ey(e))throw eA();d||(d=e)}if(o?.aborted)throw eA();if("simulator"===e.kind){let i=s.remainingMs();if(i<=0)throw eN({port:t,endpoints:l,logPath:a,lastError:d});let n=await eK(e,t,r,i);return new Response(n.body,{status:n.status})}throw eN({port:t,endpoints:l,logPath:a,lastError:d})}async function ez(e,t,r){let a=[`http://127.0.0.1:${t}/command`];if("device"!==e.kind)return a;let i=await eX(e.id,r);return i&&a.unshift(`http://[${i}]:${t}/command`),a}async function eJ(e,t,r,a){let i,n=new AbortController,o=setTimeout(()=>n.abort(),r);a&&(a.aborted?(clearTimeout(o),n.abort()):(i=()=>n.abort(),a.addEventListener("abort",i,{once:!0})));try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(o),i&&a&&a.removeEventListener("abort",i)}}async function eX(e,t){if("number"==typeof t&&t<=0)return null;let r="number"==typeof t?Math.max(1,Math.min(eq,t)):eq,a=o.join(V.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(r/1e3)),i=await m("xcrun",["devicectl","device","info","details","--device",e,"--json-output",a,"--timeout",String(t)],{allowFailure:!0,timeoutMs:r});if(0!==i.exitCode||!F.existsSync(a))return null;let n=JSON.parse(F.readFileSync(a,"utf8"));if(n.info?.outcome&&"success"!==n.info.outcome)return null;let o=(n.result?.connectionProperties?.tunnelIPAddress??n.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return o&&o.length>0?o:null}catch{return null}finally{eQ(a)}}async function eK(e,t,r,a){let i=JSON.stringify(r),n=e$(e,["spawn",e.id,"/usr/bin/curl","-s","-X","POST","-H","Content-Type: application/json","--data",i,`http://127.0.0.1:${t}/command`]),o=await m("xcrun",n,{allowFailure:!0,timeoutMs:a}),s=o.stdout;if(0!==o.exitCode){let e=eb({message:"Runner did not accept connection (simctl spawn)",stdout:o.stdout,stderr:o.stderr,context:{platform:"ios",phase:"connect"}});throw new I("COMMAND_FAILED","Runner did not accept connection (simctl spawn)",{port:t,stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode,reason:e,hint:eS(e)})}return{status:200,body:s}}async function eY(){return await new Promise((e,t)=>{let r=G.createServer();r.listen(0,"127.0.0.1",()=>{let a=r.address();r.close(),"object"==typeof a&&a?.port?e(a.port):t(new I("COMMAND_FAILED","Failed to allocate port"))}),r.on("error",t)})}function eZ(e,t,r,a){t&&F.appendFileSync(t,e),r&&F.appendFileSync(r,e),a&&process.stderr.write(e)}function eQ(e){try{F.existsSync(e)&&F.unlinkSync(e)}catch{}}async function e0(e,t,r){let a=(e.get(t)??Promise.resolve()).catch(()=>{}).then(r);return e.set(t,a),a.finally(()=>{e.get(t)===a&&e.delete(t)})}function e1(e){return"apple"===e||"ios"===e||"macos"===e}function e2(e,t){return!t||("apple"===t?e1(e):e===t)}function e3(e){let{simulatorSetPath:t,platform:r,target:a}=e;if(t&&"macos"!==r&&"desktop"!==a)return t}async function e4(e,t,r={}){let a=e,i=e=>e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim();if(t.platform&&(a=a.filter(e=>e2(e.platform,t.platform))),t.target&&(a=a.filter(e=>(e.target??"mobile")===t.target)),t.udid){let e=a.find(e=>e.id===t.udid&&e1(e.platform));if(!e)throw new I("DEVICE_NOT_FOUND",`No Apple device with UDID ${t.udid}`);return e}if(t.serial){let e=a.find(e=>e.id===t.serial&&"android"===e.platform);if(!e)throw new I("DEVICE_NOT_FOUND",`No Android device with serial ${t.serial}`);return e}if(t.deviceName){let e=i(t.deviceName),r=a.find(t=>i(t.name)===e);if(!r)throw new I("DEVICE_NOT_FOUND",`No device named ${t.deviceName}`);return r}if(1===a.length)return a[0];if(0===a.length){var n;let e=r.simulatorSetPath;if(e&&(!(n=t.platform)||"apple"===n||"ios"===n))throw new I("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:
5
+ xcrun simctl --set "${e}" create "iPhone 16" com.apple.CoreSimulator.SimDeviceType.iPhone-16 com.apple.CoreSimulator.SimRuntime.iOS-18-0`,selector:t});throw new I("DEVICE_NOT_FOUND","No devices found",{selector:t})}let o=a.filter(e=>"device"!==e.kind);o.length>0&&(a=o);let s=a.filter(e=>e.booted);return 1===s.length?s[0]:s[0]??a[0]}let e8=new Set(["RUNNER_PRODUCT_MISSING","RUNNER_PRODUCT_REPAIR_FAILED"]);async function e5(e,t,r){if("macos"!==e.platform)return;if(0===t.length)throw new I("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",xctestrunPath:r});let a=Array.from(new Set(t)).sort((e,t)=>t.length-e.length);for(let e of a)if(!F.existsSync(e))throw new I("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",productPath:e,xctestrunPath:r});for(let e of a)if(0!==x("codesign",["--verify","--deep","--strict",e],{allowFailure:!0}).exitCode){await m("codesign",["--remove-signature",e],{allowFailure:!0});try{await m("codesign",["--force","--sign","-",e])}catch(a){let t=a instanceof I?a:new I("COMMAND_FAILED",String(a));throw new I("COMMAND_FAILED","Failed to repair macOS runner product signature",{reason:"RUNNER_PRODUCT_REPAIR_FAILED",productPath:e,xctestrunPath:r,error:t.message,details:t.details})}}}let e6=o.join(V.homedir(),".agent-device","ios-runner"),e9=new Map,e7=new Set;function te(e){return e?.trim()??""}function tt(e=process.env){return te(e.AGENT_DEVICE_IOS_BUNDLE_ID)||te(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||"com.callstack.agentdevice.runner"}function tr(e=process.env){let t=te(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID);return t||`${tt(e)}.uitests`}let ta=function(e=process.env){let t=tt(e),r=tr(e);return Array.from(new Set([te(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${r}.xctrunner`,t].filter(e=>e.length>0)))}(process.env),ti={findProjectRoot:function(){let e=o.dirname(b(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=o.join(t,"package.json");if(F.existsSync(e))return t;t=o.dirname(t)}return e},findXctestrun:function(e,t){if(!F.existsSync(e))return null;let r=[],a=[e];for(;a.length>0;){let e=a.pop();for(let t of F.readdirSync(e,{withFileTypes:!0})){let i=o.join(e,t.name);if(t.isDirectory()){a.push(i);continue}if(t.isFile()&&t.name.endsWith(".xctestrun"))try{let e=F.statSync(i);r.push({path:i,mtimeMs:e.mtimeMs})}catch{}}}return 0===r.length?null:(r.sort((e,r)=>{if(t){let a=ts(r.path,t)-ts(e.path,t);if(0!==a)return a}return r.mtimeMs-e.mtimeMs||e.path.localeCompare(r.path)}),r[0]?.path??null)},xctestrunReferencesProjectRoot:function(e,t){try{let r=F.readFileSync(e,"utf8"),a=new Set([t]);try{a.add(F.realpathSync(t))}catch{}for(let e of a)if(r.includes(e))return!0;return!1}catch{return!1}},resolveExistingXctestrunProductPaths:function(e){let t=function(e){let t=function(e){try{let t=x("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==t.exitCode||!t.stdout.trim())return null;return JSON.parse(t.stdout)}catch{return null}}(e);if(t){var r,a=t;let e=new Set,i=t=>{if(t&&"object"==typeof t)for(let r of function(e){let t=new Set(["ProductPaths","DependentProductPaths","TestHostPath","TestBundlePath","UITargetAppPath"]),r=new Set;for(let[a,i]of Object.entries(e))if(t.has(a)){if("string"==typeof i){r.add(i);continue}if(Array.isArray(i))for(let e of i)"string"==typeof e&&r.add(e)}return Array.from(r)}(t))e.add(r)};i(a);let n=a.TestConfigurations;if(Array.isArray(n))for(let e of n){if(!e||"object"!=typeof e)continue;let t=e.TestTargets;if(Array.isArray(t))for(let e of t)i(e)}for(let e of Object.values(a))e&&"object"==typeof e&&"TestBundlePath"in e&&i(e);return Array.from(e)}if("darwin"===process.platform)return null;try{return r=F.readFileSync(e,"utf8"),Array.from(new Set([...["ProductPaths","DependentProductPaths"].flatMap(e=>(function(e,t){let r,a=RegExp(`<key>${t}</key>\\s*<array>([\\s\\S]*?)</array>`,"g"),i=/<string>([\s\S]*?)<\/string>/g,n=new Set;for(;null!==(r=a.exec(e));){let e,t=r[1]??"";for(;null!==(e=i.exec(t));){let t=e[1]?.trim();t&&n.add(t)}}return Array.from(n)})(r,e)),...["TestHostPath","TestBundlePath","UITargetAppPath"].flatMap(e=>(function(e,t){let r,a=RegExp(`<key>${t}</key>\\s*<string>([\\s\\S]*?)</string>`,"g"),i=new Set;for(;null!==(r=a.exec(e));){let e=r[1]?.trim();e&&i.add(e)}return Array.from(i)})(r,e))]))}catch{return null}}(e);if(!t||0===t.length)return null;let r=o.dirname(e),a=new Set,i=new Set,n=[];for(let e of t){if(e.startsWith("__TESTROOT__/")){let t=e.slice(13),n=o.join(r,t);if(!F.existsSync(n))return null;a.add(n);let s=function(e){let t=/\.app(?:\/|$)/.exec(e);return t&&void 0!==t.index?e.slice(0,t.index+4):null}(t);s&&i.add(o.join(r,s));continue}e.startsWith("__TESTHOST__/")&&n.push(e.slice(13))}for(let e of n){let t=Array.from(i).find(t=>F.existsSync(o.join(t,e)));if(!t)return null;a.add(o.join(t,e))}return Array.from(a)},repairRunnerProductsIfNeeded:e5,assertSafeDerivedCleanup:function(e,t=process.env){if(t.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()&&!function(e=process.env){return er(e.AGENT_DEVICE_IOS_ALLOW_OVERRIDE_DERIVED_CLEAN)}(t))throw new I("COMMAND_FAILED","Refusing to clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH automatically",{derivedPath:e,hint:"Unset AGENT_DEVICE_IOS_CLEAN_DERIVED, or set AGENT_DEVICE_IOS_ALLOW_OVERRIDE_DERIVED_CLEAN=1 if you trust this path."})},cleanRunnerDerivedArtifacts:function(e){try{if(!F.existsSync(e))return;if("derived"!==o.basename(e))return void F.rmSync(e,{recursive:!0,force:!0});for(let r of F.readdirSync(e,{withFileTypes:!0})){var t;t=r.name,to.has(t)&&F.rmSync(o.join(e,r.name),{recursive:!0,force:!0})}}catch{}},buildRunnerXctestrun:td};async function tn(e,t,r=ti){var a;let i,n=(a=e,(i=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim())?o.resolve(i):"macos"===a.platform?o.join(e6,"derived","macos"):"simulator"===a.kind?o.join(e6,"derived"):o.join(e6,"derived",a.kind)),s=r.findProjectRoot();return await e0(e9,n,async()=>{er(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)&&(tf("clean","forced_clean",{derived:n}),r.assertSafeDerivedCleanup(n),r.cleanRunnerDerivedArtifacts(n));let a=function(e){let t=e.findXctestrun(e.derived);if(!t)return{reason:"missing_xctestrun",xctestrunPath:null};let r=e.resolveExistingXctestrunProductPaths(t);return r?e.xctestrunReferencesProjectRoot(t,e.projectRoot)?{reason:"reuse_ready",xctestrunPath:t,productPaths:r}:{reason:"project_root_mismatch",xctestrunPath:t,productPaths:r}:{reason:"missing_products",xctestrunPath:t,productPaths:[]}}({derived:n,projectRoot:s,findXctestrun:t=>r.findXctestrun(t,e),xctestrunReferencesProjectRoot:r.xctestrunReferencesProjectRoot,resolveExistingXctestrunProductPaths:r.resolveExistingXctestrunProductPaths});if("reuse_ready"!==a.reason&&tf("rebuild",a.reason,{derived:n,xctestrunPath:a.xctestrunPath}),"reuse_ready"===a.reason)try{return await r.repairRunnerProductsIfNeeded(e,a.productPaths,a.xctestrunPath),tf("reuse","reuse_ready",{derived:n,xctestrunPath:a.xctestrunPath}),a.xctestrunPath}catch(e){if(!function(e){if(!(e instanceof I))return!1;let t=e.details&&"object"==typeof e.details?e.details.reason:void 0;return"string"==typeof t&&e8.has(t)}(e))throw e;tf("rebuild","repair_failed",{derived:n,xctestrunPath:a.xctestrunPath})}a.xctestrunPath&&(r.assertSafeDerivedCleanup(n),r.cleanRunnerDerivedArtifacts(n));let i=o.join(s,"ios-runner","AgentDeviceRunner","AgentDeviceRunner.xcodeproj");if(!F.existsSync(i))throw new I("COMMAND_FAILED","iOS runner project not found",{projectPath:i});await r.buildRunnerXctestrun(e,i,n,t);let l=r.findXctestrun(n,e);if(!l)throw new I("COMMAND_FAILED","Failed to locate .xctestrun after build");let d=r.resolveExistingXctestrunProductPaths(l);if(!d)throw new I("COMMAND_FAILED","Runner build is missing expected products",{xctestrunPath:l});return await r.repairRunnerProductsIfNeeded(e,d,l),tf("build","built_new",{derived:n,xctestrunPath:l}),l})}let to=new Set(["Build","BuildCache.noindex","Index.noindex","Logs","ModuleCache.noindex","SDKStatCaches.noindex","SourcePackages","TextBasedInstallAPI","info.plist"]);function ts(e,t){var r;let a=0,i=e.toLowerCase();o.basename(i).startsWith("agentdevicerunner.env.")&&(a-=1e3),i.includes(`${o.sep}macos${o.sep}`)&&(a-=5e3);let n="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 n.preferred.length>0&&(n.preferred.some(e=>i.includes(e))?a+=2e3:a-=500),n.disallowed.some(e=>i.includes(e))&&(a-=2500),a}async function tl(e,t,r){let a,i=o.dirname(e),n=r.replace(/[^a-zA-Z0-9._-]/g,"_"),s=o.join(i,`AgentDeviceRunner.env.${n}.json`),l=o.join(i,`AgentDeviceRunner.env.${n}.xctestrun`),d=await m("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==d.exitCode||!d.stdout.trim())throw new I("COMMAND_FAILED","Failed to read xctestrun plist",{xctestrunPath:e,stderr:d.stderr});try{a=JSON.parse(d.stdout)}catch(t){throw new I("COMMAND_FAILED","Failed to parse xctestrun JSON",{xctestrunPath:e,error:String(t)})}let u=e=>{e.EnvironmentVariables={...e.EnvironmentVariables??{},...t},e.UITestEnvironmentVariables={...e.UITestEnvironmentVariables??{},...t},e.UITargetAppEnvironmentVariables={...e.UITargetAppEnvironmentVariables??{},...t},e.TestingEnvironmentVariables={...e.TestingEnvironmentVariables??{},...t}},c=a.TestConfigurations;if(Array.isArray(c))for(let e of c){if(!e||"object"!=typeof e)continue;let t=e.TestTargets;if(Array.isArray(t))for(let e of t)e&&"object"==typeof e&&u(e)}for(let[e,t]of Object.entries(a))t&&"object"==typeof t&&t.TestBundlePath&&(u(t),a[e]=t);F.writeFileSync(s,JSON.stringify(a,null,2));let p=await m("plutil",["-convert","xml1","-o",l,s],{allowFailure:!0});if(0!==p.exitCode)throw new I("COMMAND_FAILED","Failed to write xctestrun plist",{tmpXctestrunPath:l,stderr:p.stderr});return{xctestrunPath:l,jsonPath:s}}async function td(e,t,r,a){let i=function(e=process.env){let t=tt(e),r=tr(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${r}`]}(process.env),n=function(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 a=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||"",i=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||"",n=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||"",o=["CODE_SIGN_STYLE=Automatic"];return a&&o.push(`DEVELOPMENT_TEAM=${a}`),i&&o.push(`CODE_SIGN_IDENTITY=${i}`),n&&o.push(`PROVISIONING_PROFILE_SPECIFIER=${n}`),o}(process.env,"device"===e.kind,e.platform),o="device"===e.kind?["-allowProvisioningUpdates"]:[];try{var s;let l;await S("xcodebuild",["build-for-testing","-project",t,"-scheme","AgentDeviceRunner","-parallel-testing-enabled","NO",tp(e),"1","-destination",(s=e,l=tu(s),"macOS"===l?`platform=macOS,arch=${tc()}`:"simulator"===s.kind?`platform=${l} Simulator,id=${s.id}`:`generic/platform=${l}`),"-derivedDataPath",r,"COMPILER_INDEX_STORE_ENABLE=NO","ENABLE_CODE_COVERAGE=NO",...i,...o,...n],{detached:!0,onSpawn:e=>{e7.add(e),e.on("close",()=>{e7.delete(e)})},onStdoutChunk:e=>{eZ(e,a.logPath,a.traceLogPath,a.verbose)},onStderrChunk:e=>{eZ(e,a.logPath,a.traceLogPath,a.verbose)}})}catch(n){let e,t,r=n instanceof I?n:new I("COMMAND_FAILED",String(n)),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);throw new I("COMMAND_FAILED","xcodebuild build-for-testing failed",{error:r.message,details:r.details,logPath:a.logPath,hint:i})}}function tu(e){var t;if("ios"!==e.platform&&"macos"!==e.platform)throw new I("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 tc(){return"arm64"===process.arch?"arm64":"x86_64"}function tp(e){return"macos"===e.platform||"device"===e.kind?"-maximum-concurrent-test-device-destinations":"-maximum-concurrent-test-simulator-destinations"}function tf(e,t,r){C({level:"rebuild"===e?"warn":"info",phase:"runner_xctestrun_cache",data:{action:e,reason:t,...r}})}let tm=new Map,th=new Map;async function tw(e,t){return await e0(th,e.id,async()=>{var r;let a,i=tm.get(e.id);if(i){if(function(e){return!!e&&R(e)}(i.child.pid))return i;await tI(e.id,i)}await ("simulator"!==(r=e).kind?Promise.resolve():t_(r)),await tg(e);let n=await tn(e,t),o=await eY(),{xctestrunPath:s,jsonPath:l}=await tl(n,{AGENT_DEVICE_RUNNER_PORT:String(o)},`session-${e.id}-${o}`),{child:d,wait:u}=c("xcodebuild",["test-without-building","-only-testing","AgentDeviceRunnerUITests/RunnerTests/testCommand","-parallel-testing-enabled","NO","-test-timeouts-enabled","NO","-collect-test-diagnostics","never",tp(e),"1","-destination-timeout",String(eH),"-xctestrun",s,"-destination","macOS"===(a=tu(e))?`platform=macOS,arch=${tc()}`:"simulator"===e.kind?`platform=${a} Simulator,id=${e.id}`:`platform=${a},id=${e.id}`],{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(o)},detached:!0});d.stdout?.on("data",e=>{eZ(e,t.logPath,t.traceLogPath,t.verbose)}),d.stderr?.on("data",e=>{eZ(e,t.logPath,t.traceLogPath,t.verbose)});let p={sessionId:`${e.id}:${o}:${Date.now()}`,device:e,deviceId:e.id,port:o,xctestrunPath:s,jsonPath:l,testPromise:u,child:d,ready:!1};return tm.set(e.id,p),p})}async function tg(e){if("simulator"===e.kind)for(let t of ta){let r=await m("xcrun",e$(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 tv(e){await e0(th,e.deviceId,async()=>{await tI(e.deviceId,e)})}async function tI(e,t){let r=t??tm.get(e);if(r){try{await eW(r.device,r.port,{command:"shutdown"},void 0,15e3)}catch{await tS(r.child.pid,"SIGTERM")}try{await Promise.race([r.testPromise,new Promise(e=>setTimeout(e,1e4))])}catch{}await tS(r.child.pid,"SIGKILL"),eQ(r.xctestrunPath),eQ(r.jsonPath),tm.get(e)===r&&tm.delete(e)}}async function tA(e){await e0(th,e,async()=>{await tI(e)})}async function ty(){let e=Array.from(tm.values()),t=Array.from(e7);await Promise.allSettled(e.map(async e=>{await tS(e.child.pid,"SIGINT")})),await Promise.allSettled(t.map(async e=>{await tS(e.pid,"SIGINT")})),await Promise.allSettled(e.map(async e=>{await tS(e.child.pid,"SIGTERM")})),await Promise.allSettled(t.map(async e=>{await tS(e.pid,"SIGTERM")})),await Promise.allSettled(e.map(async e=>{await tS(e.child.pid,"SIGKILL")})),await Promise.allSettled(t.map(async e=>{await tS(e.pid,"SIGKILL"),e7.delete(e)}))}async function tb(){await ty();let e=Array.from(tm.keys());await Promise.allSettled(e.map(async e=>{await tA(e)}));let t=Array.from(e7);await Promise.allSettled(t.map(async e=>{try{await tS(e.pid,"SIGTERM"),await tS(e.pid,"SIGKILL")}finally{e7.delete(e)}}))}async function tS(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 m("pkill",[`-${r}`,"-P",String(e)],{allowFailure:!0})}catch{}}async function t_(e){await m("xcrun",e$(e,["bootstatus",e.id,"-b"]),{timeoutMs:eF})}async function tN(e,t,r,a,i,n){let o=await eW(e,t.port,r,a,i,t,n);return await tD(o,t,a)}async function tD(e,t,r){let a=await e.text(),i={};try{i=JSON.parse(a)}catch{throw new I("COMMAND_FAILED","Invalid runner response",{text:a})}if(!i.ok)throw new I("COMMAND_FAILED",i.error?.message??"Runner error",{runner:i,xcodebuild:{exitCode:1,stdout:"",stderr:""},logPath:r});return t.ready=!0,i.data??{}}async function tE(e,t,r={}){var a;if("ios"!==e.platform&&"macos"!==e.platform)throw new I("UNSUPPORTED_PLATFORM",`Unsupported platform for iOS runner: ${e.platform}`);if("simulator"!==e.kind&&"device"!==e.kind)throw new I("UNSUPPORTED_OPERATION",`Unsupported iOS device kind for runner: ${e.kind}`);return(eE(r.requestId),"snapshot"===(a=t.command)||"screenshot"===a||"findText"===a||"readText"===a||"alert"===a||"uptime"===a)?el(()=>(eE(r.requestId),tk(e,t,r)),{shouldRetry:e=>{eE(r.requestId);if(!(e instanceof I)||"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"))}}):tk(e,t,r)}async function tk(e,t,r={}){let a;eE(r.requestId);let i=eI(r.requestId);try{let n=(a=await tw(e,r)).ready?eU:eF;return await tN(e,a,t,r.logPath,n,i)}catch(o){let n=o instanceof I?o:new I("COMMAND_FAILED",String(o));if("COMMAND_FAILED"===n.code&&"string"==typeof n.message&&n.message.includes("Runner did not accept connection")&&e_(n)&&a?.ready){eE(r.requestId),a?await tv(a):await tA(e.id),a=await tw(e,r);let n=await eW(a.device,a.port,t,r.logPath,eF,void 0,i);return await tD(n,a,r.logPath)}throw o}}function tM(e){let t=e.result?.text;if("string"==typeof t&&t.trim().length>0)return t;let r=e.positionals??[];return 0===r.length?"":r[0].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 tx(e){let t=new Set,r=[];for(let a of e)t.has(a)||(t.add(a),r.push(a));return r}let tO=/^-?\d+(\.\d+)?$/,tL=new Map([["--count","count"],["--interval-ms","intervalMs"],["--hold-ms","holdMs"],["--jitter-px","jitterPx"]]),tC=new Map([["--count","count"],["--pause-ms","pauseMs"]]);function tP(e){return"click"===e||"press"===e}function tR(e){let t=e.trim();return t.startsWith("@")||tO.test(t)?t:JSON.stringify(t)}function tT(e){let t=e.trim();return/\s/.test(t)?JSON.stringify(t):t}function t$(e,t){let r=t.flags??{};if(tP(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}"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))}function tF(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",tT(t.metroHost)),"number"==typeof t.metroPort&&e.push("--metro-port",String(t.metroPort)),"string"==typeof t.bundleUrl&&t.bundleUrl.length>0&&e.push("--bundle-url",tT(t.bundleUrl)),"string"==typeof t.launchUrl&&t.launchUrl.length>0&&e.push("--launch-url",tT(t.launchUrl)))}function tU(e,t){let[r,...a]=t.positionals??[];for(let t of(r&&e.push(tT(r)),a))e.push(tR(t));"number"==typeof t.flags?.fps&&e.push("--fps",String(t.flags.fps)),t.flags?.hideTouches&&e.push("--hide-touches")}function tV(e,t){let r=[],a={},i=tP(e)?tL:"swipe"===e?tC:void 0;for(let n=0;n<t.length;n+=1){let o=t[n];if(tP(e)&&"--double-tap"===o){a.doubleTap=!0;continue}if(tP(e)&&"--button"===o&&n+1<t.length){let e=t[n+1];("primary"===e||"secondary"===e||"middle"===e)&&(a.clickButton=e),n+=1;continue}let s=i?.get(o);if(s&&n+1<t.length){let e=tB(t[n+1]);null!==e&&(a[s]=e),n+=1;continue}if("swipe"===e&&"--pattern"===o&&n+1<t.length){let e=t[n+1];("one-way"===e||"ping-pong"===e)&&(a.pattern=e),n+=1;continue}r.push(o)}return{positionals:r,flags:a}}function tG(e){let t=[],r={};for(let a=0;a<e.length;a+=1){let i=e[a];if("--platform"===i&&a+1<e.length){let t=e[a+1];("ios"===t||"android"===t)&&(r.platform=t),a+=1;continue}if("--metro-host"===i&&a+1<e.length){r.metroHost=e[a+1],a+=1;continue}if("--metro-port"===i&&a+1<e.length){let t=tB(e[a+1]);null!==t&&(r.metroPort=t),a+=1;continue}if("--bundle-url"===i&&a+1<e.length){r.bundleUrl=e[a+1],a+=1;continue}if("--launch-url"===i&&a+1<e.length){r.launchUrl=e[a+1],a+=1;continue}t.push(i)}return{positionals:t,flags:r}}function tB(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function tj(e,t){for(let r of t.positionals??[])e.push(tR(r));t.flags?.relaunch&&e.push("--relaunch"),tF(e,t.runtime)}class tq{sessions=new Map;runtimeHints=new Map;sessionsDir;constructor(e){this.sessionsDir=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=tq.expandHome(t.flags.saveScript))),e.actions.push({ts:Date.now(),command:t.command,positionals:t.positionals,runtime:t.runtime,flags:function(e){if(!e)return{};let{platform:t,device:r,udid:a,serial:i,out:n,verbose:o,metroHost:s,metroPort:l,bundleUrl:d,launchUrl:u,snapshotInteractiveOnly:c,snapshotCompact:p,snapshotDepth:f,snapshotScope:m,snapshotRaw:h,relaunch:w,saveScript:g,noRecord:v,fps:I,hideTouches:A,count:y,intervalMs:b,holdMs:S,jitterPx:_,doubleTap:N,clickButton:D,pauseMs:E,pattern:k}=e;return{platform:t,device:r,udid:a,serial:i,out:n,verbose:o,metroHost:s,metroPort:l,bundleUrl:d,launchUrl:u,snapshotInteractiveOnly:c,snapshotCompact:p,snapshotDepth:f,snapshotScope:m,snapshotRaw:h,relaunch:w,saveScript:g,noRecord:v,fps:I,hideTouches:A,count:y,intervalMs:b,holdMs:S,jitterPx:_,doubleTap:N,clickButton:D,pauseMs:E,pattern:k}}(t.flags),result:t.result}),C({level:"debug",phase:"record_action",data:{command:t.command,session:e.name}}))}writeSessionLog(e){try{if(!e.recordSession)return;let t=this.resolveScriptPath(e),r=o.dirname(t);F.existsSync(r)||F.mkdirSync(r,{recursive:!0});let a=function(e,t){let r=[],a=e.device.name.replace(/"/g,'\\"'),i=e.device.kind?` kind=${e.device.kind}`:"";for(let n of(r.push(`context platform=${e.device.platform} device="${a}"${i} theme=unknown`),t))n.flags?.noRecord||r.push(function(e){let t=[e.command];if(tP(e.command)){let r=e.positionals?.[0];if(r){if(r.startsWith("@")){t.push(tR(r));let a=e.result?.refLabel;return"string"==typeof a&&a.trim().length>0&&t.push(tR(a)),t$(t,e),t.join(" ")}if(1===e.positionals.length)return t.push(tR(r)),t$(t,e),t.join(" ")}}if("fill"===e.command){let r=e.positionals?.[0];if(r&&r.startsWith("@")){t.push(tR(r));let a=e.result?.refLabel,i=e.positionals.slice(1).join(" ");return"string"==typeof a&&a.trim().length>0&&t.push(tR(a)),i&&t.push(tR(i)),t.join(" ")}}if("get"===e.command){let r=e.positionals?.[0],a=e.positionals?.[1];if(r&&a){if(t.push(tR(r)),t.push(tR(a)),a.startsWith("@")){let r=e.result?.refLabel;"string"==typeof r&&r.trim().length>0&&t.push(tR(r))}return t.join(" ")}}if("snapshot"===e.command)return e.flags?.snapshotInteractiveOnly&&t.push("-i"),e.flags?.snapshotCompact&&t.push("-c"),"number"==typeof e.flags?.snapshotDepth&&t.push("-d",String(e.flags.snapshotDepth)),e.flags?.snapshotScope&&t.push("-s",tR(e.flags.snapshotScope)),e.flags?.snapshotRaw&&t.push("--raw"),t.join(" ");if("open"===e.command)return tj(t,e),t.join(" ");if("runtime"===e.command){let r=e.positionals?.[0];return r&&t.push(tT(r)),tF(t,e.flags),t.join(" ")}if("record"===e.command)return tU(t,e),t.join(" ");for(let r of e.positionals??[])t.push(tR(r));return t$(t,e),t.join(" ")}(n));return`${r.join("\n")}
8
+ `}(e,this.buildOptimizedActions(e));F.writeFileSync(t,a)}catch{}}defaultTracePath(e){let t=tq.safeSessionName(e.name),r=new Date().toISOString().replace(/[:.]/g,"-");return o.join(this.sessionsDir,`${t}-${r}.trace.log`)}resolveAppLogPath(e){return o.join(this.sessionsDir,tq.safeSessionName(e),"app.log")}resolveAppLogPidPath(e){return o.join(this.sessionsDir,tq.safeSessionName(e),"app-log.pid")}static safeSessionName(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}static expandHome(e,t){return E(e,{cwd:t})}resolveScriptPath(e){if(e.saveScriptPath)return tq.expandHome(e.saveScriptPath);F.existsSync(this.sessionsDir)||F.mkdirSync(this.sessionsDir,{recursive:!0});let t=tq.safeSessionName(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,"-");return o.join(this.sessionsDir,`${t}-${r}.ad`)}buildOptimizedActions(e){let t=[];for(let r of e.actions){if("snapshot"===r.command)continue;let a=Array.isArray(r.result?.selectorChain)&&r.result?.selectorChain.every(e=>"string"==typeof e)?r.result.selectorChain:[];if(a.length>0&&(tP(r.command)||"fill"===r.command||"get"===r.command)){let e=a.join(" || ");if(tP(r.command)){t.push({...r,positionals:[e]});continue}if("fill"===r.command){let a=tM(r);if(a.length>0){t.push({...r,positionals:[e,a]});continue}}if("get"===r.command){let a=r.positionals?.[0];if("text"===a||"attrs"===a){t.push({...r,positionals:[a,e]});continue}}}if(tP(r.command)||"fill"===r.command||"get"===r.command){let a=r.result?.refLabel;"string"==typeof a&&a.trim().length>0&&t.push({ts:r.ts,command:"snapshot",positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotCompact:!0,snapshotScope:a.trim()},result:{scope:a.trim()}})}t.push(r)}return t}}function tH(e,t){if(!e)return;let r=o.dirname(e);F.existsSync(r)||F.mkdirSync(r,{recursive:!0});let a={pid:t,startTime:T(t)??void 0,command:s(t)??void 0};F.writeFileSync(e,`${JSON.stringify(a)}
9
+ `)}function tW(e){if(e&&F.existsSync(e))try{F.unlinkSync(e)}catch{}}async function tz(e,t=2e3){await Promise.race([e.then(()=>void 0).catch(()=>void 0),new Promise(e=>setTimeout(e,t))])}async function tJ(e){await new Promise(t=>setTimeout(t,e))}function tX(e,t){let r=t.includeTokens?.filter(e=>e.length>0)??[],a="",i=a=>{(!(r.length>0)||r.some(e=>a.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}(a,t.redactionPatterns))};return{onChunk:e=>{let t=`${a}${e}`.split("\n");for(let e of(a=t.pop()??"",t))i(`${e}
10
+ `)},flush:()=>{a&&(i(a),a="")}}}function tK(e,t,r){let a=e.stdout,i=e.stderr;return a&&i?(a.setEncoding("utf8"),i.setEncoding("utf8"),a.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(a=>{e.on("close",e=>{r.writer.flush(),r.endStreamOnClose&&t.end(),a({stdout:"",stderr:"",exitCode:e??1})})})):Promise.resolve({stdout:"",stderr:"missing stdio pipes",exitCode:1})}async function tY(e,t){let r=(await m("adb",["-s",e,"shell","pidof",t],{allowFailure:!0})).stdout.trim().split(/\s+/)[0];return r&&/^\d+$/.test(r)?r:null}async function tZ(e,t,r,a,i){let n,o,s="active",l=!1,d=(async()=>{try{for(;!l;){let d=await tY(e,t);if(!d){await tJ(1e3);continue}let u=h("adb",["-s",e,"logcat","-v","time","--pid",d],{stdio:["ignore","pipe","pipe"]});n=u;let c=tX(r,{redactionPatterns:a});o=tK(u,r,{endStreamOnClose:!1,writer:c}),"number"==typeof u.pid&&tH(i,u.pid);let p=await o;if(tW(i),n=void 0,o=void 0,l)break;0!==p.exitCode&&(s="failed"),await tJ(500)}return{stdout:"",stderr:"",exitCode:0}}finally{r.end(),tW(i)}})();return{backend:"android",getState:()=>s,startedAt:Date.now(),wait:d,stop:async()=>{l=!0,n&&!n.killed&&n.kill("SIGINT"),o&&await tz(o),n&&!n.killed&&n.kill("SIGKILL"),await tz(d),tW(i)}}}function tQ(e){return`subsystem == "${e}" OR processImagePath ENDSWITH[c] "/${e}" OR senderImagePath ENDSWITH[c] "/${e}" OR eventMessage CONTAINS[c] "${e}"`}async function t0(e,t,r,a){let i="active",n=h("log",["stream","--style","compact","--predicate",tQ(e)],{stdio:["ignore","pipe","pipe"]}),o=tX(t,{redactionPatterns:r});"number"==typeof n.pid&&tH(a,n.pid);let s=tK(n,t,{endStreamOnClose:!0,writer:o}).then(e=>(0!==e.exitCode&&(i="failed"),tW(a),e));return{backend:"ios-simulator",getState:()=>i,startedAt:Date.now(),wait:s,stop:async()=>{n.killed||n.kill("SIGINT"),await tz(s),n.killed||n.kill("SIGKILL"),await tz(s),tW(a)}}}async function t1(e,t,r,a){let i="active",n=h("log",["stream","--style","compact","--predicate",tQ(e)],{stdio:["ignore","pipe","pipe"]}),o=tX(t,{redactionPatterns:r});"number"==typeof n.pid&&tH(a,n.pid);let s=tK(n,t,{endStreamOnClose:!0,writer:o}).then(e=>(0!==e.exitCode&&(i="failed"),tW(a),e));return{backend:"macos",getState:()=>i,startedAt:Date.now(),wait:s,stop:async()=>{n.killed||n.kill("SIGINT"),await tz(s),n.killed||n.kill("SIGKILL"),await tz(s),tW(a)}}}async function t2(e,t,r,a){let i="active",n=h("xcrun",["devicectl","device","log","stream","--device",e],{stdio:["ignore","pipe","pipe"]}),o=tX(t,{redactionPatterns:r});"number"==typeof n.pid&&tH(a,n.pid);let s=tK(n,t,{endStreamOnClose:!0,writer:o}).then(e=>(0!==e.exitCode&&(i="failed"),tW(a),e));return{backend:"ios-device",getState:()=>i,startedAt:Date.now(),wait:s,stop:async()=>{n.killed||n.kill("SIGINT"),await tz(s),n.killed||n.kill("SIGKILL"),await tz(s),tW(a)}}}function t3(e,t){let r=process.env[e];if(!r)return t;let a=Number.parseInt(r,10);return Number.isInteger(a)&&a>0?a:t}function t4(e){let t=o.dirname(e);F.existsSync(t)||F.mkdirSync(t,{recursive:!0}),function(e,t){if(F.existsSync(e)&&!(F.statSync(e).size<t.maxBytes))for(let r=t.maxRotatedFiles;r>=1;r-=1){let t=1===r?e:`${e}.${r-1}`,a=`${e}.${r}`;F.existsSync(t)&&(F.existsSync(a)&&F.unlinkSync(a),F.renameSync(t,a))}}(e,{maxBytes:t3("AGENT_DEVICE_APP_LOG_MAX_BYTES",5242880),maxRotatedFiles:t3("AGENT_DEVICE_APP_LOG_MAX_FILES",1)})}async function t8(e,t,r,a){t4(r);let i=F.createWriteStream(r,{flags:"a"}),n=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 t2(e.id,i,n,a):await t0(t,i,n,a);if("android"===e.platform){if(!/^[a-zA-Z0-9._:-]+$/.test(t))throw new I("INVALID_ARGS",`Invalid Android package name for logs: ${t}`);return await tZ(e.id,t,i,n,a)}if("macos"===e.platform)return await t1(t,i,n,a);throw i.end(),new I("UNSUPPORTED_PLATFORM",`unsupported platform: ${e.platform}`)}async function t5(e){await e.stop(),await tz(e.wait)}async function t6(e,t){let r={},a=[];if(t||a.push("No app bundle is tracked in this session. Run open <app> first for app-scoped logs."),"android"===e.platform){try{let e=await m("adb",["version"],{allowFailure:!0});r.adbAvailable=0===e.exitCode}catch{r.adbAvailable=!1}if(t)try{r.androidPidVisible=(await m("adb",["-s",e.id,"shell","pidof",t],{allowFailure:!0})).stdout.trim().length>0}catch{r.androidPidVisible=!1}}if("ios"===e.platform&&"simulator"===e.kind)try{let e=await m("xcrun",["simctl","help"],{allowFailure:!0});r.simctlAvailable=0===e.exitCode}catch{r.simctlAvailable=!1}if("ios"===e.platform&&"device"===e.kind)try{let e=await m("xcrun",["devicectl","--version"],{allowFailure:!0});r.devicectlAvailable=0===e.exitCode}catch{r.devicectlAvailable=!1}if("macos"===e.platform)try{let e=await m("log",["help"],{allowFailure:!0});r.logAvailable=0===e.exitCode}catch{r.logAvailable=!1}return{checks:r,notes:a}}function t9(e){let t=o.dirname(e),r=o.basename(e);F.existsSync(t)||F.mkdirSync(t,{recursive:!0}),F.existsSync(e)?F.truncateSync(e,0):F.writeFileSync(e,"","utf8");let a=0;for(let e of F.readdirSync(t)){if(!e.startsWith(`${r}.`))continue;let i=e.slice(r.length+1);if(/^\d+$/.test(i))try{F.unlinkSync(o.join(t,e)),a+=1}catch{}}return{path:e,cleared:!0,removedRotatedFiles:a}}let t7=new Map;function re(e){let t=t7.get(e);if(t&&(clearTimeout(t.timer),t7.delete(e),t.deleteAfterDownload))try{F.rmSync(t.artifactPath,{force:!0})}catch{}}let rt=new Map;function rr(e,t){let r=rt.get(e);if(!r)throw new I("INVALID_ARGS",`Uploaded artifact not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new I("UNAUTHORIZED","Uploaded artifact belongs to a different tenant");return clearTimeout(r.timer),r.artifactPath}function ra(e){let t=rt.get(e);t&&(clearTimeout(t.timer),rt.delete(e),F.rmSync(t.tempDir,{recursive:!0,force:!0}))}async function ri(e){let t=await rn(e);await m("tar",["xf",e.archivePath,"-C",e.tempDir]);let r=o.join(e.tempDir,t);if(!F.existsSync(r))throw new I("INVALID_ARGS",`Expected extracted bundle "${t}" not found in archive`);return r}async function rn(e){let t=await m("tar",["-tf",e.archivePath],{allowFailure:!0});if(0!==t.exitCode)throw new I("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 I("INVALID_ARGS","Uploaded app bundle archive is empty");let a=r.map(e=>(function(e){if(e.includes("\0"))throw new I("INVALID_ARGS",`Invalid archive entry: ${e}`);if(o.posix.isAbsolute(e))throw new I("INVALID_ARGS",`Archive entry must be relative: ${e}`);let t=o.posix.normalize(e).replace(/^(\.\/)+/,"");if(!t||"."===t||t.startsWith("../"))throw new I("INVALID_ARGS",`Archive entry escapes bundle root: ${e}`);return t})(e)),i=e.expectedRootName??function(e,t){let r=new Set;for(let t of e){let[e]=t.split("/");e&&r.add(e)}let a=[...r];if("ios"===t){let e=a.filter(e=>e.toLowerCase().endsWith(".app"));if(1===e.length)return e[0];if(0===e.length)throw new I("INVALID_ARGS","iOS app bundle archives must contain a single top-level .app directory");throw new I("INVALID_ARGS",`iOS app bundle archives must contain exactly one top-level .app directory, found: ${e.join(", ")}`)}if(1===a.length)return a[0];throw new I("INVALID_ARGS",`Archive must contain a single top-level bundle, found: ${a.join(", ")}`)}(a,e.platform);if(!a.some(e=>e===i||e.startsWith(`${i}/`)))throw new I("INVALID_ARGS",`Uploaded archive must contain a top-level "${i}" bundle`);for(let e of a){var n=e,s=i;if(n!==s&&!n.startsWith(`${s}/`))throw new I("INVALID_ARGS",`Archive entry must stay inside top-level "${s}" bundle: ${n}`)}for(let t of(await m("tar",["-tvf",e.archivePath])).stdout.split(/\r?\n/).filter(Boolean)){let e=t[0];if("l"===e||"h"===e)throw new I("INVALID_ARGS","Uploaded app bundle archive cannot contain symlinks or hard links")}return i}let ro=ek(process.env.AGENT_DEVICE_ARTIFACT_IDLE_TIMEOUT_MS,6e4,1e3);function rs(e,t){return new Promise((r,a)=>{let i,n=F.createWriteStream(t),o=t=>{"destroy"in e&&"function"==typeof e.destroy&&e.destroy(t)},s=!1,l=0,d=e=>{if(!s){if(s=!0,i&&clearTimeout(i),e){n.destroy(),F.rmSync(t,{force:!0}),a(e);return}r()}},u=()=>{i&&clearTimeout(i),i=setTimeout(()=>{let e=new I("COMMAND_FAILED","Artifact transfer timed out due to inactivity",{timeoutMs:ro});o(e),n.destroy(e),d(e)},ro)};e.on("data",e=>{u();let t=Buffer.isBuffer(e)?e.length:Buffer.byteLength(e);if((l+=t)>0x80000000){let e=new I("INVALID_ARGS","Upload exceeds maximum size of 2147483648 bytes");o(e),n.destroy(e),d(e)}}),e.on("error",d),e.on("aborted",()=>{d(new I("COMMAND_FAILED","Artifact transfer was interrupted"))}),n.on("error",d),n.on("finish",()=>d()),u(),e.pipe(n)})}async function rl(e){let t,r=e.headers["x-artifact-type"],a=e.headers["x-artifact-filename"];if(!r||!a)throw new I("INVALID_ARGS","Missing required headers: x-artifact-type and x-artifact-filename");if("file"!==r&&"app-bundle"!==r)throw new I("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 I("INVALID_ARGS","Upload exceeds maximum size of 2147483648 bytes")}(e.headers["content-length"]);let i=function(e){let t=e.trim(),r=o.basename(t);if(!r||"."===r||".."===r)throw new I("INVALID_ARGS",`Invalid artifact filename: ${e}`);return r}(a),n=(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"),F.mkdtempSync(o.join(V.tmpdir(),`agent-device-artifact-${t}-`)));try{if("file"===r){let t=o.join(n,i);return await rs(e,t),{artifactPath:t,tempDir:n}}let t=o.join(n,"artifact.tar");await rs(e,t);let a=await ri({archivePath:t,tempDir:n,platform:"ios",expectedRootName:i});return F.rmSync(t,{force:!0}),{artifactPath:a,tempDir:n}}catch(e){throw F.rmSync(n,{recursive:!0,force:!0}),e}}let rd=new Set(["agent_device.command","agent-device.command"]),ru=new Set(["agent_device.install_from_source","agent-device.install_from_source"]),rc=new Set(["agent_device.release_materialized_paths","agent-device.release_materialized_paths"]),rp={"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"},rf=new Set([...rd,...ru,...rc,...Object.keys(rp)]);function rm(e,t,r,a){return{jsonrpc:"2.0",id:e,error:{code:t,message:r,data:a}}}function rh(e,t,r=200){e.statusCode=r,e.setHeader("content-type","application/json"),e.end(JSON.stringify(t))}function rw(e){switch(e){case"INVALID_ARGS":return 400;case"UNAUTHORIZED":return 401;case"SESSION_NOT_FOUND":return 404;default:return 500}}function rg(e,t){let r="string"==typeof t.authorization?t.authorization:"",a=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??a??""}function rv(e,t){let r=e[t];return"string"==typeof r?r:void 0}function rI(e,t){let r=e[t];return Number.isInteger(r)?Number(r):void 0}async function rA(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=N(new I("UNAUTHORIZED","Request rejected by auth hook"));return{ok:!1,statusCode:401,response:rm(t.rpcRequest.id??null,-32001,e.message,e)}}if(!1===r.ok){let e=N(new I(r.code??"UNAUTHORIZED",r.message??"Request rejected by auth hook",r.details));return{ok:!1,statusCode:401,response:rm(t.rpcRequest.id??null,-32001,e.message,e)}}if("string"==typeof r.tenantId&&r.tenantId.length>0){let e=l(r.tenantId);if(!e){let e=N(new I("INVALID_ARGS","Auth hook returned invalid tenantId"));return{ok:!1,statusCode:500,response:rm(t.rpcRequest.id??null,-32e3,e.message,e)}}return{ok:!0,tenantId:e}}return{ok:!0}}async function ry(){let e,t=process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;if(!t)return null;let r=process.env.AGENT_DEVICE_HTTP_AUTH_EXPORT||"default",a=o.isAbsolute(t)?t:o.resolve(t);try{e=await import(v(a).href)}catch(e){throw new I("COMMAND_FAILED","Failed to load AGENT_DEVICE_HTTP_AUTH_HOOK module",{hookPath:a,error:e instanceof Error?e.message:String(e)})}let i=e[r];if("function"!=typeof i)throw new I("INVALID_ARGS",`Auth hook export ${r} is not a function`,{hookPath:a,exportName:r});return i}async function rb(e){let t=await ry(),{handleRequest:r,token:a}=e;return q.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 rS(e,i,t,a);if("GET"===e.method&&e.url?.startsWith("/upload/"))return void r_(e,i,t,a);if("POST"!==e.method||"/rpc"!==e.url){i.statusCode=404,i.end("Not found");return}let n="";e.setEncoding("utf8"),e.on("data",t=>{(n+=t).length>1048576&&e.destroy(Error("request too large"))}),e.on("error",()=>{i.headersSent||rh(i,rm(null,-32700,"Parse error"),400)}),e.on("end",async()=>{let a,o;try{a=JSON.parse(n)}catch{rh(i,rm(null,-32700,"Parse error"),400);return}if("2.0"!==a.jsonrpc||"string"!=typeof a.method)return void rh(i,rm(a.id??null,-32600,"Invalid Request"),400);if(!rf.has(a.method))return void rh(i,rm(a.id??null,-32601,`Method not found: ${a.method}`),404);if(!a.params||"object"!=typeof a.params)return void rh(i,rm(a.id??null,-32602,"Invalid params"),400);try{var s;let n=a.params,l=function(e,t,r){if(rd.has(e))return{token:rg(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(ru.has(e)){let e,a=rv(t,"platform");if("ios"!==a&&"android"!==a)throw new I("INVALID_ARGS",'Invalid params: platform must be "ios" or "android"');return{token:rg(t,r),session:rv(t,"session")??"default",command:"install_source",positionals:[],flags:{platform:a},meta:{requestId:rv(t,"requestId"),installSource:function(e){let t=e.source;if(!t||"object"!=typeof t)throw new I("INVALID_ARGS","Invalid params: source is required");if("url"===t.kind){let e="string"==typeof t.url?t.url.trim():"";if(!e)throw new I("INVALID_ARGS","Invalid params: source.url is required for url sources");let r=t.headers,a={};if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw new I("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 I("INVALID_ARGS","Invalid params: source.headers values must be strings");a[e]=t}}return Object.keys(a).length>0?{kind:"url",url:e,headers:a}:{kind:"url",url:e}}if("path"===t.kind){let e="string"==typeof t.path?t.path.trim():"";if(!e)throw new I("INVALID_ARGS","Invalid params: source.path is required for path sources");return{kind:"path",path:e}}throw new I("INVALID_ARGS",'Invalid params: source.kind must be "url" or "path"')}(t),retainMaterializedPaths:(e=t.retainPaths,"boolean"==typeof e?e:void 0),materializedPathRetentionMs:rI(t,"retentionMs")}}}if(rc.has(e)){let e=rv(t,"materializationId")?.trim();if(!e)throw new I("INVALID_ARGS","Invalid params: materializationId is required");return{token:rg(t,r),session:rv(t,"session")??"default",command:"release_materialized_paths",positionals:[],meta:{requestId:rv(t,"requestId"),materializationId:e}}}let a=rp[e];if(a)return{token:rg(t,r),session:rv(t,"session")??"default",command:a,positionals:[],meta:{tenantId:rv(t,"tenantId")??rv(t,"tenant"),runId:rv(t,"runId"),leaseId:rv(t,"leaseId"),leaseTtlMs:rI(t,"ttlMs"),leaseBackend:rv(t,"backend")}};throw new I("INVALID_ARGS",`Method not found: ${e}`)}(a.method,n,e.headers);if(s=a.method,rd.has(s)&&("string"!=typeof l.command||0===l.command.length))return void rh(i,rm(a.id??null,-32602,"Invalid params: command is required"),400);o=em(l.meta?.requestId,a.id),l.meta={...l.meta,requestId:o},eh(o);let d=()=>{i.writableFinished||ew(o)};e.on("aborted",d),i.on("close",d);let u=await rA(t,{headers:e.headers,rpcRequest:a,daemonRequest:l});if(!u.ok)return void rh(i,u.response,u.statusCode);u.tenantId&&(l.meta={...l.meta,tenantId:u.tenantId,sessionIsolation:l.meta?.sessionIsolation??l.flags?.sessionIsolation??"tenant"});let c=await r(l);if(c.ok)return void rh(i,{jsonrpc:"2.0",id:a.id??null,result:c});rh(i,rm(a.id??null,-32e3,c.error.message,c.error),rw(c.error.code))}catch(t){let e=N(t);rh(i,rm(a.id??null,-32e3,e.message,e),rw(e.code))}finally{eg(o)}})})}async function rS(e,t,r,a){try{var i;let n,o,s=rg({},e.headers),l=rN(s,a);if(l){t.statusCode=rw(l.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:l.message,code:l.code}));return}let d=await rA(r,{headers:e.headers,rpcRequest:{jsonrpc:"2.0",id:null,method:"agent_device.command"},daemonRequest:{token:s,session:"default",command:"upload",positionals:[]}});if(!d.ok){t.statusCode=d.statusCode,t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:d.response.error?.data?.message??d.response.error?.message??"Unauthorized"}));return}let u=await rl(e),c=(i={artifactPath:u.artifactPath,tempDir:u.tempDir,tenantId:d.tenantId},n=f.randomUUID(),o=setTimeout(()=>{ra(n)},3e5),rt.set(n,{artifactPath:i.artifactPath,tempDir:i.tempDir,tenantId:i.tenantId,timer:o}),n);t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!0,uploadId:c}))}catch(r){let e=N(r);t.statusCode=rw(e.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:e.message,code:e.code}))}}async function r_(e,t,r,a){let i=e.url?.slice("/upload/".length)??"";if(!i){t.statusCode=400,t.end("Missing artifact id");return}try{let n=rg({},e.headers),o=rN(n,a);if(o){t.statusCode=rw(o.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:o.message,code:o.code}));return}let s=await rA(r,{headers:e.headers,rpcRequest:{jsonrpc:"2.0",id:null,method:"agent_device.command"},daemonRequest:{token:n,session:"default",command:"download_artifact",positionals:[i]}});if(!s.ok){t.statusCode=s.statusCode,t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:s.response.error?.data?.message??s.response.error?.message??"Unauthorized"}));return}let l=function(e,t){let r=t7.get(e);if(!r)throw new I("INVALID_ARGS",`Artifact not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new I("UNAUTHORIZED","Artifact belongs to a different tenant");if(!F.existsSync(r.artifactPath))throw re(e),new I("COMMAND_FAILED",`Artifact file is missing: ${r.artifactPath}`);return{artifactPath:r.artifactPath,fileName:r.fileName,deleteAfterDownload:r.deleteAfterDownload}}(i,s.tenantId),d=F.createReadStream(l.artifactPath);t.statusCode=200,t.setHeader("content-type","application/octet-stream"),l.fileName&&t.setHeader("content-disposition",`attachment; filename="${l.fileName.replace(/"/g,"")}"`),d.on("error",e=>{if(t.headersSent)t.destroy(e);else{let r=N(e);t.statusCode=rw(r.code),t.end(r.message)}}),t.on("close",()=>{t.writableFinished&&re(i)}),d.pipe(t)}catch(r){let e=N(r);t.statusCode=rw(e.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:e.message,code:e.code}))}}function rN(e,t){return t&&e!==t?N(new I("UNAUTHORIZED","Invalid token")):null}function rD(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}function rE(e){if(!e)return;let t=e.trim();if(t&&/^[a-f0-9]{16,128}$/i.test(t))return t.toLowerCase()}function rk(e){let t=(e??"").trim().toLowerCase();if(!t||"ios-simulator"===t)return"ios-simulator";throw new I("INVALID_ARGS",`Unsupported lease backend: ${e??""}`)}class rM{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=rk(e.backend),r=l(e.tenantId);if(!r)throw new I("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");let a=rD(e.runId);if(!a)throw new I("INVALID_ARGS","Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");this.cleanupExpiredLeases();let i=this.resolveLeaseTtlMs(e.ttlMs),n=this.bindingKey(r,a,t),o=this.runBindings.get(n);if(o){let e=this.leases.get(o);if(e)return this.refreshLease(e,i);this.runBindings.delete(n)}this.enforceCapacity(t);let s=this.now(),d={leaseId:f.randomBytes(16).toString("hex"),tenantId:r,runId:a,backend:t,createdAt:s,heartbeatAt:s,expiresAt:s+i};return this.leases.set(d.leaseId,d),this.runBindings.set(n,d.leaseId),{...d}}heartbeatLease(e){let t=rE(e.leaseId);if(!t)throw new I("INVALID_ARGS","Invalid lease id.");this.cleanupExpiredLeases();let r=this.leases.get(t);if(!r)throw new I("UNAUTHORIZED","Lease is not active",{reason:"LEASE_NOT_FOUND"});this.assertOptionalScopeMatch(r,e.tenantId,e.runId);let a=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(r,a)}releaseLease(e){let t=rE(e.leaseId);if(!t)throw new I("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=rk(e.backend),r=l(e.tenantId);if(!r)throw new I("INVALID_ARGS","tenant isolation requires tenant id.");let a=rD(e.runId);if(!a)throw new I("INVALID_ARGS","tenant isolation requires run id.");let i=rE(e.leaseId);if(!i)throw new I("INVALID_ARGS","tenant isolation requires lease id.");this.cleanupExpiredLeases();let n=this.leases.get(i);if(!n)throw new I("UNAUTHORIZED","Lease is not active",{reason:"LEASE_NOT_FOUND"});if(n.backend!==t||n.tenantId!==r||n.runId!==a)throw new I("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 I("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 I("INVALID_ARGS",`Lease ttlMs must be between ${this.minLeaseTtlMs} and ${this.maxLeaseTtlMs}.`);return t}refreshLease(e,t){let r=this.now(),a={...e,heartbeatAt:r,expiresAt:r+t};return this.leases.set(a.leaseId,a),this.runBindings.set(this.bindingKey(a.tenantId,a.runId,a.backend),a.leaseId),{...a}}bindingKey(e,t,r){return`${e}:${t}:${r}`}assertOptionalScopeMatch(e,t,r){let a=l(t),i=rD(r);if(t&&!a)throw new I("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if(r&&!i)throw new I("INVALID_ARGS","Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if(a&&e.tenantId!==a||i&&e.runId!==i)throw new I("UNAUTHORIZED","Lease does not match tenant/run scope",{reason:"LEASE_SCOPE_MISMATCH"})}}let rx=["emulator","platform-tools",o.join("cmdline-tools","latest","bin"),o.join("cmdline-tools","tools","bin")];function rO(e){let t=new Set,r=[];for(let a of e){let e=a.trim();!e||t.has(e)||(t.add(e),r.push(e))}return r}function rL(e=process.env){let t=e.ANDROID_SDK_ROOT?.trim(),r=e.ANDROID_HOME?.trim(),a=e.HOME?.trim()||V.homedir();return rO([t??"",r??"",a?o.join(a,"Android","Sdk"):""])}async function rC(e){try{return await P.access(e,P.constants.X_OK),!0}catch{return!1}}async function rP(e=process.env){let t,r=[];for(let a of rL(e)){let e=[];for(let t of rx){let r=o.join(a,t);await rC(r)&&e.push(r)}0!==e.length&&(t||(t=a),r.push(...e))}if(t&&(e.ANDROID_SDK_ROOT=e.ANDROID_SDK_ROOT?.trim()||t,e.ANDROID_HOME=e.ANDROID_HOME?.trim()||t),0===r.length)return;let a=(e.PATH??"").split(o.delimiter).map(e=>e.trim()).filter(e=>e.length>0);e.PATH=rO([...r,...a]).join(o.delimiter)}function rR(e,t){return["-s",e.id,...t]}async function rT(){if(await rP(),!await y("adb"))throw new I("TOOL_MISSING","adb not found in PATH")}function r$(e,t){let r=`${e}
11
+ ${t}`.toLowerCase();return r.includes("no shell command implementation")||r.includes("unknown command")}async function rF(e){await new Promise(t=>setTimeout(t,e))}function rU(e){let t=e.trim();if(!t||/\s/.test(t))return!1;let r=/^([A-Za-z][A-Za-z0-9+.-]*):(.+)$/.exec(t);if(!r)return!1;let a=r[1]?.toLowerCase(),i=r[2]??"";return"http"!==a&&"https"!==a&&"ws"!==a&&"wss"!==a&&"ftp"!==a&&"ftps"!==a||i.startsWith("//")}function rV(e,t){let r,a=e?.trim();return a?a:"http"===(r=t.trim().split(":")[0]?.toLowerCase())||"https"===r?"com.apple.mobilesafari":void 0}let rG=["android.software.leanback","android.software.leanback_only","android.hardware.type.television"];function rB(e){return`${e.stdout}
12
+ ${e.stderr}`}function rj(e,t){return["-s",e,...t]}function rq(e){return e.startsWith("emulator-")}function rH(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}function rW(e){let t=e.split("\n").map(e=>e.trim()).filter(e=>e.length>0);if(0!==t.length)return"OK"===t.at(-1)&&t.pop(),t.join("\n").trim()||void 0}async function rz(e,t=en){return m("adb",rj(e,["shell","getprop","sys.boot_completed"]),{allowFailure:!0,timeoutMs:t})}async function rJ(e,t){let r=t.replace(/_/g," ").trim();if(!rq(e))return r||e;let a=await rK(e);return a?a.replace(/_/g," "):r||e}async function rX(e,t,r){try{return await r("adb",rj(e,t),{allowFailure:!0,timeoutMs:1e4})}catch(e){var a;if("COMMAND_FAILED"===(a=w(e)).code&&"number"==typeof a.details?.timeoutMs)return;throw e}}async function rK(e,t=m){for(let r of["ro.boot.qemu.avd_name","persist.sys.avd_name"]){let a=await rX(e,["shell","getprop",r],t);if(!a)continue;let i=a.stdout.trim();if(0===a.exitCode&&i.length>0)return i}let r=await rX(e,["emu","avd","name"],t);if(!r)return;let a=rW(r.stdout);if(0===r.exitCode&&a)return a}function rY(e){let t=e.toLowerCase();return t.includes("tv")||t.includes("leanback")?"tv":null}function rZ(e){return/feature:android\.(software\.leanback(_only)?|hardware\.type\.television)\b/i.test(e)}async function rQ(e,t){let r=rB(await m("adb",rj(e,["shell","cmd","package","has-feature",t]),{allowFailure:!0,timeoutMs:en})).toLowerCase();return!!r.includes("true")||!r.includes("false")&&null}async function r0(e){return(await Promise.all(rG.map(async t=>await rQ(e,t)))).some(e=>!0===e)}async function r1(e){return"tv"===rY(rB(await m("adb",rj(e,["shell","getprop","ro.build.characteristics"]),{allowFailure:!0,timeoutMs:en})))||await r0(e)||rZ(rB(await m("adb",rj(e,["shell","pm","list","features"]),{allowFailure:!0,timeoutMs:en})))?"tv":"mobile"}async function r2(e={}){if(await rP(),!await y("adb"))throw new I("TOOL_MISSING","adb not found in PATH");let t=e.serialAllowlist??eR(void 0),r=(await r3()).filter(e=>!t||t.has(e.serial));return await Promise.all(r.map(async({serial:e,rawModel:t})=>{let[r,a,i]=await Promise.all([rJ(e,t),r7(e),r1(e)]);return{platform:"android",id:e,name:r,kind:rq(e)?"emulator":"device",target:i,booted:a}}))}async function r3(){return(await m("adb",["devices","-l"],{timeoutMs:en})).stdout.split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith("List of devices")).map(e=>e.split(/\s+/)).filter(e=>"device"===e[1]).map(e=>({serial:e[0],rawModel:(e.find(e=>e.startsWith("model:"))??"").replace("model:","")}))}function r4(e){return e.split("\n").map(e=>e.trim()).filter(e=>e.length>0)}function r8(e,t){let r=e.find(e=>e===t);if(r)return r;let a=rH(t);return e.find(e=>rH(e)===a)}async function r5(){let e=await m("emulator",["-list-avds"],{allowFailure:!0,timeoutMs:en});if(0!==e.exitCode)throw new I("COMMAND_FAILED","Failed to list Android emulator AVDs",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,hint:"Verify Android emulator tooling is installed and available in PATH."});return r4(e.stdout)}async function r6(e){let t=Date.now();for(;Date.now()-t<e.timeoutMs;){try{let t=await r9(e.avdName,e.serial);if(t)return{platform:"android",id:t,name:e.avdName,kind:"emulator",target:"mobile",booted:!1}}catch{}await new Promise(e=>setTimeout(e,1e3))}throw new I("COMMAND_FAILED","Android emulator did not appear in time",{avdName:e.avdName,serial:e.serial,timeoutMs:e.timeoutMs,hint:"Check emulator logs and verify the AVD can start from command line."})}async function r9(e,t){let r=rH(e);for(let e of(await r3()).filter(e=>(!t||e.serial===t)&&rq(e.serial)))if(rH(e.rawModel)===r||rH(await rJ(e.serial,e.rawModel))===r)return e.serial}async function r7(e){try{let t=await rz(e);return"1"===t.stdout.trim()}catch{return!1}}async function ae(e){var t,r;let a;await rP();let i=e.avdName.trim();if(!i)throw new I("INVALID_ARGS","Android emulator boot requires a non-empty AVD name.");let n=e.timeoutMs??12e4;if(!await y("adb"))throw new I("TOOL_MISSING","adb not found in PATH");if(!await y("emulator"))throw new I("TOOL_MISSING","emulator not found in PATH");let o=await r5(),s=r8(o,i);if(!s)throw new I("DEVICE_NOT_FOUND",`No Android emulator AVD named ${e.avdName}`,{requestedAvdName:i,availableAvds:o,hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."});let l=Date.now(),d=(t=await r2(),r=e.serial,a=rH(s),t.find(e=>"android"===e.platform&&"emulator"===e.kind&&(!r||e.id===r)&&rH(e.name)===a));if(!d){let t=["-avd",s];e.headless&&t.push("-no-window","-no-audio"),u("emulator",t)}let c=d??await r6({avdName:s,serial:e.serial,timeoutMs:n}),p=Math.max(1e3,n-(Date.now()-l));await ar(c.id,p);let f=(await r2()).find(e=>e.id===c.id);return f?{...f,name:s,booted:!0}:{...c,name:s,booted:!0}}async function at(e){return await ae({...e,headless:!0})}async function ar(e,t=6e4){let r,a=eo.fromTimeoutMs(t),i=Math.max(1,Math.ceil(t/1e3)),n=!1;try{await es(async({deadline:i})=>{if(i?.isExpired())throw n=!0,new I("COMMAND_FAILED","Android boot deadline exceeded",{serial:e,timeoutMs:t,elapsedMs:a.elapsedMs(),message:"timeout"});let o=Math.max(1e3,i?.remainingMs()??t),s=await rz(e,Math.min(o,en));if(r=s,"1"!==s.stdout.trim())throw new I("COMMAND_FAILED","Android device is still booting",{serial:e,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode})},{maxAttempts:i,baseDelayMs:1e3,maxDelayMs:1e3,jitter:0,shouldRetry:e=>{let t=eb({error:e,stdout:r?.stdout,stderr:r?.stderr,context:{platform:"android",phase:"boot"}});return"ADB_TRANSPORT_UNAVAILABLE"!==t&&"ANDROID_BOOT_TIMEOUT"!==t}},{deadline:a,phase:"boot",classifyReason:e=>eb({error:e,stdout:r?.stdout,stderr:r?.stderr,context:{platform:"android",phase:"boot"}})})}catch(c){let i=w(c),o=r?.stdout,s=r?.stderr,l=r?.exitCode,d=eb({error:c,stdout:o,stderr:s,context:{platform:"android",phase:"boot"}});"BOOT_COMMAND_FAILED"===d&&"Android device is still booting"===i.message&&(d="ANDROID_BOOT_TIMEOUT");let u={serial:e,timeoutMs:t,elapsedMs:a.elapsedMs(),reason:d,hint:eS(d),stdout:o,stderr:s,exitCode:l};if(n||"ANDROID_BOOT_TIMEOUT"===d)throw new I("COMMAND_FAILED","Android device did not finish booting in time",u);if("TOOL_MISSING"===i.code)throw new I("TOOL_MISSING",i.message,{...u,...i.details??{}});if("ADB_TRANSPORT_UNAVAILABLE"===d)throw new I("COMMAND_FAILED",i.message,{...u,...i.details??{}});throw new I(i.code,i.message,{...u,...i.details??{}},i.cause)}}let aa=/\.(?:apk|aab)$/i,ai=/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)+$/;function an(e){var t,r;let a=e.trim();return 0===a.length?"other":aa.test(a)?a.includes("/")||a.includes("\\")||a.startsWith(".")||a.startsWith("~")||(t=a,!ai.test(t))?"binary":"package":(r=a,ai.test(r))?"package":"other"}function ao(e){return`Android runtime hints require an installed package name, not "${e}". Install or reinstall the app first, then relaunch by package.`}let as=[".zip",".tar",".tar.gz",".tgz"],al=ek(process.env.AGENT_DEVICE_SOURCE_DOWNLOAD_TIMEOUT_MS,12e4,1e3),ad=["1","true","yes","on"];async function au(e){let t=[];try{let r=await ac(e.source,{signal:e.signal,downloadTimeoutMs:e.downloadTimeoutMs});t.push(r.cleanup);let a=await aw(r.localPath,{archivePath:void 0,isInstallablePath:e.isInstallablePath,installableLabel:e.installableLabel,allowArchiveExtraction:!1!==e.allowArchiveExtraction,registerCleanup:e=>{t.push(e)}});return{archivePath:a.archivePath,installablePath:a.installablePath,cleanup:async()=>{await aA(t)}}}catch(e){throw await aA(t),e}}async function ac(e,t){if("path"===e.kind)return{localPath:g(e.path),cleanup:async()=>{}};let r=await P.mkdtemp(o.join(V.tmpdir(),"agent-device-source-"));try{return{localPath:await ap(r,e.url,e.headers,t),cleanup:async()=>{await P.rm(r,{recursive:!0,force:!0})}}}catch(e){throw await P.rm(r,{recursive:!0,force:!0}),e}}async function ap(e,t,r,a){let i;try{i=new URL(t)}catch{throw new I("INVALID_ARGS",`Invalid source URL: ${t}`)}await af(i);let n=a?.signal;if(n?.aborted)throw new I("COMMAND_FAILED","request canceled",{reason:"request_canceled"});let s=new AbortController,l=()=>{s.abort(n?.reason)};n?.addEventListener("abort",l,{once:!0});let d=a?.downloadTimeoutMs??al,u=setTimeout(()=>{s.abort(Error("download timeout"))},d);try{let t=await fetch(i,{headers:r,redirect:"follow",signal:s.signal});if(!t.ok)throw new I("COMMAND_FAILED",`Failed to download app source: ${t.status} ${t.statusText}`,{status:t.status,statusText:t.statusText,url:i.toString()});let a=function(e,t){let r=e.headers.get("content-disposition"),a=r?.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i),i=a?.[1]?.trim();if(i)return o.basename(i);let n=o.basename(t.pathname);return n||"downloaded-artifact.bin"}(t,i),n=o.join(e,a),l=t.body;if(!l)throw new I("COMMAND_FAILED","Download response body was empty",{url:i.toString()});let d=await P.open(n,"w");try{for await(let e of l)await d.write(e)}finally{await d.close()}return n}catch(e){if(n?.aborted)throw new I("COMMAND_FAILED","request canceled",{reason:"request_canceled"},e);if(s.signal.aborted)throw new I("COMMAND_FAILED",`App source download timed out after ${d}ms`,{timeoutMs:d,url:i.toString()},e);throw e}finally{n?.removeEventListener("abort",l),clearTimeout(u)}}async function af(e){if("http:"!==e.protocol&&"https:"!==e.protocol)throw new I("INVALID_ARGS",`Unsupported source URL protocol: ${e.protocol}`);if(!ad.includes((process.env.AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS??"").toLowerCase())){var t;if(!(t=e.hostname.toLowerCase())||"localhost"===t||t.endsWith(".localhost")||ah(t))throw new I("INVALID_ARGS",`Source URL host is not allowed: ${e.hostname}`,{hint:"Use a public artifact URL, or set AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS=1 for trusted private-network daemons."});if((await i.lookup(e.hostname,{all:!0,verbatim:!0}).catch(()=>[])).some(e=>ah(e.address)))throw new I("INVALID_ARGS",`Source URL host resolved to a private or loopback address: ${e.hostname}`,{hint:"Use a public artifact URL, or set AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS=1 for trusted private-network daemons."})}}function am(e){var t,r,a,i;let n=e instanceof URL?e:new URL(e),o=n.hostname.toLowerCase();if(!o)return!1;let s=n.pathname;return t=o,r=s,("api.github.com"===t?/^\/repos\/[^/]+\/[^/]+\/actions\/artifacts\/\d+\/zip$/i.test(r):"github.com"===t&&/^\/[^/]+\/[^/]+\/(?:actions\/runs\/\d+\/artifacts\/\d+|suites\/\d+\/artifacts\/\d+)$/i.test(r))||(a=o,i=s,("expo.dev"===a||!!a.endsWith(".expo.dev"))&&/^\/(?:artifacts\/eas\/|accounts\/[^/]+\/projects\/[^/]+\/builds\/)/i.test(i))}function ah(e){let t,r=G.isIP(e);return 4===r?function(e){let t=e.split(".").map(e=>Number.parseInt(e,10));if(4!==t.length||t.some(e=>Number.isNaN(e)||e<0||e>255))return!1;let[r,a]=t;return 10===r||127===r||169===r&&254===a||172===r&&!!(a>=16)&&!!(a<=31)||192===r&&168===a}(e):6===r&&!!("::1"===(t=e.toLowerCase())||t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80:"))}async function aw(e,t){let r=await P.stat(e).catch(()=>null);if(!r)throw new I("INVALID_ARGS",`App source not found: ${e}`);if(t.isInstallablePath(e,r))return{archivePath:t.archivePath,installablePath:e};if(r.isFile()&&aI(e)){if(!t.allowArchiveExtraction)throw new I("INVALID_ARGS",`URL sources must point directly to a ${t.installableLabel}; archive extraction is not allowed`,{path:e});let r=await av(e);return t.registerCleanup(r.cleanup),await aw(r.outputPath,{...t,archivePath:t.archivePath??e})}if(r.isDirectory()){let r=await ag(e,t.isInstallablePath);if(1===r.length)return{archivePath:t.archivePath,installablePath:r[0]};if(r.length>1)throw new I("INVALID_ARGS",`Found multiple ${t.installableLabel} candidates under ${e}`,{matches:r});let a=await ag(e,(e,t)=>t.isFile()&&aI(e));if(1===a.length){if(!t.allowArchiveExtraction)throw new I("INVALID_ARGS",`URL sources must point directly to a ${t.installableLabel}; nested archives are not allowed`,{path:a[0]});let e=await av(a[0]);return t.registerCleanup(e.cleanup),await aw(e.outputPath,{...t,archivePath:t.archivePath??a[0]})}if(a.length>1)throw new I("INVALID_ARGS",`Found multiple nested archives under ${e}; expected one ${t.installableLabel} source`,{matches:a})}throw new I("INVALID_ARGS",`Expected ${t.installableLabel} source, but got ${e}`)}async function ag(e,t){let r=[],a=[{path:e,depth:0}];for(;a.length>0;){let e=a.shift();if(!e)continue;let i=await P.readdir(e.path,{withFileTypes:!0});for(let n of(i.sort((e,t)=>e.name.localeCompare(t.name)),i)){let i=o.join(e.path,n.name);if(t(i,n)){r.push(i);continue}n.isDirectory()&&e.depth<5&&a.push({path:i,depth:e.depth+1})}}return r}async function av(e){let t=await P.mkdtemp(o.join(V.tmpdir(),"agent-device-archive-"));try{return e.toLowerCase().endsWith(".zip")?await m("ditto",["-x","-k",e,t]):e.toLowerCase().endsWith(".tar.gz")||e.toLowerCase().endsWith(".tgz")?await m("tar",["-xzf",e,"-C",t]):await m("tar",["-xf",e,"-C",t]),{outputPath:t,cleanup:async()=>{await P.rm(t,{recursive:!0,force:!0})}}}catch(e){throw await P.rm(t,{recursive:!0,force:!0}),e}}function aI(e){let t=e.toLowerCase();return as.some(e=>t.endsWith(e))}async function aA(e){for(let t=e.length-1;t>=0;t-=1)await e[t]()}let ay=new Z("utf-16le");async function ab(e){for(let r of["AndroidManifest.xml","base/manifest/AndroidManifest.xml"]){var t;let a=await aS(e,r);if(!a)continue;let i=(t=a).subarray(0,Math.min(t.length,128)).toString("utf8").trimStart().startsWith("<")?function(e){let t=e.match(/<manifest\b[^>]*\bpackage\s*=\s*["']([^"']+)["']/i);return t?.[1]}(t.toString("utf8")):function(e){let t;if(!(e.length<8)&&3===e.readUInt16LE(0))for(let r=e.readUInt16LE(2);r+8<=e.length;){let a=e.readUInt16LE(r),i=e.readUInt16LE(r+2),n=e.readUInt32LE(r+4);if(n<=0||r+n>e.length)break;if(1===a)t=function(e){if(e.length<28)return[];let t=e.readUInt32LE(8),r=e.readUInt32LE(16),a=e.readUInt32LE(20),i=(256&r)!=0,n=[];for(let r=0;r<t;r+=1){let t=28+4*r;if(t+4>e.length)break;let o=a+e.readUInt32LE(t);n.push(i?function(e,t){let[,r]=a_(e,t),[a,i]=a_(e,t+r),n=t+r+i;return e.subarray(n,n+a).toString("utf8")}(e,o):function(e,t){let[r,a]=function(e,t){let r=e.readUInt16LE(t);return(32768&r)==0?[r,2]:[(32767&r)<<16|e.readUInt16LE(t+2),4]}(e,t),i=t+a;return ay.decode(e.subarray(i,i+2*r))}(e,o))}return n}(e.subarray(r,r+n));else if(258===a&&t){let a=function(e,t,r,a){if(r<36||t+r>e.length||"manifest"!==a[e.readUInt32LE(t+20)])return;let i=e.readUInt16LE(t+24),n=e.readUInt16LE(t+26),o=e.readUInt16LE(t+28),s=t+i;for(let t=0;t<o;t+=1){let r=s+t*n;if(r+20>e.length)break;if("package"!==a[e.readUInt32LE(r+4)])continue;let i=e.readUInt32LE(r+8);if(0xffffffff!==i)return a[i];let o=e.readUInt8(r+15),l=e.readUInt32LE(r+16);if(3===o)return a[l];break}}(e,r,i,t);if(a)return a}r+=n}}(t);if(i)return i}return await aN(e)}async function aS(e,t){try{let r=await m("unzip",["-p",e,t],{allowFailure:!0,binaryStdout:!0});if(0!==r.exitCode||!r.stdoutBuffer||0===r.stdoutBuffer.length)return;return r.stdoutBuffer}catch{return}}function a_(e,t){let r=e.readUInt8(t);return(128&r)==0?[r,1]:[(127&r)<<8|e.readUInt8(t+1),2]}async function aN(e){let t=await aD();if(!t)return;let r=await m(t,["dump","badging",e],{allowFailure:!0});if(0!==r.exitCode)return;let a=r.stdout.match(/package:\s+name='([^']+)'/);return a?.[1]}async function aD(){if(void 0!==e)return e??void 0;try{for(let t of rL()){let r=o.join(t,"build-tools");try{for(let t of(await n.readdir(r)).sort((e,t)=>t.localeCompare(e,void 0,{numeric:!0}))){let a=o.join(r,t,"aapt");try{return await n.access(a),e=a,a}catch{}}}catch{}}}catch{}e=null}async function aE(e,t){let r="url"===e.kind&&am(e.url),a=await au({source:e,isInstallablePath:(e,t)=>{var r;let a;return t.isFile()&&(r=e,".apk"===(a=o.extname(r).toLowerCase())||".aab"===a)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==e.kind||r,signal:t?.signal}),i=t?.resolveIdentity===!1?{}:await ak(a.installablePath);return{archivePath:a.archivePath,installablePath:a.installablePath,packageName:i.packageName,cleanup:a.cleanup}}async function ak(e){let t=o.extname(e).toLowerCase();return".apk"!==t&&".aab"!==t?{}:{packageName:await ab(e)}}let aM={settings:{type:"intent",value:"android.settings.SETTINGS"}},ax="android.intent.category.LAUNCHER",aO="android.intent.category.LEANBACK_LAUNCHER",aL="android.intent.category.DEFAULT";async function aC(e,t){let r=t.trim();if("package"===an(r))return{type:"package",value:r};let a=aM[r.toLowerCase()];if(a)return a;let i=(await m("adb",rR(e,["shell","pm","list","packages"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean).filter(e=>e.toLowerCase().includes(r.toLowerCase()));if(1===i.length)return{type:"package",value:i[0]};if(i.length>1)throw new I("INVALID_ARGS",`Multiple packages matched "${t}"`,{matches:i});throw new I("APP_NOT_INSTALLED",`No package found matching "${t}"`)}async function aP(e,t="all"){let r=await aR(e);return("user-installed"===t?(await a$(e)).filter(e=>r.has(e)):Array.from(r)).sort((e,t)=>e.localeCompare(t)).map(e=>({package:e,name:aF(e)}))}async function aR(e){let t=new Set;for(let r of aT(e,{includeFallbackWhenUnknown:!0})){let a=await m("adb",rR(e,["shell","cmd","package","query-activities","--brief","-a","android.intent.action.MAIN","-c",r]),{allowFailure:!0});if(0===a.exitCode&&0!==a.stdout.trim().length)for(let e of a.stdout.split("\n")){let r=e.trim();if(!r)continue;let a=r.split(/\s+/)[0],i=a.includes("/")?a.split("/")[0]:a;i&&t.add(i)}}return t}function aT(e,t={}){return"tv"===e.target?[aO]:"mobile"===e.target?[ax]:t.includeFallbackWhenUnknown?[ax,aO]:[ax]}async function a$(e){return(await m("adb",rR(e,["shell","pm","list","packages","-3"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean)}function aF(e){let t=new Set(["com","android","google","app","apps","service","services","mobile","client"]),r=e.split(".").flatMap(e=>e.split(/[_-]+/)).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0),a=r[r.length-1]??e;for(let e=r.length-1;e>=0;e-=1){let i=r[e];if(!t.has(i)){a=i;break}}return a.split(/[^a-z0-9]+/i).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async function aU(e){let t=await aV(e,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]]);if(t)return t;let r=await aV(e,[["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]);return r||{}}async function aV(e,t){for(let r of t){let t=function(e){for(let t of[/mCurrentFocus=Window\{[^}]*\s([\w.]+)\/([\w.$]+)/,/mFocusedApp=AppWindowToken\{[^}]*\s([\w.]+)\/([\w.$]+)/,/mResumedActivity:.*?\s([\w.]+)\/([\w.$]+)/,/ResumedActivity:.*?\s([\w.]+)\/([\w.$]+)/]){let r=t.exec(e);if(r)return{package:r[1],activity:r[2]}}return null}((await m("adb",rR(e,r),{allowFailure:!0})).stdout??"");if(t)return t}return null}async function aG(e,t,r){e.booted||await ar(e.id);let a=t.trim();if(rU(a)){if(r)throw new I("INVALID_ARGS","Activity override is not supported when opening a deep link URL");await m("adb",rR(e,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",a]));return}let i=await aC(e,t),n=aT(e)[0]??ax;if("intent"===i.type){if(r)throw new I("INVALID_ARGS","Activity override requires a package name, not an intent");await m("adb",rR(e,["shell","am","start","-W","-a",i.value]));return}if(r){let t=r.includes("/")?r:`${i.value}/${r.startsWith(".")?r:`.${r}`}`;await m("adb",rR(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",aL,"-c",n,"-n",t]));return}let o=await m("adb",rR(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",aL,"-c",n,"-p",i.value]),{allowFailure:!0});if(0===o.exitCode&&!aj(o.stdout,o.stderr))return;let s=await aB(e,i.value);if(!s)throw new I("COMMAND_FAILED",`Failed to launch ${i.value}`,{stdout:o.stdout,stderr:o.stderr});await m("adb",rR(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",aL,"-c",n,"-n",s]))}async function aB(e,t){for(let r of Array.from(new Set(aT(e,{includeFallbackWhenUnknown:!0})))){let a=await m("adb",rR(e,["shell","cmd","package","resolve-activity","--brief","-a","android.intent.action.MAIN","-c",r,t]),{allowFailure:!0});if(0!==a.exitCode)continue;let i=aq(a.stdout);if(i)return i}return null}function aj(e,t){let r=`${e}
13
+ ${t}`;return/Error:.*(?:Activity not started|unable to resolve Intent)/i.test(r)}function aq(e){let t=e.split("\n").map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.includes("/"))return r.split(/\s+/)[0]}return null}async function aH(e){e.booted||await ar(e.id)}async function aW(e,t){if("settings"===t.trim().toLowerCase())return void await m("adb",rR(e,["shell","am","force-stop","com.android.settings"]));let r=await aC(e,t);if("intent"===r.type)throw new I("INVALID_ARGS","Close requires a package name, not an intent");await m("adb",rR(e,["shell","am","force-stop",r.value]))}async function az(e,t){let r=await aC(e,t);if("intent"===r.type)throw new I("INVALID_ARGS","App uninstall requires a package name, not an intent");let a=await m("adb",rR(e,["uninstall",r.value]),{allowFailure:!0});if(0!==a.exitCode){let e=`${a.stdout}
14
+ ${a.stderr}`.toLowerCase();if(!e.includes("unknown package")&&!e.includes("not installed"))throw new I("COMMAND_FAILED",`adb uninstall failed for ${r.value}`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode})}return{package:r.value}}let aJ=null;async function aX(){let e=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(aJ?.key===e)return aJ.invocation;if(await y("bundletool")){let t={cmd:"bundletool",prefixArgs:[]};return aJ={key:e,invocation:t},t}let t=process.env.AGENT_DEVICE_BUNDLETOOL_JAR?.trim();if(!t)throw new I("TOOL_MISSING","bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.");try{await P.access(t)}catch{throw new I("TOOL_MISSING",`AGENT_DEVICE_BUNDLETOOL_JAR points to a missing file: ${t}`)}let r={cmd:"java",prefixArgs:["-jar",t]};return aJ={key:e,invocation:r},r}async function aK(e){let t=await aX();await m(t.cmd,[...t.prefixArgs,...e])}async function aY(e,t){let r,a=await P.mkdtemp(o.join(V.tmpdir(),"agent-device-aab-")),i=o.join(a,"bundle.apks"),n=(r=process.env.AGENT_DEVICE_ANDROID_BUNDLETOOL_MODE?.trim())&&r.length>0?r:"universal";try{await aK(["build-apks","--bundle",t,"--output",i,"--mode",n]),await aK(["install-apks","--apks",i,"--device-id",e.id])}finally{await P.rm(a,{recursive:!0,force:!0})}}async function aZ(e,t){".aab"===o.extname(t).toLowerCase()?await aY(e,t):await m("adb",rR(e,["install","-r",t]))}async function aQ(e){return new Set((await m("adb",rR(e,["shell","pm","list","packages"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean))}async function a0(e,t){let r=Array.from(await aQ(e)).filter(e=>!t.has(e));if(1===r.length)return r[0]}async function a1(e,t){e.booted||await ar(e.id),await aZ(e,t)}async function a2(e,t,r){let a=r?void 0:await aQ(e);return await a1(e,t),r??(a?await a0(e,a):void 0)}async function a3(e,t){e.booted||await ar(e.id);let r=await aE({kind:"path",path:t});try{let t=await a2(e,r.installablePath,r.packageName),a=t?aF(t):void 0;return{archivePath:r.archivePath,installablePath:r.installablePath,packageName:t,appName:a,launchTarget:t}}finally{await r.cleanup()}}async function a4(e,t,r){e.booted||await ar(e.id);let{package:a}=await az(e,t),i=await aE({kind:"path",path:r},{resolveIdentity:!1});try{return await a1(e,i.installablePath),{package:a}}finally{await i.cleanup()}}function a8(e){let t=a5(e),r=e=>{let r=a6(t,e);if(null!==r)return"true"===r};return{text:a6(t,"text"),desc:a6(t,"content-desc"),resourceId:a6(t,"resource-id"),className:a6(t,"class"),bounds:a6(t,"bounds"),clickable:r("clickable"),enabled:r("enabled"),focusable:r("focusable"),focused:r("focused")}}function a5(e){let t=new Map,r=e.indexOf(" "),a=e.lastIndexOf(">");if(r<0||a<=r)return t;let i=/([^\s=/>]+)\s*=\s*(["'])([\s\S]*?)\2/y,n=r;for(;n<a;){for(;n<a;){let t=e[n];if(" "!==t&&"\n"!==t&&"\r"!==t&&" "!==t)break;n+=1}if(n>=a)break;let r=e[n];if("/"===r||">"===r)break;i.lastIndex=n;let o=i.exec(e);if(!o)break;t.set(o[1],o[3]),n=i.lastIndex}return t}function a6(e,t){return e.get(t)??null}function a9(e){if(!e)return;let t=/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/.exec(e);if(!t)return;let r=Number(t[1]),a=Number(t[2]);return{x:r,y:a,width:Math.max(0,Number(t[3])-r),height:Math.max(0,Number(t[4])-a)}}function a7(e){return e?e.toLowerCase():""}function ie(e){let t=e.trim();return!!t&&/^[\w.]+:id\/[\w.-]+$/i.test(t)}async function it(e,t={}){return function(e,t,r){let a=function(e){let t={type:null,label:null,value:null,identifier:null,depth:-1,children:[]},r=[t],a=/<node\b[^>]*>|<\/node>/g,i=a.exec(e);for(;i;){let t=i[0];if(t.startsWith("</node")){r.length>1&&r.pop(),i=a.exec(e);continue}let n=a8(t),o=a9(n.bounds),s=r[r.length-1],l={type:n.className,label:n.text||n.desc,value:n.text,identifier:n.resourceId,rect:o,enabled:n.enabled,hittable:n.clickable??n.focusable,depth:s.depth+1,parentIndex:void 0,children:[]};s.children.push(l),t.endsWith("/>")||r.push(l),i=a.exec(e)}return t}(e),i=[],n=!1,o=r.depth??1/0,s=r.scope?function(e,t){let r=t.toLowerCase(),a=[...e.children];for(;a.length>0;){let e=a.shift(),t=e.label?.toLowerCase()??"",i=e.value?.toLowerCase()??"",n=e.identifier?.toLowerCase()??"";if(t.includes(r)||i.includes(r)||n.includes(r))return e;a.push(...e.children)}return null}(a,r.scope):null,l=s?[s]:a.children,d=new Map,u=e=>{let t=d.get(e);if(void 0!==t)return t;for(let t of e.children)if(t.hittable||u(t))return d.set(e,!0),!0;return d.set(e,!1),!1},c=(e,t,a,s=!1,l=!1)=>{var d,p,f,m,h,w;let g,v,I,A,y,b,S,_;if(i.length>=800){n=!0;return}if(t>o)return;let N=!!r.raw||(d=e,p=r,f=s,m=u(e),h=l,v=a7(d.type),I=!!(d.label&&d.label.trim().length>0),A=!!(d.identifier&&d.identifier.trim().length>0),y=I&&!ie(d.label??""),b=A&&!ie(d.identifier??""),S=(g=(w=v).split(".").pop()??w).includes("layout")||"viewgroup"===g||"view"===g,_="imageview"===v||"imagebutton"===v,p.interactiveOnly?!!d.hittable||!!(y||b)&&!_&&(!S||!!h)&&(f||m||h):p.compact?y||b||!!d.hittable:!S&&!_||!!d.hittable||!!y||!!b&&!!m||m),D=a;N&&(D=i.length,i.push({index:D,type:e.type??void 0,label:e.label??void 0,value:e.value??void 0,identifier:e.identifier??void 0,rect:e.rect,enabled:e.enabled,hittable:e.hittable,depth:t,parentIndex:a}));let E=s||!!e.hittable,k=l||function(e){if(!e)return!1;let t=a7(e);return t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")}(e.type);for(let r of e.children)if(c(r,t+1,D,E,k),n)return};for(let e of l)if(c(e,0,void 0,!1,!1),n)break;return n?{nodes:i,truncated:n}:{nodes:i}}(await ir(e),0,t)}async function ir(e){return el(()=>ia(e),{shouldRetry:io})}async function ia(e){var t,r,a;let i,n,o=await m("adb",rR(e,["exec-out","uiautomator","dump","/dev/tty"]),{allowFailure:!0});if(0===o.exitCode){let e=ii(o.stdout,o.stderr);if(e)return e}let s="/sdcard/window_dump.xml",l=await m("adb",rR(e,["shell","uiautomator","dump",s])),d=(t=s,r=l.stdout,a=l.stderr,i=`${r}
15
+ ${a}`,n=/dumped to:\s*(\S+)/i.exec(i),n?.[1]??t),u=await m("adb",rR(e,["shell","cat",d])),c=ii(u.stdout,u.stderr);if(!c)throw new I("COMMAND_FAILED","uiautomator dump did not return XML",{stdout:u.stdout,stderr:u.stderr});return c}function ii(e,t){let r=`${e}
16
+ ${t}`,a=r.indexOf("<?xml"),i=a>=0?a:r.indexOf("<hierarchy");if(i<0)return null;let n=r.lastIndexOf("</hierarchy>");if(n<0||n<i)return null;let o=r.slice(i,n+12).trim();return o.length>0?o:null}function io(e){if(!(e instanceof I)||"COMMAND_FAILED"!==e.code)return!1;let t=`${e.details?.stderr??""}`.toLowerCase();return!!(t.includes("device offline")||t.includes("device not found")||t.includes("transport error")||t.includes("connection reset")||t.includes("broken pipe")||t.includes("timed out")||t.includes("no such file or directory"))}async function is(e,t,r){await m("adb",rR(e,["shell","input","tap",String(t),String(r)]))}async function il(e,t,r,a,i,n=250){await m("adb",rR(e,["shell","input","swipe",String(t),String(r),String(a),String(i),String(n)]))}async function id(e){await m("adb",rR(e,["shell","input","keyevent","4"]))}async function iu(e){await m("adb",rR(e,["shell","input","keyevent","3"]))}async function ic(e){await m("adb",rR(e,["shell","input","keyevent","187"]))}async function ip(e,t,r,a=800){await m("adb",rR(e,["shell","input","swipe",String(t),String(r),String(t),String(r),String(a)]))}async function im(e,t){let r=iy(t);if(!r||"ok"!==await ib(e,t))try{let r=t.replace(/ /g,"%s");await m("adb",rR(e,["shell","input","text",r]))}catch(e){if(r&&function(e){if(!(e instanceof I)||"COMMAND_FAILED"!==e.code)return!1;let t=String(e.details?.stderr??"").toLowerCase();return!!(t.includes("exception occurred while executing 'text'")||t.includes("nullpointerexception")&&t.includes("inputshellcommand.sendtext"))}(e))throw new I("COMMAND_FAILED","Non-ASCII text input is not supported on this Android shell. Install an ADB keyboard IME or use ASCII input.",{textPreview:t.slice(0,32)},e instanceof Error?e:void 0);throw e}}async function ih(e,t,r){await is(e,t,r)}async function iw(e,t,r,a){let i=Array.from(a).length,n=iy(a),o=[{strategy:"input_text",clearPadding:12,minClear:8,maxClear:48}];n||(o.push({strategy:"clipboard_paste",clearPadding:12,minClear:8,maxClear:48}),o.push({strategy:"chunked_input",clearPadding:24,minClear:16,maxClear:96}));let s=null;for(let n of o){var l,d;await ih(e,t,r);let o=(l=i+n.clearPadding,d=n.minClear,Math.max(d,Math.min(n.maxClear,l)));if(await iS(e,o),"input_text"===n.strategy)await im(e,a);else if("clipboard_paste"===n.strategy){if("ok"!==await ib(e,a))continue}else await iA(e,a,1,15);if((s=await i_(e,t,r))===a)return}throw new I("COMMAND_FAILED","Android fill verification failed",{expected:a,actual:s??null})}async function ig(e,t,r=.6){let{width:a,height:i}=await iI(e),n=Math.floor(a*r),o=Math.floor(i*r),s=Math.floor(a/2),l=Math.floor(i/2),d=s,u=l,c=s,p=l;switch(t){case"up":u=l-Math.floor(o/2),p=l+Math.floor(o/2);break;case"down":u=l+Math.floor(o/2),p=l-Math.floor(o/2);break;case"left":d=s-Math.floor(n/2),c=s+Math.floor(n/2);break;case"right":d=s+Math.floor(n/2),c=s-Math.floor(n/2);break;default:throw new I("INVALID_ARGS",`Unknown direction: ${t}`)}await m("adb",rR(e,["shell","input","swipe",String(d),String(u),String(c),String(p),"300"]))}async function iv(e,t){for(let r=0;r<8;r+=1){let r="";try{r=await ir(e)}catch(t){let e=t instanceof Error?t.message:String(t);throw new I("UNSUPPORTED_OPERATION",`uiautomator dump failed: ${e}`)}if(function(e,t){let r=t.toLowerCase(),a=/<node[^>]+>/g,i=a.exec(e);for(;i;){let t=a5(i[0]),n=(a6(t,"text")??"").toLowerCase(),o=(a6(t,"content-desc")??"").toLowerCase();if(n.includes(r)||o.includes(r)){let e=a9(a6(t,"bounds"));if(e)return{x:Math.floor(e.x+e.width/2),y:Math.floor(e.y+e.height/2)};return{x:0,y:0}}i=a.exec(e)}return null}(r,t))return;await ig(e,"down",.5)}throw new I("COMMAND_FAILED",`Could not find element containing "${t}" after scrolling`)}async function iI(e){let t=(await m("adb",rR(e,["shell","wm","size"]))).stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(!t)throw new I("COMMAND_FAILED","Unable to read screen size");return{width:Number(t[1]),height:Number(t[2])}}async function iA(e,t,r,a){let i=Math.max(1,Math.floor(r)),n=Array.from(t);for(let t=0;t<n.length;t+=i){let r=n.slice(t,t+i).join("");await im(e,r),a>0&&t+i<n.length&&await rF(a)}}function iy(e){for(let t of e){let e=t.codePointAt(0);if(void 0!==e&&(e<32||e>126))return!0}return!1}async function ib(e,t){let r=await m("adb",rR(e,["shell","cmd","clipboard","set","text",t]),{allowFailure:!0});return 0!==r.exitCode?"failed":r$(r.stdout,r.stderr)?"unsupported":0===(await m("adb",rR(e,["shell","input","keyevent","KEYCODE_PASTE"]),{allowFailure:!0})).exitCode||0===(await m("adb",rR(e,["shell","input","keyevent","279"]),{allowFailure:!0})).exitCode?"ok":"failed"}async function iS(e,t){let r=Math.max(0,t);await m("adb",rR(e,["shell","input","keyevent","KEYCODE_MOVE_END"]),{allowFailure:!0});for(let t=0;t<r;t+=24){let a=Math.min(24,r-t);await m("adb",rR(e,["shell","input","keyevent",...Array(a).fill("KEYCODE_DEL")]),{allowFailure:!0})}}async function i_(e,t,r){let a,i=await ir(e),n=/<node\b[^>]*>/g,o=null,s=null,l=null;for(;null!==(a=n.exec(i));){let e=a8(a[0]),i=a9(e.bounds);if(!i)continue;let n=e.className??"",d=(e.text??"").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),u=e.focused??!1;if(!d)continue;let c=Math.max(1,i.width*i.height),p=t>=i.x&&t<=i.x+i.width&&r>=i.y&&r<=i.y+i.height;if(u&&iN(n)){(!o||c<=o.area)&&(o={text:d,area:c});continue}if(p&&iN(n)){(!s||c<=s.area)&&(s={text:d,area:c});continue}p&&(!l||c<=l.area)&&(l={text:d,area:c})}return o?.text??s?.text??l?.text??null}function iN(e){let t=e.toLowerCase();return t.includes("edittext")||t.includes("textfield")}async function iD(e){let t=await m("adb",rR(e,["shell","dumpsys","input_method"]),{allowFailure:!0});if(0!==t.exitCode)throw new I("COMMAND_FAILED","Failed to query Android keyboard state",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});return function(e){let t=function(e){let t=new Map;for(let r of e.matchAll(/\b(mInputShown|mIsInputViewShown|isInputViewShown)=([a-zA-Z]+)\b/g)){let e=r[1],a=r[2]?.toLowerCase();e&&("true"===a||"false"===a)&&t.set(e,"true"===a)}if(0===t.size)return null;for(let e of t.values())if(e)return!0;return!1}(e),r=t??!1;if(null===t){let t=e.match(/\bmImeWindowVis=0x([0-9a-fA-F]+)\b/);if(t?.[1]){let e=Number.parseInt(t[1],16);Number.isNaN(e)||(r=(1&e)!=0)}}let a=Array.from(e.matchAll(/\binputType=0x([0-9a-fA-F]+)\b/gi)),i=a.length>0?a[a.length-1]?.[1]:void 0,n=i?`0x${i.toLowerCase()}`:void 0;return{visible:r,inputType:n,type:n?function(e){let t=Number.parseInt(e.replace(/^0x/i,""),16);if(Number.isNaN(t))return"unknown";let r=15&t;if(2===r)return"number";if(3===r)return"phone";if(4===r)return"datetime";if(1!==r)return"unknown";let a=4080&t;return 32===a||208===a?"email":128===a||224===a||144===a?"password":"text"}(n):void 0}}(t.stdout)}async function iE(e){let t=await iD(e),r=t,a=0;for(;r.visible&&a<2;)await id(e),a+=1,await rF(120),r=await iD(e);return{attempts:a,wasVisible:t.visible,dismissed:t.visible&&!r.visible,visible:r.visible,inputType:r.inputType,type:r.type}}async function ik(e){let t,r;return(r=(t=(await ix(e,["shell","cmd","clipboard","get","text"],"read")).replace(/\r\n/g,"\n").replace(/\n$/,"")).match(/^clipboard text:\s*(.*)$/i))?r[1]??"":"null"===t.trim().toLowerCase()?"":t}async function iM(e,t){await ix(e,["shell","cmd","clipboard","set","text",t],"write")}async function ix(e,t,r){let a=await m("adb",rR(e,t),{allowFailure:!0});if(r$(a.stdout,a.stderr))throw new I("UNSUPPORTED_OPERATION",`Android shell clipboard ${r} is not supported on this device.`);if(0!==a.exitCode)throw new I("COMMAND_FAILED",`Failed to ${r} Android clipboard text`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return a.stdout}let iO=["camera","microphone","photos","contacts","contacts-limited","notifications","calendar","location","location-always","media-library","motion","reminders","siri"];function iL(e){let t=e.trim().toLowerCase();if("grant"===t)return"grant";if("deny"===t)return"deny";if("reset"===t)return"reset";throw new I("INVALID_ARGS",`Invalid permission action: ${e}. Use grant|deny|reset.`)}function iC(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 I("INVALID_ARGS",`permission setting requires a target: ${iO.join("|")}`)}function iP(e){let t=e.trim().toLowerCase();if("light"===t)return"light";if("dark"===t)return"dark";if("toggle"===t)return"toggle";throw new I("INVALID_ARGS",`Invalid appearance state: ${e}. Use light|dark|toggle.`)}async function iR(e,t,r,a,i){switch(t.toLowerCase()){case"wifi":{let t=i$(r);await m("adb",rR(e,["shell","svc","wifi",t?"enable":"disable"]));return}case"airplane":{let t=i$(r);await m("adb",rR(e,["shell","settings","put","global","airplane_mode_on",t?"1":"0"])),await m("adb",rR(e,["shell","am","broadcast","-a","android.intent.action.AIRPLANE_MODE","--ez","state",t?"true":"false"]));return}case"location":{let t=i$(r);await m("adb",rR(e,["shell","settings","put","secure","location_mode",t?"3":"0"]));return}case"appearance":{let t=await iF(e,r);await m("adb",rR(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 I("INVALID_ARGS",`Invalid fingerprint state: ${e}. Use match|nonmatch.`)}(r);await iT(e,t);return}case"permission":{if(!a)throw new I("INVALID_ARGS","permission setting requires an active app in session");let t=iL(r),n=function(e,t){let r=iC(e);if(t?.trim())throw new I("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 I("INVALID_ARGS",`Unsupported permission target on Android: ${e}. Use camera|microphone|photos|contacts|notifications.`)}(i?.permissionTarget,i?.permissionMode);if("notifications"===n.kind)return void await iV(e,a,t,n);let o="grant"===t?"grant":"revoke";if("photos"===n.type)return void await iU(e,a,o);await m("adb",rR(e,["shell","pm",o,a,n.value]));return}default:throw new I("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function iT(e,t){var r;let a,i,n=(r=e,i=[["shell","cmd","fingerprint","touch",a="match"===t?"1":"9999"],["shell","cmd","fingerprint","finger",a]],"emulator"===r.kind&&i.push(["emu","finger","touch",a]),i),o=[];for(let t of n){let r=await m("adb",rR(e,t),{allowFailure:!0});if(0===r.exitCode)return;o.push({args:t,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}let s=o.map(e=>({args:e.args.join(" "),exitCode:e.exitCode,stderr:e.stderr.slice(0,400)}));if(o.length>0&&o.every(e=>{var t,r;let a;return t=e.stdout,r=e.stderr,(a=`${t}
17
+ ${r}`.toLowerCase()).includes("unknown command")||a.includes("can't find service: fingerprint")||a.includes("service fingerprint was not found")||a.includes("fingerprint cmd unavailable")||a.includes("emu command is not supported")||a.includes("emulator console is not running")||a.includes("fingerprint")&&a.includes("not found")}))throw new I("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 I("COMMAND_FAILED","Failed to simulate Android fingerprint.",{deviceId:e.id,action:t,attempts:s})}function i$(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 I("INVALID_ARGS",`Invalid setting state: ${e}`)}async function iF(e,t){let r=iP(t);if("toggle"!==r)return r;let a=await m("adb",rR(e,["shell","cmd","uimode","night"]),{allowFailure:!0});if(0!==a.exitCode)throw new I("COMMAND_FAILED","Failed to read current Android appearance",{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});let i=function(e,t){let r=/night mode:\s*(yes|no|auto)\b/i.exec(`${e}
18
+ ${t}`);if(!r)return null;let a=r[1].toLowerCase();return"yes"===a?"dark":"no"===a?"light":"auto"===a?"auto":null}(a.stdout,a.stderr);if(!i)throw new I("COMMAND_FAILED","Unable to determine current Android appearance for toggle",{stdout:a.stdout,stderr:a.stderr});return"auto"===i?"dark":"dark"===i?"light":"dark"}async function iU(e,t,r){let a=await iG(e),i=[];for(let n of null!==a&&a>=33?["android.permission.READ_MEDIA_IMAGES","android.permission.READ_EXTERNAL_STORAGE"]:["android.permission.READ_EXTERNAL_STORAGE","android.permission.READ_MEDIA_IMAGES"]){let a=await m("adb",rR(e,["shell","pm",r,t,n]),{allowFailure:!0});if(0===a.exitCode)return;i.push({permission:n,stderr:a.stderr,exitCode:a.exitCode})}throw new I("COMMAND_FAILED",`Failed to ${r} Android photos permission`,{appPackage:t,sdkInt:a,attempts:i})}async function iV(e,t,r,a){"grant"===r?await m("adb",rR(e,["shell","pm","grant",t,a.permission]),{allowFailure:!0}):(await m("adb",rR(e,["shell","pm","revoke",t,a.permission]),{allowFailure:!0}),"reset"===r&&(await m("adb",rR(e,["shell","pm","clear-permission-flags",t,a.permission,"user-set"]),{allowFailure:!0}),await m("adb",rR(e,["shell","pm","clear-permission-flags",t,a.permission,"user-fixed"]),{allowFailure:!0}))),await m("adb",rR(e,["shell","appops","set",t,a.appOps,"grant"===r?"allow":"deny"===r?"deny":"default"]))}async function iG(e){let t=await m("adb",rR(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}async function iB(e,t,r){let a="string"==typeof r.action&&r.action.trim()?r.action.trim():`${t}.TEST_PUSH`,i=["shell","am","broadcast","-a",a,"-p",t],n="string"==typeof r.receiver?r.receiver.trim():"";n&&i.push("-n",n);let o=r.extras;if(void 0!==o&&("object"!=typeof o||null===o||Array.isArray(o)))throw new I("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 I("INVALID_ARGS",`Unsupported Android broadcast extra type for "${t}". Use string, boolean, or number.`)}(i,e,t),s+=1);return await m("adb",rR(e,i)),{action:a,extrasCount:s}}let ij=Buffer.from([137,80,78,71,13,10,26,10]),iq={enableDemoMode:iW,settle:rF,capture:iJ,disableDemoMode:iz};async function iH(e,t,r=iq){await r.enableDemoMode(e);try{await r.settle(1e3),await r.capture(e,t)}finally{await r.disableDemoMode(e).catch(()=>{})}}async function iW(e){let t=t=>m("adb",rR(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 iz(e){await m("adb",rR(e,["shell","am broadcast -a com.android.systemui.demo -e command exit"]),{allowFailure:!0})}async function iJ(e,t){let r=await m("adb",rR(e,["exec-out","screencap","-p"]),{binaryStdout:!0});if(!r.stdoutBuffer)throw new I("COMMAND_FAILED","Failed to capture screenshot");let a=r.stdoutBuffer.indexOf(ij);if(a<0)throw new I("COMMAND_FAILED","Screenshot data does not contain a valid PNG header");let i=function(e,t){let r=t+ij.length;for(;r+8<=e.length;){let t=e.readUInt32BE(r),a=r+4,i=e.toString("ascii",a,a+4),n=r+12+t;if(n>e.length)break;if("IEND"===i)return n;r=n}return null}(r.stdoutBuffer,a);if(!i)throw new I("COMMAND_FAILED","Screenshot data does not contain a complete PNG payload");await P.writeFile(t,r.stdoutBuffer.subarray(a,i))}let iX=ek(process.env.AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS,ei,5e3),iK=ek(process.env.AGENT_DEVICE_IOS_SIMCTL_LIST_TIMEOUT_MS,ea,1e3),iY=ek(process.env.AGENT_DEVICE_IOS_APP_LAUNCH_TIMEOUT_MS,3e4,5e3),iZ=ek(process.env.AGENT_DEVICE_IOS_DEVICECTL_TIMEOUT_MS,2e4,1e3),iQ=ek(process.env.AGENT_DEVICE_IOS_SIMULATOR_FOCUS_TIMEOUT_MS,1e4,1e3),i0=ek(process.env.AGENT_DEVICE_IOS_SIMULATOR_SCREENSHOT_TIMEOUT_MS,2e4,1e3),i1=ek(process.env.AGENT_DEVICE_IOS_RUNNER_SCREENSHOT_COPY_TIMEOUT_MS,2e4,1e3);async function i2(e,t){let r=["devicectl",...e],a=await m("xcrun",r,{allowFailure:!0,timeoutMs:iZ});if(0===a.exitCode)return;let i=String(a.stdout??""),n=String(a.stderr??"");throw new I("COMMAND_FAILED",`Failed to ${t.action}`,{cmd:"xcrun",args:r,exitCode:a.exitCode,stdout:i,stderr:n,deviceId:t.deviceId,hint:i5(i,n)??i8})}async function i3(e,t){let r=o.join(V.tmpdir(),`agent-device-ios-apps-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),a=["devicectl","device","info","apps","--device",e.id,"--include-all-apps","--json-output",r],i=await m("xcrun",a,{allowFailure:!0,timeoutMs:iZ});try{var n,s;if(0!==i.exitCode){let t=String(i.stdout??""),r=String(i.stderr??"");throw new I("COMMAND_FAILED","Failed to list iOS apps",{cmd:"xcrun",args:a,exitCode:i.exitCode,stdout:t,stderr:r,deviceId:e.id,hint:i5(t,r)??i8})}let o=await P.readFile(r,"utf8");return n=i4(JSON.parse(o)),s=t,"user-installed"===s?n.filter(e=>!e.bundleId.startsWith("com.apple.")):n}catch(t){if(t instanceof I)throw t;throw new I("COMMAND_FAILED","Failed to parse iOS apps list",{deviceId:e.id,cause:String(t)})}finally{await P.unlink(r).catch(()=>{})}}function i4(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 a="string"==typeof e.name&&e.name.trim().length>0?e.name.trim():t;r.push({bundleId:t,name:a})}return r}let i8="Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.";function i5(e,t){let r=`${e}
19
+ ${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}function i6(e){if(!(e instanceof I)||"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 i9(e,t){let r=await m("xcrun",e$(e,["get_app_container",e.id,t]),{allowFailure:!0});if(0!==r.exitCode)return{installed:!1};let a=r.stdout.trim();if(!a)return{installed:!1};let i=await m("plutil",["-extract","CFBundleExecutable","raw","-o","-",`${a}/Info.plist`],{allowFailure:!0});if(0!==i.exitCode||!i.stdout.trim())return{installed:!0};let n=i.stdout.trim(),o=`${a}/${n}`,s=await m("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 i7(e,t){if("simulator"!==e.kind)throw new I("UNSUPPORTED_OPERATION",`${t} is only supported on iOS simulators`)}async function ne(){await m("open",["-a","Simulator"],{allowFailure:!0,timeoutMs:iQ})}async function nt(e){let t,r;if("simulator"!==e.kind||"Booted"===await na(e))return;let a=eo.fromTimeoutMs(iX);try{await es(async({deadline:a})=>{if(a?.isExpired())throw new I("COMMAND_FAILED","iOS simulator boot deadline exceeded",{timeoutMs:iX});let i=Math.max(1e3,a?.remainingMs()??iX),n=await m("xcrun",e$(e,["boot",e.id]),{allowFailure:!0,timeoutMs:i});t={stdout:String(n.stdout??""),stderr:String(n.stderr??""),exitCode:n.exitCode};let o=`${t.stdout}
20
+ ${t.stderr}`.toLowerCase(),s=o.includes("already booted")||o.includes("current state: booted");if(0!==t.exitCode&&!s)throw new I("COMMAND_FAILED","simctl boot failed",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let l=await m("xcrun",e$(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 I("COMMAND_FAILED","simctl bootstatus failed",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});let d=await na(e);if("Booted"!==d)throw new I("COMMAND_FAILED","Simulator is still booting",{state:d})},{maxAttempts:3,baseDelayMs:500,maxDelayMs:2e3,jitter:.2,shouldRetry:e=>{let a=eb({error:e,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});return"IOS_BOOT_TIMEOUT"!==a&&"CI_RESOURCE_STARVATION_SUSPECTED"!==a}},{deadline:a,phase:"boot",classifyReason:e=>eb({error:e,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}})})}catch(n){let i=eb({error:n,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});throw new I("COMMAND_FAILED","iOS simulator failed to boot",{platform:"ios",deviceId:e.id,timeoutMs:iX,elapsedMs:a.elapsedMs(),reason:i,hint:eS(i),boot:t,bootstatus:r})}}async function nr(e){let t=e$(e,["shutdown",e.id]),r=await m("xcrun",t,{allowFailure:!0,timeoutMs:15e3});return{success:0===r.exitCode,exitCode:r.exitCode,stdout:String(r.stdout??""),stderr:String(r.stderr??"")}}async function na(e){let t="string"==typeof e?e:e.id,r="string"==typeof e?eT(["list","devices","-j"]):e$(e,["list","devices","-j"]),a=await m("xcrun",r,{allowFailure:!0,timeoutMs:iK});if(0!==a.exitCode)return null;try{let e=JSON.parse(String(a.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 ni(e,t){try{let r=await m("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{let r=await P.readFile(e,"utf8");return function(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=e.match(RegExp(`<key>\\s*${r}\\s*<\\/key>\\s*<string>([\\s\\S]*?)<\\/string>`,"i"));if(!a?.[1])return;let i=a[1].trim().replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&amp;/g,"&");return i.length>0?i:void 0}(r,t)}catch{return}}async function nn(e,t){if("url"===e.kind&&!am(e.url))throw new I("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 r=await au({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||am(e.url),signal:t?.signal}),a=await ns(r.installablePath,t),i=await no(a.installPath);return{archivePath:r.archivePath??(r.installablePath.toLowerCase().endsWith(".ipa")?r.installablePath:void 0),installablePath:a.installPath,bundleId:i.bundleId,appName:i.appName,cleanup:async()=>{await a.cleanup(),await r.cleanup()}}}async function no(e){let t=o.join(e,"Info.plist"),[r,a,i]=await Promise.all([ni(t,"CFBundleIdentifier"),ni(t,"CFBundleDisplayName"),ni(t,"CFBundleName")]);return{bundleId:r,appName:a??i}}async function ns(e,t){if(!e.toLowerCase().endsWith(".ipa"))return{installPath:e,cleanup:async()=>{}};let r=await P.mkdtemp(o.join(V.tmpdir(),"agent-device-ios-ipa-")),a=async()=>{await P.rm(r,{recursive:!0,force:!0})};try{await m("ditto",["-x","-k",e,r]);let i=o.join(r,"Payload"),n=(await P.readdir(i,{withFileTypes:!0}).catch(()=>{throw new I("INVALID_ARGS","Invalid IPA: missing Payload directory")})).filter(e=>e.isDirectory()&&e.name.toLowerCase().endsWith(".app")).map(e=>({installPath:o.join(i,e.name),bundleName:e.name.replace(/\.app$/i,"")}));if(1===n.length)return{installPath:n[0].installPath,cleanup:a};if(0===n.length)throw new I("INVALID_ARGS","Invalid IPA: expected at least one .app under Payload, found 0");await nl(n);let s=t?.appIdentifierHint?.trim();if(s){let e=function(e,t){let r=t.toLowerCase(),a=e.filter(e=>e.bundleName.toLowerCase()===r);if(1===a.length)return a[0];if(a.length>1)throw new I("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]}}(n,s);if(e)return{installPath:e.installPath,cleanup:a};throw new I("INVALID_ARGS",`Invalid IPA: found ${n.length} .app bundles under Payload and none matched "${s}". Available bundles: ${n.map(nd).join(", ")}`)}throw new I("INVALID_ARGS",`Invalid IPA: found ${n.length} .app bundles under Payload. Pass an app identifier or bundle name matching one of: ${n.map(nd).join(", ")}`)}catch(e){throw await a(),e}}async function nl(e){await Promise.all(e.map(async e=>{if(e.bundleId&&e.appName)return;let t=await no(e.installPath);e.bundleId=e.bundleId??t.bundleId,e.appName=e.appName??t.appName}))}function nd(e){let t=e.bundleId??e.appName;return t?`${e.bundleName}.app (${t})`:`${e.bundleName}.app`}function nu(e,t){return"user-installed"===t?e.filter(e=>!e.bundleId.startsWith("com.apple.")):e}let nc="agent-device-macos-helper",np="AGENT_DEVICE_MACOS_HELPER_BIN",nf=o.join(V.homedir(),".agent-device","macos-helper","current"),nm=o.join(nf,"manifest.json"),nh=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;function nw(e){let t=e.trim();if(!nh.test(t))throw new I("INVALID_ARGS","macOS bundle id must use reverse-DNS form like com.example.App",{bundleId:e});return t}function ng(){return function(e){let t=o.dirname(e);for(;;){let e=o.join(t,"macos-helper");if(d(o.join(e,"Package.swift")))return e;let r=o.dirname(t);if(r===t)break;t=r}throw new I("COMMAND_FAILED","Unable to locate macOS helper package root",{modulePath:e})}(b(import.meta.url))}async function nv(e){let t=await P.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let r=o.join(e,t.name);return t.isDirectory()?".build"===t.name?[]:await nv(r):t.isFile()&&(t.name.endsWith(".swift")||"Package.swift"===t.name)?[r]:[]}))).flat().sort()}async function nI(e){let t=await nv(e),r=_("sha256");for(let a of t)r.update(o.relative(e,a)),r.update("\0"),r.update(await P.readFile(a)),r.update("\0");let a=await m("swift",["--version"],{allowFailure:!0,cwd:e,timeoutMs:1e4});return r.update("swift-version"),r.update("\0"),r.update(a.stdout||a.stderr||`exit:${a.exitCode}`),r.update("\0"),r.digest("hex")}async function nA(){try{let e=JSON.parse(await P.readFile(nm,"utf8"));return"string"==typeof e.fingerprint?e.fingerprint:null}catch{return null}}async function ny(){let e=process.env[np]?.trim();if(e)return e;let t=ng(),r=await nI(t),a=o.join(nf,nc);try{if(await nA()===r)return await P.access(a),a}catch{}let i=o.join(ng(),".build","release",nc);process.stderr.write("agent-device: building macOS helper (first run or helper update)\n"),await m("swift",["build","-c","release","--package-path",t],{cwd:t,timeoutMs:12e4}),await P.mkdir(nf,{recursive:!0});let n=`${a}.tmp`;return await P.copyFile(i,n),await P.rename(n,a),await P.chmod(a,493),await P.writeFile(nm,`${JSON.stringify({fingerprint:r},null,2)}
21
+ `,"utf8"),a}async function nb(e){let t=process.env[np]?.trim();if("darwin"!==process.platform&&!t)throw new I("UNSUPPORTED_PLATFORM","macOS helper is only available on macOS");let r=await ny(),a=await m(r,e,{allowFailure:!0,timeoutMs:3e4}),i=a.stdout.trim(),n=null;if(i)try{n=JSON.parse(i)}catch{n=null}if(0===a.exitCode&&n?.ok)return n.data;throw new I("COMMAND_FAILED",n&&!n.ok?n.error?.message??`macOS helper exited with code ${a.exitCode}`:i||a.stderr.trim()||`macOS helper exited with code ${a.exitCode}`,{helperPath:r,args:e,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,...n&&!n.ok?n.error?.details:{}})}async function nS(){return await nb(["app","frontmost"])}async function n_(e){return await nb(["app","quit","--bundle-id",nw(e)])}async function nN(e,t){return await nb(["permission",e,t])}async function nD(e,t={}){let r=["alert",e];return t.bundleId&&r.push("--bundle-id",nw(t.bundleId)),t.surface&&r.push("--surface",t.surface),await nb(r)}async function nE(e){return await nb(["snapshot","--surface",e])}async function nk(e,t,r={}){let a=["read","--x",String(e),"--y",String(t)];return r.bundleId&&a.push("--bundle-id",nw(r.bundleId)),r.surface&&a.push("--surface",r.surface),await nb(a)}let nM={settings:"com.apple.systempreferences"},nx=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/;function nO(e,t){let r=["-b",e];return t&&r.push(t),r}async function nL(e){for(let t of[o.join(e,"Contents","Info.plist"),o.join(e,"Info.plist")]){let[e,r,a]=await Promise.all([ni(t,"CFBundleIdentifier"),ni(t,"CFBundleDisplayName"),ni(t,"CFBundleName")]);if(e||r||a)return{bundleId:e,appName:r??a}}return{}}async function nC(e){let t=e.trim(),r=nM[t.toLowerCase()];if(r)return r;let a=(await nV("all")).filter(e=>e.name.toLowerCase()===t.toLowerCase());if(1===a.length)return a[0].bundleId;if(a.length>1)throw new I("INVALID_ARGS",`Multiple apps matched "${e}"`,{matches:a});if(nx.test(t))return t;throw new I("APP_NOT_INSTALLED",`No app found matching "${e}"`)}async function nP(e,t,r){let a=r?.url?.trim();if(a){if(!rU(a))throw new I("INVALID_ARGS","open <app> <url> requires a valid URL target");let e=r?.appBundleId??await nC(t);await m("open",nO(e,a));return}let i=t.trim();if(rU(i))return void await m("open",[i]);let n=r?.appBundleId??await nC(i);await m("open",nO(n))}async function nR(e,t){let r=await nC(t),a=await n_(r);if(a.running&&!a.terminated&&!a.forceTerminated)throw new I("COMMAND_FAILED",`Failed to close macOS app ${t}`,{bundleId:r,running:a.running,terminated:a.terminated,forceTerminated:a.forceTerminated})}async function nT(){let e=await m("pbpaste",[],{allowFailure:!0});if(0!==e.exitCode)throw new I("COMMAND_FAILED","Failed to read macOS clipboard",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode});return e.stdout.replace(/\r\n/g,"\n").replace(/\n$/,"")}async function n$(e){let t=await m("pbcopy",[],{allowFailure:!0,stdin:e});if(0!==t.exitCode)throw new I("COMMAND_FAILED","Failed to write macOS clipboard",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode})}async function nF(){let e=await m("osascript",["-e",'tell application "System Events" to tell appearance preferences to get dark mode'],{allowFailure:!0});if(0!==e.exitCode)throw new I("COMMAND_FAILED","Failed to read macOS appearance",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode});let t=e.stdout.trim().toLowerCase();if("true"===t)return!0;if("false"===t)return!1;throw new I("COMMAND_FAILED",`Unable to determine current macOS appearance from osascript output: ${e.stdout.trim()}`)}async function nU(e){let t=iP(e),r="toggle"===t?!await nF():"dark"===t,a=`tell application "System Events" to tell appearance preferences to set dark mode to ${r?"true":"false"}`,i=await m("osascript",["-e",a],{allowFailure:!0});if(0!==i.exitCode)throw new I("COMMAND_FAILED","Failed to set macOS appearance",{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode})}async function nV(e="all"){let t=["/Applications","/System/Applications",o.join(V.homedir(),"Applications")],r=new Set;for(let e of t){let t=await P.stat(e).catch(()=>null);if(!t?.isDirectory())continue;let a=await m("find",[e,"-maxdepth","4","-type","d","-name","*.app"],{allowFailure:!0});if(0===a.exitCode)for(let e of a.stdout.split("\n")){let t=e.trim();t&&r.add(t)}}return nu((await Promise.all(Array.from(r).map(async e=>{let t=await nL(e).catch(()=>({})),r=t.bundleId;return r?{bundleId:r,name:t.appName??o.basename(e,".app")}:null}))).filter(e=>null!==e).sort((e,t)=>e.name.localeCompare(t.name)),e)}let nG=["--time","9:41","--dataNetwork","wifi","--wifiMode","active","--wifiBars","3","--batteryState","charged","--batteryLevel","100"],nB={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"},nj={1:"searching",2:"failed",3:"active"},nq={0:"notSupported",1:"searching",2:"failed",3:"active"};function nH(e,t,r){return m("xcrun",e$(e,t),r)}async function nW(e,t){var r,a;let i;await nJ(e),t&&await nX(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||(a=r.dataNetwork)&&"hide"!==a&&"wifi"!==a||void 0!==r.operatorName)&&i.push("--cellularBars",r.cellularBars),void 0!==r.operatorName&&i.push("--operatorName",r.operatorName),i))}async function nz(e){let t=await nH(e,["status_bar",e.id,"list"],{allowFailure:!0});if(0!==t.exitCode)throw new I("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]),a=nB[r];if(!a)throw new I("COMMAND_FAILED",`Unsupported simulator data network type: ${r}`);t.dataNetwork=a;continue}let a=/^WiFi Mode:\s+(\d+),\s+WiFi Bars:\s+(\d+)$/.exec(r);if(a){let e=nj[Number(a[1])];e&&(t.wifiMode=e),t.wifiBars=a[2];continue}let i=/^Cell Mode:\s+(\d+),\s+Cell Bars:\s+(\d+)$/.exec(r);if(i){let e=Number(i[1]),r=nq[e];if(!r)throw new I("COMMAND_FAILED",`Unsupported simulator cellular mode: ${e}`);t.cellularMode=r,t.cellularBars=i[2];continue}let n=/^Operator Name:\s*(.*)$/.exec(r);if(n){t.operatorName=n[1]??"";continue}}return 0===Object.keys(t).length?null:t}(t.stdout)}async function nJ(e){await nH(e,["status_bar",e.id,"clear"])}async function nX(e,t){0!==t.length&&await nH(e,["status_bar",e.id,"override",...t])}function nK(e,t,r){C({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...function(e){if(!(e instanceof I))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}}(r)}})}function nY(e,t,r){return m("xcrun",e$(e,t),r)}let nZ={ensureBooted:nt,prepareStatusBarForScreenshot:async function e(e){let t=null,r=!1;try{t=await nz(e),r=!0}catch(t){nK(e,"snapshot_failed",t)}try{await nJ(e),await nX(e,nG)}catch(t){nK(e,"prepare_failed",t)}return async()=>{await nW(e,r?t:null)}},captureWithRetry:n1,captureWithRunner:n2,shouldFallbackToRunner:n7};async function nQ(e,t,r){if("macos"===e.platform)return void await n2(e,t,r);if("simulator"===e.kind)return void await n0(e,t,r);try{await i2(["device","screenshot","--device",e.id,t],{action:"capture iOS screenshot",deviceId:e.id});return}catch(t){if(!function(e){if(!(e instanceof I)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},r="string"==typeof t.stdout?t.stdout:"",a="string"==typeof t.stderr?t.stderr:"",i=`${e.message}
21
22
  ${r}
22
- ${a}`.toLowerCase();return i.includes("unknown option '--device'")||i.includes("unknown subcommand")&&i.includes("screenshot")||i.includes("unrecognized subcommand")&&i.includes("screenshot")}(t))throw t;nM(e,"devicectl_screenshot",t)}await nk(e,t,r)}async function nD(e,t,r,a=nN){if("simulator"!==e.kind)throw new w("UNSUPPORTED_OPERATION","Simulator screenshot fallback flow supports only iOS simulators");await a.ensureBooted(e);let i=async()=>{};try{i=await a.prepareStatusBarForScreenshot(e)}catch(t){nC(e,"prepare_failed",t)}try{try{await a.captureWithRetry(e,t);return}catch(t){if(!a.shouldFallbackToRunner(t))throw t;nM(e,"simctl_screenshot",t)}await a.captureWithRunner(e,t,r)}finally{await i().catch(t=>nC(e,"restore_failed",t))}}async function nE(e,t){let r=ee.fromTimeoutMs(ij);await iQ(),await et(async({attempt:r,deadline:a})=>{r>1&&await iQ(),await nS(e,["io",e.id,"screenshot",t],{timeoutMs:Math.max(1e3,a?.remainingMs()??ij)})},{maxAttempts:5,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>nP(e)},{deadline:r,phase:"ios_simulator_screenshot"})}async function nk(e,t,r){let a=(await tA(e,{command:"screenshot",appBundleId:r})).message;if(!a)throw new w("COMMAND_FAILED","Failed to capture iOS screenshot: runner returned no file path");"macos"===e.platform?await O.copyFile(a,t):"simulator"===e.kind?await nO(e,a,t):await nL(e,a,t)}async function nL(e,t,r){let a=ee.fromTimeoutMs(iq),i={exitCode:1,stdout:"",stderr:""};for(let n of e5)if(0===(i=await c("xcrun",["devicectl","device","copy","from","--device",e.id,"--source",t,"--destination",r,"--domain-type","appDataContainer","--domain-identifier",n],{allowFailure:!0,timeoutMs:nx(a,iq,"runner screenshot copy")})).exitCode)return;let n=i.stderr.trim()||i.stdout.trim()||`devicectl exited with code ${i.exitCode}`;throw new w("COMMAND_FAILED",`Failed to capture iOS screenshot: ${n}`)}async function nO(e,t,r){let a=ee.fromTimeoutMs(iq),n="Unable to locate runner container for simulator screenshot";for(let o of e5){let s=await nS(e,["get_app_container",e.id,o,"data"],{allowFailure:!0,timeoutMs:nx(a,iq,"runner screenshot container lookup")});if(0!==s.exitCode){let e=s.stderr.trim();e&&(n=e);continue}let l=s.stdout.trim();if(!l){n="simctl get_app_container returned empty output";continue}for(let e of function(e,t){let r=i.resolve(e),a=t.trim();if(!a)return[];let n=[],o=new Set,s=e=>{let t=i.normalize(e);o.has(t)||(o.add(t),n.push(t))},l=a.replace(/^\/+/,""),d=l.replace(/\\/g,"/");if(l&&s(i.join(r,l)),i.isAbsolute(a)&&s(i.normalize(a)),d.startsWith("tmp/"))s(i.join(r,d));else{let e=d.lastIndexOf("/tmp/");if(e>=0){let t=d.slice(e+1);s(i.join(r,t))}}let u=i.basename(a);return u&&s(i.join(r,"tmp",u)),n}(l,t))try{await O.copyFile(e,r);return}catch(e){n=e instanceof Error?e.message:String(e)}}throw new w("COMMAND_FAILED",`Failed to capture iOS screenshot: ${n}`)}function nx(e,t,r){let a=e.remainingMs();if(a>0)return a;throw new w("COMMAND_FAILED",`iOS ${r} timed out after ${t}ms`,{timeoutMs:t,step:r})}function nM(e,t,r){let a=nR(r);L({level:"warn",phase:"ios_screenshot_fallback",data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:t,to:"runner",...a}})}function nC(e,t,r){L({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...nR(r)}})}function nR(e){if(!(e instanceof w))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}}function nP(e){if(!(e instanceof w)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},r="string"==typeof t.stdout?t.stdout:"",a="string"==typeof t.stderr?t.stderr:"",i=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):"",n=`${e.message}
23
+ ${a}`.toLowerCase();return i.includes("unknown option '--device'")||i.includes("unknown subcommand")&&i.includes("screenshot")||i.includes("unrecognized subcommand")&&i.includes("screenshot")}(t))throw t;n5(e,"devicectl_screenshot",t)}await n2(e,t,r)}async function n0(e,t,r,a=nZ){if("simulator"!==e.kind)throw new I("UNSUPPORTED_OPERATION","Simulator screenshot fallback flow supports only iOS simulators");await a.ensureBooted(e);let i=async()=>{};try{i=await a.prepareStatusBarForScreenshot(e)}catch(t){n6(e,"prepare_failed",t)}try{try{await a.captureWithRetry(e,t);return}catch(t){if(!a.shouldFallbackToRunner(t))throw t;n5(e,"simctl_screenshot",t)}await a.captureWithRunner(e,t,r)}finally{await i().catch(t=>n6(e,"restore_failed",t))}}async function n1(e,t){let r=eo.fromTimeoutMs(i0);await ne(),await es(async({attempt:r,deadline:a})=>{r>1&&await ne(),await nY(e,["io",e.id,"screenshot",t],{timeoutMs:Math.max(1e3,a?.remainingMs()??i0)})},{maxAttempts:5,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>n7(e)},{deadline:r,phase:"ios_simulator_screenshot"})}async function n2(e,t,r){let a=(await tE(e,{command:"screenshot",appBundleId:r})).message;if(!a)throw new I("COMMAND_FAILED","Failed to capture iOS screenshot: runner returned no file path");"macos"===e.platform?await P.copyFile(a,t):"simulator"===e.kind?await n4(e,a,t):await n3(e,a,t)}async function n3(e,t,r){let a=eo.fromTimeoutMs(i1),i={exitCode:1,stdout:"",stderr:""};for(let n of ta)if(0===(i=await m("xcrun",["devicectl","device","copy","from","--device",e.id,"--source",t,"--destination",r,"--domain-type","appDataContainer","--domain-identifier",n],{allowFailure:!0,timeoutMs:n8(a,i1,"runner screenshot copy")})).exitCode)return;let n=i.stderr.trim()||i.stdout.trim()||`devicectl exited with code ${i.exitCode}`;throw new I("COMMAND_FAILED",`Failed to capture iOS screenshot: ${n}`)}async function n4(e,t,r){let a=eo.fromTimeoutMs(i1),i="Unable to locate runner container for simulator screenshot";for(let n of ta){let s=await nY(e,["get_app_container",e.id,n,"data"],{allowFailure:!0,timeoutMs:n8(a,i1,"runner screenshot container lookup")});if(0!==s.exitCode){let e=s.stderr.trim();e&&(i=e);continue}let l=s.stdout.trim();if(!l){i="simctl get_app_container returned empty output";continue}for(let e of function(e,t){let r=o.resolve(e),a=t.trim();if(!a)return[];let i=[],n=new Set,s=e=>{let t=o.normalize(e);n.has(t)||(n.add(t),i.push(t))},l=a.replace(/^\/+/,""),d=l.replace(/\\/g,"/");if(l&&s(o.join(r,l)),o.isAbsolute(a)&&s(o.normalize(a)),d.startsWith("tmp/"))s(o.join(r,d));else{let e=d.lastIndexOf("/tmp/");if(e>=0){let t=d.slice(e+1);s(o.join(r,t))}}let u=o.basename(a);return u&&s(o.join(r,"tmp",u)),i}(l,t))try{await P.copyFile(e,r);return}catch(e){i=e instanceof Error?e.message:String(e)}}throw new I("COMMAND_FAILED",`Failed to capture iOS screenshot: ${i}`)}function n8(e,t,r){let a=e.remainingMs();if(a>0)return a;throw new I("COMMAND_FAILED",`iOS ${r} timed out after ${t}ms`,{timeoutMs:t,step:r})}function n5(e,t,r){let a=n9(r);C({level:"warn",phase:"ios_screenshot_fallback",data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:t,to:"runner",...a}})}function n6(e,t,r){C({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...n9(r)}})}function n9(e){if(!(e instanceof I))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}}function n7(e){if(!(e instanceof I)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},r="string"==typeof t.stdout?t.stdout:"",a="string"==typeof t.stderr?t.stderr:"",i=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):"",n=`${e.message}
23
24
  ${r}
24
25
  ${a}
25
- ${i}`.toLowerCase();return n.includes("timeout waiting for screen surfaces")||n.includes("nsposixerrordomain")&&n.includes("code=60")&&n.includes("screenshot")||n.includes("timed out")&&n.includes("screenshot")}let nT={settings:"com.apple.Preferences"},n$=null;function nF(e,t,r){return c("xcrun",ex(e,t),r)}function nU(e){return e.includes("not installed")||e.includes("not found")||e.includes("no such file")}async function nV(e,t){if("macos"===e.platform)return await nn(t);let r=t.trim();if(r.includes("."))return r;let a=nT[r.toLowerCase()];if(a)return a;let i=("simulator"===e.kind?await nQ(e):await iW(e,"all")).filter(e=>e.name.toLowerCase()===r.toLowerCase());if(1===i.length)return i[0].bundleId;if(i.length>1)throw new w("INVALID_ARGS",`Multiple apps matched "${t}"`,{matches:i});throw new w("APP_NOT_INSTALLED",`No app found matching "${t}"`)}async function nG(e,t,r){if("macos"===e.platform)return void await no(e,t,r);let a=r?.url?.trim();if(a){if(!rk(a))throw new w("INVALID_ARGS","open <app> <url> requires a valid URL target");if("simulator"===e.kind){await i0(e),await iQ(),await nF(e,["openurl",e.id,a]);return}let i=rL(r?.appBundleId??await nV(e,t),a);if(!i)throw new w("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await n9(e,i,{payloadUrl:a});return}let i=t.trim();if(rk(i)){if("simulator"===e.kind){await i0(e),await iQ(),await nF(e,["openurl",e.id,i]);return}let t=rL(r?.appBundleId,i);if(!t)throw new w("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await n9(e,t,{payloadUrl:i});return}let n=r?.appBundleId??await nV(e,t);"simulator"===e.kind?await n5(e,n):await n9(e,n)}async function nB(e){"macos"===e.platform||"simulator"!==e.kind||"Booted"!==await i2(e)&&(await i0(e),await iQ())}async function nj(e,t){if("macos"===e.platform)return void await ns(e,t);let r=await nV(e,t);if("simulator"===e.kind){await i0(e);let t=ex(e,["terminate",e.id,r]),a=await c("xcrun",t,{allowFailure:!0});if(0!==a.exitCode){if(a.stderr.toLowerCase().includes("found nothing to terminate"))return;throw new w("COMMAND_FAILED",`xcrun exited with code ${a.exitCode}`,{cmd:"xcrun",args:t,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode})}return}await iH(["device","process","terminate","--device",e.id,r],{action:"terminate iOS app",deviceId:e.id})}async function nq(e,t){let r=await nV(e,t);if("simulator"!==e.kind){let t=["devicectl","device","uninstall","app","--device",e.id,r],a=await c("xcrun",t,{allowFailure:!0,timeoutMs:iG});if(0!==a.exitCode){let i=String(a.stdout??""),n=String(a.stderr??"");if(!nU(`${i}
26
- ${n}`.toLowerCase()))throw new w("COMMAND_FAILED",`Failed to uninstall iOS app ${r}`,{cmd:"xcrun",args:t,exitCode:a.exitCode,stdout:i,stderr:n,deviceId:e.id,hint:iK(i,n)??iJ})}return{bundleId:r}}await i0(e);let a=await nF(e,["uninstall",e.id,r],{allowFailure:!0});if(0!==a.exitCode&&!nU(`${a.stdout}
27
- ${a.stderr}`.toLowerCase()))throw new w("COMMAND_FAILED",`simctl uninstall failed for ${r}`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return{bundleId:r}}async function nH(e,t,r){let a=await i4({kind:"path",path:t},r);try{return await nz(e,a.installablePath),{archivePath:a.archivePath,installablePath:a.installablePath,bundleId:a.bundleId,appName:a.appName,launchTarget:a.bundleId}}finally{await a.cleanup()}}async function nW(e,t,r){let{bundleId:a}=await nq(e,t);return await nH(e,r,{appIdentifierHint:t}),{bundleId:a}}async function nz(e,t){"simulator"!==e.kind?await iH(["device","install","app","--device",e.id,t],{action:"install iOS app",deviceId:e.id}):(await i0(e),await nF(e,["install",e.id,t]))}async function nJ(e){if("macos"===e.platform)return await nl();iY(e,"clipboard"),await i0(e);let t=await nF(e,["pbpaste",e.id],{allowFailure:!0});if(0!==t.exitCode)throw new w("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 nK(e,t){if("macos"===e.platform)return void await nd(t);iY(e,"clipboard"),await i0(e);let r=await nF(e,["pbcopy",e.id],{allowFailure:!0,stdin:t});if(0!==r.exitCode)throw new w("COMMAND_FAILED","Failed to write iOS simulator clipboard",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}async function nX(e,t,r){iY(e,"push"),await i0(e);let a=await O.mkdtemp(i.join(T.tmpdir(),"agent-device-ios-push-")),n=i.join(a,"payload.apns");try{await O.writeFile(n,`${JSON.stringify(r)}
28
- `,"utf8"),await nF(e,["push",e.id,t,n])}finally{await O.rm(a,{recursive:!0,force:!0})}}async function nZ(e,t,r,a,i){if("macos"===e.platform){if("appearance"!==t.toLowerCase())throw new w("INVALID_ARGS",`Unsupported macOS setting: ${t}. macOS currently supports only settings appearance <light|dark|toggle>.`);await nc(r);return}iY(e,"settings"),await i0(e);let n=t.toLowerCase();switch(n){case"wifi":{let t=n0(r);await nF(e,["status_bar",e.id,"override","--wifiMode",t?"active":"failed"]);return}case"airplane":return void(n0(r)?await nF(e,["status_bar",e.id,"override","--dataNetwork","hide","--wifiMode","failed","--wifiBars","0","--cellularMode","failed","--cellularBars","0","--operatorName",""]):await nF(e,["status_bar",e.id,"clear"]));case"location":{let t=n0(r);if(!a)throw new w("INVALID_ARGS","location setting requires an active app in session");await nF(e,["privacy",e.id,t?"grant":"revoke","location",a]);return}case"faceid":case"touchid":{let t=n2[n],a=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 w("INVALID_ARGS",`Invalid ${t} state: ${e}. Use match|nonmatch|enroll|unenroll.`)}(r,n);await n6(e,a,{settingName:n,label:t.label,modalityAliases:t.modalityAliases});return}case"appearance":{let t=await n1(e,r);await nF(e,["ui",e.id,"appearance",t]);return}case"permission":{var o;if(!a)throw new w("INVALID_ARGS","permission setting requires an active app in session");let t="deny"===(o=iy(r))?"revoke":o,n=function(e,t){let r=ib(e);if("photos"!==r&&t?.trim())throw new w("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 w("INVALID_ARGS",`Invalid photos mode: ${t}. Use full|limited.`)}throw new w("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 n3(e,t,n,a);return}default:throw new w("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function nY(e,t="all"){return"macos"===e.platform?await np(t):"simulator"===e.kind?i7(await nQ(e),t):await iW(e,t)}async function nQ(e){let t=(await nF(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 c("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])=>({bundleId:e,name:t.CFBundleDisplayName??t.CFBundleName??e})):[]}function n0(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 w("INVALID_ARGS",`Invalid setting state: ${e}`)}async function n1(e,t){let r=iS(t);if("toggle"!==r)return r;let a=await nF(e,["ui",e.id,"appearance"],{allowFailure:!0});if(0!==a.exitCode)throw new w("COMMAND_FAILED","Failed to read current iOS appearance",{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});let i=function(e,t){let r=/\b(light|dark|unsupported|unknown)\b/i.exec(`${e}
29
- ${t}`);if(!r)return null;let a=r[1].toLowerCase();return"dark"===a?"dark":"light"===a?"light":null}(a.stdout,a.stderr);if(!i)throw new w("COMMAND_FAILED","Unable to determine current iOS appearance for toggle",{stdout:a.stdout,stderr:a.stderr});return"dark"===i?"light":"dark"}let n2={faceid:{label:"Face ID",modalityAliases:["face"]},touchid:{label:"Touch ID",modalityAliases:["finger","touch"]}};async function n3(e,t,r,a){let i=await n8(e);if(!i.has(r))throw new w("UNSUPPORTED_OPERATION",`iOS simctl privacy does not support service "${r}" on this runtime.`,{deviceId:e.id,appBundleId:a,hint:`Supported services: ${Array.from(i).sort().join(", ")}`});let n=["privacy",e.id,t,r,a],o="notifications"===r;if(!("reset"===t&&o))try{await nF(e,n);return}catch(t){if(!(o&&n4(t)))throw t;throw new w("UNSUPPORTED_OPERATION","iOS simulator does not support setting notifications permission via simctl privacy on this runtime.",{deviceId:e.id,appBundleId:a,hint:"Use reset notifications for reprompt behavior, or toggle notifications manually in Settings."})}try{await nF(e,n);return}catch(e){if(!n4(e))throw e}try{await nF(e,["privacy",e.id,"reset","all",a])}catch(t){throw new w("COMMAND_FAILED","iOS simulator blocked direct notifications reset. Fallback reset-all also failed.",{deviceId:e.id,appBundleId:a,hint:"Use reinstall to force a fresh notifications prompt, or reset simulator content and settings."},t instanceof Error?t:void 0)}}function n4(e){if(!(e instanceof w)||"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 n8(e){let r=eE(e.simulatorSetPath),a=`${process.env.PATH??""}::${r??""}`;if(n$&&t===a)return n$;let i=await nF(e,["privacy","help"],{allowFailure:!0}),n=function(e){let t=new Set,r=!1;for(let a of e.split("\n")){let e=a.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);i&&t.add(i[1])}return t}(`${i.stdout}
30
- ${i.stderr}`);if(0===n.size)throw new w("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 n$=n,t=a,n}async function n6(e,t,r){let a=function(e,t,r){let a=r.length>0?r:["face"];switch(t){case"match":return a.flatMap(t=>[["biometric",e,"match",t],["biometric","match",e,t]]);case"nonmatch":return a.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 a){let r=ex(e,t),a=await c("xcrun",r,{allowFailure:!0});if(0===a.exitCode)return;i.push({args:r,stderr:a.stderr,stdout:a.stdout,exitCode:a.exitCode})}let n=i.map(e=>({args:e.args.join(" "),exitCode:e.exitCode,stderr:e.stderr.slice(0,400)}));if(i.length>0&&i.every(e=>{var t,r;let a;return t=e.stdout,r=e.stderr,(a=`${t}
31
- ${r}`.toLowerCase()).includes("unrecognized subcommand")||a.includes("unknown subcommand")||a.includes("not supported")||a.includes("unavailable")||a.includes("biometric")&&a.includes("invalid")}))throw new w("UNSUPPORTED_OPERATION",`${r.label} simulation is not supported on this simulator runtime.`,{deviceId:e.id,action:t,setting:r.settingName,attempts:n});throw new w("COMMAND_FAILED",`Failed to simulate ${r.settingName}.`,{deviceId:e.id,action:t,setting:r.settingName,attempts:n})}async function n5(e,t){await i0(e),await iQ();let r=0,a=ee.fromTimeoutMs(iV);try{await et(async({deadline:r})=>{var a;if(r?.isExpired())throw new w("COMMAND_FAILED","App launch deadline exceeded",{timeoutMs:iV});let i=(a=["launch",e.id,t],ex(e,a)),n=await c("xcrun",i,{allowFailure:!0});if(0!==n.exitCode)throw new w("COMMAND_FAILED",`xcrun exited with code ${n.exitCode}`,{cmd:"xcrun",args:i,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})},{maxAttempts:10,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>!!iX(e)&&(r+=1)<3},{deadline:a})}catch(r){if(iX(r)){var i;let a=(i=await iZ(e,t)).installed?!1===i.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."}}(a)}}throw r}}async function n9(e,t,r){let a=["device","process","launch","--device",e.id,t];r?.payloadUrl&&a.push("--payload-url",r.payloadUrl),await iH(a,{action:"launch iOS app",deviceId:e.id})}function n7(e){return e?.clickButton??"primary"}function oe(e){return"primary"===e.button?null:"click"!==e.commandLabel?new w("INVALID_ARGS","--button is supported only for click"):"macos"!==e.platform?new w("UNSUPPORTED_OPERATION",`click --button ${e.button} is supported only on macOS`):"middle"===e.button?new w("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 w("INVALID_ARGS",`click --button ${e.button} does not support repeat or gesture modifier flags`):null}let ot=/^[A-Za-z0-9_.:-]{1,64}$/,or=[[0,0],[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];function oa(e,t,r,a){if(!Number.isFinite(e)||!Number.isInteger(e)||e<r||e>a)throw new w("INVALID_ARGS",`${t} must be an integer between ${r} and ${a}`);return e}async function oi(e,t,r){for(let a=0;a<e;a+=1)await r(a),a<e-1&&t>0&&await on(t)}async function on(e){await new Promise(t=>setTimeout(t,e))}function oo(e,t){let r,a=t?.subject??"Payload",i=e.trim();if(!i)throw new w("INVALID_ARGS",`${a} cannot be empty`);let n=t?.expandPath?t.expandPath(i,t.cwd):i;try{if(!R.statSync(n).isFile())throw new w("INVALID_ARGS",`${a} path is not a file: ${n}`);return{kind:"file",path:n}}catch(t){if(t instanceof w)throw t;let e=t.code;if("EACCES"===e||"EPERM"===e)throw new w("INVALID_ARGS",`${a} file is not readable: ${n}`);if(e&&"ENOENT"!==e)throw new w("COMMAND_FAILED",`Unable to read ${a} file: ${n}`,{cause:String(t)})}if((r=i.trim()).startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))return{kind:"inline",text:i};throw new w("INVALID_ARGS",`${a} file not found: ${n}`)}async function os(e){let t=oo(e,{subject:"Push payload"}),r="inline"===t.kind?t.text:await ol(t.path);try{let e=JSON.parse(r);if(!e||"object"!=typeof e||Array.isArray(e))throw new w("INVALID_ARGS","push payload must be a JSON object");return e}catch(t){if(t instanceof w)throw t;throw new w("INVALID_ARGS",`Invalid push payload JSON: ${e}`)}}async function ol(e){try{return await O.readFile(e,"utf8")}catch(r){let t=r.code;if("ENOENT"===t)throw new w("INVALID_ARGS",`Push payload file not found: ${e}`);if("EISDIR"===t)throw new w("INVALID_ARGS",`Push payload path is not a file: ${e}`);if("EACCES"===t||"EPERM"===t)throw new w("INVALID_ARGS",`Push payload file is not readable: ${e}`);throw new w("COMMAND_FAILED",`Unable to read push payload file: ${e}`,{cause:String(r)})}}let od=eb(process.env.AGENT_DEVICE_IOS_DEVICECTL_LIST_TIMEOUT_MS,8e3,500),ou=/^(iphone|ipad|ipod|appletv)/i,oc=/^appletv/i,op=["apple tv","appletv","tvos"];function of(e){return(e??"").trim().toLowerCase()}function om(e){return of(e.hardwareProperties?.platform)}function oh(e){return e.includes("tvos")}function ow(e){return oh(of(e))?"tv":"mobile"}function og(e){let t=of(e);return t.includes("ios")||t.includes("tvos")}function oI(e){let t=of(e);return op.some(e=>t.includes(e))}function oA(e){return ou.test(e.trim())}function ov(e){return oc.test(e.trim())}function oy(e){return[e.name??"",e.deviceProperties?.name??"",e.deviceProperties?.deviceType??""]}function ob(e){return e.hardwareProperties?.productType??e.deviceProperties?.productType??""}function oS(e){return oh(om(e))||ov(ob(e))||oy(e).some(oI)?"tv":"mobile"}function oN(e){let t=om(e);return!!(t.includes("ios")||t.includes("tvos")||oA(ob(e)))||oy(e).some(oI)}async function o_(e={}){let t,r,a=eE(e.simulatorSetPath),i=e.target;try{t=await c("xcrun",eO(["list","devices","-j"],{simulatorSetPath:a}))}catch{return null}try{r=JSON.parse(t.stdout)}catch{return null}let n=null,o=null,s=null;for(let[e,t]of Object.entries(r.devices)){if(!og(e))continue;let r=ow(e);if(!i||r===i)for(let e of t){if(!e.isAvailable)continue;let t={platform:"ios",id:e.udid,name:e.name,kind:"simulator",target:r,booted:"Booted"===e.state,...a?{simulatorSetPath:a}:{}};t.booted&&(n=n??t),"mobile"===r&&(o=o??t),s=s??t}}return n??o??s}async function oD(e={}){if("darwin"!==process.platform)throw new w("UNSUPPORTED_PLATFORM","Apple tools are only available on macOS");if(!await I("xcrun"))throw new w("TOOL_MISSING","xcrun not found in PATH");let t=[],r=eE(e.simulatorSetPath),a=await c("xcrun",eO(["list","devices","-j"],{simulatorSetPath:r}));try{let e=JSON.parse(a.stdout);for(let[a,i]of Object.entries(e.devices))if(og(a))for(let e of i)e.isAvailable&&t.push({platform:"ios",id:e.udid,name:e.name,kind:"simulator",target:ow(a),booted:"Booted"===e.state,...r?{simulatorSetPath:r}:{}})}catch(e){throw new w("COMMAND_FAILED","Failed to parse simctl devices JSON",void 0,e)}if(t.push({platform:"macos",id:"host-macos-local",name:T.hostname(),kind:"device",target:"desktop",booted:!0}),r)return t;let n=null;try{n=i.join(T.tmpdir(),`agent-device-devicectl-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);let e=await c("xcrun",["devicectl","list","devices","--json-output",n],{allowFailure:!0,timeoutMs:od});if(0!==e.exitCode)return t;let r=await O.readFile(n,"utf8"),a=JSON.parse(r);for(let e of a.result?.devices??[])if(oN(e)){let r=e.hardwareProperties?.udid??e.identifier??"",a=e.name??e.deviceProperties?.name??r;if(!r)continue;t.push({platform:"ios",id:r,name:a,kind:"device",target:oS(e),booted:!0})}}catch{}finally{n&&await O.rm(n,{force:!0}).catch(()=>{})}return t}async function oE(e,t,r,a){let i,n=!!(t.udid||t.serial||t.deviceName);try{i=await a.resolveDevice(e,t,r)}catch(e){if(n||!(e instanceof w)||"DEVICE_NOT_FOUND"!==e.code)throw e}if(!n&&(!t.platform||"apple"===t.platform||"ios"===t.platform)&&"desktop"!==t.target&&(!i||"device"===i.kind)){let e=await a.findBootableSimulator({simulatorSetPath:r.simulatorSetPath,target:t.target});if(e)return e}if(i)return i;throw new w("DEVICE_NOT_FOUND","No devices found",{selector:t})}async function ok(e){let t=e.platform,r=eZ({simulatorSetPath:eE(e.iosSimulatorDeviceSet),platform:t,target:e.target}),a=eL(e.androidDeviceAllowlist);return await E("resolve_target_device",async()=>{let i={platform:t,target:e.target,deviceName:e.device,udid:e.udid,serial:e.serial};if(i.target&&!i.platform)throw new w("INVALID_ARGS","Device target selector requires --platform. Use --platform ios|macos|android|apple with --target mobile|tv|desktop.");if("android"===i.platform){await r_();let e=await rH({serialAllowlist:a});return await eY(e,i)}if(i.platform){let e=await oD({simulatorSetPath:r});return await oE(e,i,{simulatorSetPath:r},{resolveDevice:eY,findBootableSimulator:o_})}let n=[];try{n.push(...await rH({serialAllowlist:a}))}catch{}try{n.push(...await oD({simulatorSetPath:r}))}catch{}return await eY(n,i,{simulatorSetPath:r})},{platform:t,target:e.target})}async function oL(e,t,r,a,n){let o=function(e,t){switch(e.platform){case"android":return{open:(t,r)=>aO(e,t,r?.activity),openDevice:()=>aR(e),close:t=>aP(e,t),tap:(t,r)=>a8(e,t,r),doubleTap:async(t,r)=>{await a8(e,t,r),await a8(e,t,r)},swipe:(t,r,a,i,n)=>a6(e,t,r,a,i,n),longPress:(t,r,a)=>ie(e,t,r,a),focus:(t,r)=>ir(e,t,r),type:t=>it(e,t),fill:(t,r,a)=>ia(e,t,r,a),scroll:(t,r)=>ii(e,t,r),scrollIntoView:t=>io(e,t),screenshot:(t,r)=>iR(e,t),back:()=>a5(e),home:()=>a9(e),appSwitcher:()=>a7(e),readClipboard:()=>ig(e),writeClipboard:t=>iI(e,t),setSetting:(t,r,a,i)=>iN(e,t,r,a,i)};case"ios":case"macos":{var r,a;let i,n,{overrides:o,runnerOpts:s}=(r=e,i={verbose:(a=t).verbose,logPath:a.logPath,traceLogPath:a.traceLogPath,requestId:a.requestId},n=()=>{if(ep(a.requestId))throw em()},{runnerOpts:i,overrides:{tap:async(e,t)=>{await tA(r,{command:"tap",x:e,y:t,appBundleId:a.appBundleId},i)},doubleTap:async(e,t)=>{await tA(r,{command:"tapSeries",x:e,y:t,count:1,intervalMs:0,doubleTap:!0,appBundleId:a.appBundleId},i)},swipe:async(e,t,n,o,s)=>{await tA(r,{command:"drag",x:e,y:t,x2:n,y2:o,durationMs:s,appBundleId:a.appBundleId},i)},longPress:async(e,t,n)=>{await tA(r,{command:"longPress",x:e,y:t,durationMs:n,appBundleId:a.appBundleId},i)},focus:async(e,t)=>{await tA(r,{command:"tap",x:e,y:t,appBundleId:a.appBundleId},i)},type:async e=>{await tA(r,{command:"type",text:e,appBundleId:a.appBundleId},i)},fill:async(e,t,n)=>{await tA(r,{command:"tap",x:e,y:t,appBundleId:a.appBundleId},i),await tA(r,{command:"type",text:n,clearFirst:!0,appBundleId:a.appBundleId},i)},scroll:async(e,t)=>{if(!["up","down","left","right"].includes(e))throw new w("INVALID_ARGS",`Unknown direction: ${e}`);let n=function(e){switch(e){case"up":return"down";case"down":return"up";case"left":return"right";case"right":return"left"}}(e);await tA(r,{command:"swipe",direction:n,appBundleId:a.appBundleId},i)},scrollIntoView:async e=>{let t=await tA(r,{command:"findText",text:e,appBundleId:a.appBundleId},i);if(t?.found)return{attempts:1};for(let t=0;t<12;t+=1){for(let e=0;e<4;e+=1)n(),await tA(r,{command:"swipe",direction:"up",appBundleId:a.appBundleId},i),await new Promise(e=>setTimeout(e,80));n();let o=await tA(r,{command:"findText",text:e,appBundleId:a.appBundleId},i);if(o?.found)return{attempts:t+2}}throw new w("COMMAND_FAILED",`scrollintoview could not find text: ${e}`)}}});return{open:(t,r)=>nG(e,t,{appBundleId:r?.appBundleId,url:r?.url}),openDevice:()=>nB(e),close:t=>nj(e,t),screenshot:(t,r)=>n_(e,t,r),back:async()=>{await tA(e,{command:"back",appBundleId:t.appBundleId},s)},home:async()=>{await tA(e,{command:"home",appBundleId:t.appBundleId},s)},appSwitcher:async()=>{await tA(e,{command:"appSwitcher",appBundleId:t.appBundleId},s)},readClipboard:()=>nJ(e),writeClipboard:t=>nK(e,t),setSetting:(t,r,a,i)=>nZ(e,t,r,a,i),...o}}default:throw new w("UNSUPPORTED_PLATFORM",`Unsupported platform: ${e.platform}`)}}(e,{requestId:n?.requestId,appBundleId:n?.appBundleId,verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath});return L({level:"debug",phase:"platform_command_prepare",data:{command:t,platform:e.platform,kind:e.kind}}),await E("platform_command",async()=>{switch(t){case"open":{let t=r[0],a=r[1];if(r.length>2)throw new w("INVALID_ARGS","open accepts at most two arguments: <app|url> [url]");if(!t)return await o.openDevice(),{app:null};if(void 0!==a){if("android"===e.platform)throw new w("INVALID_ARGS","open <app> <url> is supported only on Apple platforms");if(rk(t))throw new w("INVALID_ARGS","open <app> <url> requires an app target as the first argument");if(!rk(a))throw new w("INVALID_ARGS","open <app> <url> requires a valid URL target");return await o.open(t,{activity:n?.activity,appBundleId:n?.appBundleId,url:a}),{app:t,url:a}}return await o.open(t,{activity:n?.activity,appBundleId:n?.appBundleId}),{app:t}}case"close":{let e=r[0];if(!e)return{closed:"session"};return await o.close(e),{app:e}}case"press":{let[t,a]=r.map(Number);if(Number.isNaN(t)||Number.isNaN(a))throw new w("INVALID_ARGS","press requires x y");let i=n7(n);if("primary"!==i){let r=oe({commandLabel:"click",platform:e.platform,button:i,count:n?.count,intervalMs:n?.intervalMs,holdMs:n?.holdMs,jitterPx:n?.jitterPx,doubleTap:n?.doubleTap});if(r)throw r;return await tA(e,{command:"mouseClick",x:t,y:a,button:i,appBundleId:n?.appBundleId},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId}),{x:t,y:a,button:i}}let s=oa(n?.count??1,"count",1,200),l=oa(n?.intervalMs??0,"interval-ms",0,1e4),d=oa(n?.holdMs??0,"hold-ms",0,1e4),u=oa(n?.jitterPx??0,"jitter-px",0,100),c=n?.doubleTap===!0;if(c&&d>0)throw new w("INVALID_ARGS","double-tap cannot be combined with hold-ms");if(c&&u>0)throw new w("INVALID_ARGS","double-tap cannot be combined with jitter-px");if(("ios"===e.platform||"macos"===e.platform)&&s>1&&0===d&&0===u)return await tA(e,{command:"tapSeries",x:t,y:a,count:s,intervalMs:l,doubleTap:c,appBundleId:n?.appBundleId},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId}),{x:t,y:a,count:s,intervalMs:l,holdMs:d,jitterPx:u,doubleTap:c,timingMode:"runner-series"};return await oi(s,l,async e=>{let[r,i]=function(e,t){if(t<=0)return[0,0];let[r,a]=or[e%or.length];return[r*t,a*t]}(e,u),n=t+r,s=a+i;c?await o.doubleTap(n,s):d>0?await o.longPress(n,s,d):await o.tap(n,s)}),{x:t,y:a,count:s,intervalMs:l,holdMs:d,jitterPx:u,doubleTap:c}}case"swipe":{let t=Number(r[0]),a=Number(r[1]),i=Number(r[2]),s=Number(r[3]);if([t,a,i,s].some(Number.isNaN))throw new w("INVALID_ARGS","swipe requires x1 y1 x2 y2 [durationMs]");let l=oa(r[4]?Number(r[4]):250,"durationMs",16,1e4),d="ios"===e.platform?Math.min(60,Math.max(16,Math.round(l))):l,u=oa(n?.count??1,"count",1,200),c=oa(n?.pauseMs??0,"pause-ms",0,1e4),p=n?.pattern??"one-way";if("one-way"!==p&&"ping-pong"!==p)throw new w("INVALID_ARGS",`Invalid pattern: ${p}`);if(("ios"===e.platform||"macos"===e.platform)&&u>1)return await tA(e,{command:"dragSeries",x:t,y:a,x2:i,y2:s,durationMs:d,count:u,pauseMs:c,pattern:p,appBundleId:n?.appBundleId},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId}),{x1:t,y1:a,x2:i,y2:s,durationMs:l,effectiveDurationMs:d,timingMode:"runner-series",count:u,pauseMs:c,pattern:p};return await oi(u,c,async e=>{"ping-pong"===p&&e%2==1?await o.swipe(i,s,t,a,d):await o.swipe(t,a,i,s,d)}),{x1:t,y1:a,x2:i,y2:s,durationMs:l,effectiveDurationMs:d,timingMode:"ios"===e.platform?"safe-normalized":"direct",count:u,pauseMs:c,pattern:p}}case"longpress":{let e=Number(r[0]),t=Number(r[1]),a=r[2]?Number(r[2]):void 0;if(Number.isNaN(e)||Number.isNaN(t))throw new w("INVALID_ARGS","longpress requires x y [durationMs]");return await o.longPress(e,t,a),{x:e,y:t,durationMs:a}}case"focus":{let[e,t]=r.map(Number);if(Number.isNaN(e)||Number.isNaN(t))throw new w("INVALID_ARGS","focus requires x y");return await o.focus(e,t),{x:e,y:t}}case"type":{let e=r.join(" ");if(!e)throw new w("INVALID_ARGS","type requires text");return await o.type(e),{text:e}}case"fill":{let e=Number(r[0]),t=Number(r[1]),a=r.slice(2).join(" ");if(Number.isNaN(e)||Number.isNaN(t)||!a)throw new w("INVALID_ARGS","fill requires x y text");return await o.fill(e,t,a),{x:e,y:t,text:a}}case"scroll":{let e=r[0],t=r[1]?Number(r[1]):void 0;if(!e)throw new w("INVALID_ARGS","scroll requires direction");return await o.scroll(e,t),{direction:e,amount:t}}case"scrollintoview":{let e=r.join(" ").trim();if(!e)throw new w("INVALID_ARGS","scrollintoview requires text");let t=await o.scrollIntoView(e);if(t?.attempts)return{text:e,attempts:t.attempts};return{text:e}}case"pinch":{if("android"===e.platform)throw new w("UNSUPPORTED_OPERATION","Android pinch is not supported in current adb backend; requires instrumentation-based backend.");let t=Number(r[0]),a=r[1]?Number(r[1]):void 0,i=r[2]?Number(r[2]):void 0;if(Number.isNaN(t)||t<=0)throw new w("INVALID_ARGS","pinch requires scale > 0");return await tA(e,{command:"pinch",scale:t,x:a,y:i,appBundleId:n?.appBundleId},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId}),{scale:t,x:a,y:i}}case"trigger-app-event":{let{eventName:t,payload:a}=function(e){let t=e[0]?.trim(),r=e[1]?.trim();if(!t)throw new w("INVALID_ARGS","trigger-app-event requires <event> [payloadJson]");if(!ot.test(t))throw new w("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 w("INVALID_ARGS","trigger-app-event accepts at most two arguments: <event> [payloadJson]");let a=function(e,t){if(e)try{let r=JSON.parse(e);if(!r||"object"!=typeof r||Array.isArray(r))throw new w("INVALID_ARGS",`trigger-app-event payload for "${t}" must be a JSON object`);let a=JSON.stringify(r);if(Buffer.byteLength(a,"utf8")>8192)throw new w("INVALID_ARGS",`trigger-app-event payload for "${t}" exceeds 8192 bytes`);return r}catch(t){if(t instanceof w)throw t;throw new w("INVALID_ARGS",`Invalid trigger-app-event payload JSON: ${e}`)}}(r,t);return{eventName:t,payload:a}}(r),i=function(e,t,r){var a;let i,n=(i=("ios"===(a=e)?process.env.AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE:"macos"===a?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(!n)throw new w("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=n.replaceAll("{event}",encodeURIComponent(t)).replaceAll("{payload}",encodeURIComponent(o)).replaceAll("{platform}",encodeURIComponent(e));if(s.length>4096)throw new w("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,t,a);return await o.open(i,{appBundleId:n?.appBundleId}),{event:t,eventUrl:i,transport:"deep-link"}}case"screenshot":{let e=r[0]??a??`./screenshot-${Date.now()}.png`;return await O.mkdir(i.dirname(e),{recursive:!0}),await o.screenshot(e,n?.appBundleId),{path:e}}case"back":return await o.back(),{action:"back"};case"home":return await o.home(),{action:"home"};case"app-switcher":return await o.appSwitcher(),{action:"app-switcher"};case"clipboard":{let e=(r[0]??"").toLowerCase();if("read"!==e&&"write"!==e)throw new w("INVALID_ARGS","clipboard requires a subcommand: read or write");if("read"===e){if(1!==r.length)throw new w("INVALID_ARGS","clipboard read does not accept additional arguments");return{action:e,text:await o.readClipboard()}}if(r.length<2)throw new w("INVALID_ARGS",'clipboard write requires text (use "" to clear clipboard)');let t=r.slice(1).join(" ");return await o.writeClipboard(t),{action:e,textLength:Array.from(t).length}}case"keyboard":{if("android"!==e.platform)throw new w("UNSUPPORTED_OPERATION","keyboard is currently supported only on Android");let t=(r[0]??"status").toLowerCase();if("status"!==t&&"get"!==t&&"dismiss"!==t)throw new w("INVALID_ARGS","keyboard requires a subcommand: status, get, or dismiss");if(r.length>1)throw new w("INVALID_ARGS","keyboard accepts at most one subcommand argument");if("dismiss"===t){let t=await iw(e);return{platform:"android",action:"dismiss",attempts:t.attempts,wasVisible:t.wasVisible,dismissed:t.dismissed,visible:t.visible,inputType:t.inputType,type:t.type}}let a=await ih(e);return{platform:"android",action:"status",visible:a.visible,inputType:a.inputType,type:a.type}}case"settings":{let[t,a,i,s,l]=r,d="permission"===t?{permissionTarget:i,permissionMode:s}:void 0;return L({level:"debug",phase:"settings_apply",data:{setting:t,state:a,target:i,mode:s,platform:e.platform}}),await o.setSetting(t,a,l??n?.appBundleId,d),{setting:t,state:a}}case"push":{let t=r[0]?.trim(),a=r[1]?.trim();if(!t||!a)throw new w("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>");let i=await os(a);if("ios"===e.platform)return await nX(e,t,i),{platform:"ios",bundleId:t};let n=await ix(e,t,i);return{platform:"android",package:t,action:n.action,extrasCount:n.extrasCount}}case"snapshot":{if("android"!==e.platform){let t=await E("snapshot_capture",async()=>await tA(e,{command:"snapshot",appBundleId:n?.appBundleId,interactiveOnly:n?.snapshotInteractiveOnly,compact:n?.snapshotCompact,depth:n?.snapshotDepth,scope:n?.snapshotScope,raw:n?.snapshotRaw},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId}),{backend:"xctest"}),r=t.nodes??[];if(0===r.length&&"simulator"===e.kind)throw new w("COMMAND_FAILED","XCTest snapshot returned 0 nodes on iOS simulator.");return{nodes:r,truncated:t.truncated??!1,backend:"xctest"}}let t=await E("snapshot_capture",async()=>await a0(e,{interactiveOnly:n?.snapshotInteractiveOnly,compact:n?.snapshotCompact,depth:n?.snapshotDepth,scope:n?.snapshotScope,raw:n?.snapshotRaw}),{backend:"android"});return{nodes:t.nodes??[],truncated:t.truncated??!1,backend:"android"}}default:throw new w("INVALID_ARGS",`Unknown command: ${t}`)}},{command:t,platform:e.platform})}let oO=e=>"macos"!==e.platform,ox={alert:{apple:{simulator:!0},android:{}},pinch:{apple:{simulator:!0},android:{}},"app-switcher":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:oO},apps:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},back:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},boot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:oO},click:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},clipboard:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind},keyboard:{apple:{},android:{emulator:!0,device:!0,unknown:!0}},close:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},fill:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},diff:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},find:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},focus:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},get:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},is:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},home:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:oO},logs:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:oO},network:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:oO},longpress:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},open:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},perf:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},install:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:oO},"install-from-source":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:oO},reinstall:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:oO},press:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},push:{apple:{simulator:!0},android:{emulator:!0,device:!0,unknown:!0},supports:oO},record:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},screenshot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},scroll:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},scrollintoview:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},swipe:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},settings:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind},snapshot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},"trigger-app-event":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},type:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},wait:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}}};function oM(e,t){let r=ox[e];if(!r)return!0;let a=eK(t.platform)?r.apple:r.android;return!!a&&(!r.supports||!!r.supports(t))&&!0===a[t.kind??"unknown"]}function oC(e,t,r,a,i){return{requestId:i??_().requestId,appBundleId:r,activity:t?.activity,verbose:t?.verbose,logPath:e,traceLogPath:a,snapshotInteractiveOnly:t?.snapshotInteractiveOnly,snapshotCompact:t?.snapshotCompact,snapshotDepth:t?.snapshotDepth,snapshotScope:t?.snapshotScope,snapshotRaw:t?.snapshotRaw,count:t?.count,intervalMs:t?.intervalMs,holdMs:t?.holdMs,jitterPx:t?.jitterPx,doubleTap:t?.doubleTap,clickButton:n7(t),pauseMs:t?.pauseMs,pattern:t?.pattern}}let oR=eb(process.env.AGENT_DEVICE_IOS_DEVICE_READY_TIMEOUT_MS,15e3,1e3);async function oP(e){if("ios"===e.platform){if("simulator"===e.kind){let{ensureBootedSimulator:t}=await Promise.resolve().then(()=>({ensureBootedSimulator:i0}));await t(e);return}if("device"===e.kind)return void await oT(e.id)}if("android"===e.platform){let{waitForAndroidBoot:t}=await Promise.resolve().then(()=>({waitForAndroidBoot:r1}));await t(e.id)}}async function oT(e){let t=i.join(T.tmpdir(),`agent-device-ready-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),r=Math.max(1,Math.ceil(oR/1e3));try{let a=await c("xcrun",["devicectl","device","info","details","--device",e,"--json-output",t,"--timeout",String(r)],{allowFailure:!0,timeoutMs:oR+3e3}),i=String(a.stdout??""),n=String(a.stderr??""),o=await o$(t);if(0===a.exitCode){if(!o.parsed)throw new w("COMMAND_FAILED","iOS device readiness probe failed",{kind:"probe_inconclusive",deviceId:e,stdout:i,stderr:n,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 w("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 w("COMMAND_FAILED","iOS device is not ready for automation",{kind:"not_ready",deviceId:e,stdout:i,stderr:n,exitCode:a.exitCode,tunnelState:o?.tunnelState,hint:oF(i,n)})}catch(t){if(t instanceof w&&"COMMAND_FAILED"===t.code){if("not_ready"===("string"==typeof t.details?.kind?t.details.kind:""))throw t;let r=t.details??{},a=String(r.stdout??""),i=String(r.stderr??""),n=Number(r.timeoutMs??oR),o=`CoreDevice did not respond within ${n}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;throw new w("COMMAND_FAILED","iOS device readiness probe failed",{deviceId:e,cause:t.message,timeoutMs:n,stdout:a,stderr:i,hint:a||i?oF(a,i):o},t)}throw new w("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 O.rm(t,{force:!0}).catch(()=>{})}}async function o$(e){try{let t=await O.readFile(e,"utf8"),r=JSON.parse(t),a=function(e){let t=e?.result;if(!t||"object"!=typeof t)return{};let r=t.connectionProperties?.tunnelState,a=t.device?.connectionProperties?.tunnelState,i="string"==typeof r?r:"string"==typeof a?a:void 0;return i?{tunnelState:i}:{}}(r);return{parsed:!0,tunnelState:a.tunnelState}}catch{return{parsed:!1}}}function oF(e,t){let r=iK(e,t);return r||(`${e}
32
- ${t}`.toLowerCase().includes("timed out waiting for all destinations")?"Xcode destination did not become available in time. Keep device unlocked and retry.":iJ)}function oU(e){return e.map((e,t)=>({...e,ref:`e${t+1}`}))}function oV(e){let t=e.trim();return t.startsWith("@")?t.slice(1)||null:t.startsWith("e")?t:null}function oG(e,t){return e.find(e=>e.ref===t)??null}function oB(e){return{x:Math.round(e.x+e.width/2),y:Math.round(e.y+e.height/2)}}function oj(e,t){let r=t.toLowerCase();return e.find(e=>{let t=(e.label??"").toLowerCase(),a=(e.value??"").toLowerCase(),i=(e.identifier??"").toLowerCase();return t.includes(r)||a.includes(r)||i.includes(r)})??null}function oq(e,t){let r=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);return r&&oH(r)?r:function(e,t){if(!e.rect)return;let r=e.rect.y+e.rect.height/2,a=null;for(let e of t){if(!e.rect)continue;let t=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);if(!t||!oH(t))continue;let i=Math.abs(e.rect.y+e.rect.height/2-r);(!a||i<a.distance)&&(a={label:t,distance:i})}return a?.label}(e,t)??(r&&oH(r)?r:void 0)}function oH(e){let t=e.trim();return!(!t||/^(true|false)$/i.test(t)||/^\d+$/.test(t))}function oW(e){let t=[],r=[];for(let a of e){let e=a.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let i=oz(a.type??""),n=[a.label,a.value,a.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0),o=!!n&&oH(n);if(("group"===i||"ioscontentgroup"===i)&&!o){t.push(e);continue}let s=Math.max(0,e-t.length);r.push({...a,depth:s})}return r}function oz(e){let t=e.trim().replace(/XCUIElementType/gi,"").toLowerCase(),r=Math.max(t.lastIndexOf("."),t.lastIndexOf("/"));return -1!==r&&(t=t.slice(r+1)),t}function oJ(e,t){let r=oz(e);return!r||("android"===t?r.includes("edittext")||r.includes("autocompletetextview"):r.includes("textfield")||r.includes("securetextfield")||r.includes("searchfield")||r.includes("textview")||r.includes("textarea")||"search"===r)}function oK(e){return[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0)[0]??""}let oX=new Set(["id","role","text","label","value"]),oZ=new Set(["visible","hidden","editable","selected","enabled","hittable"]),oY=new Set([...oX,...oZ]);function oQ(e){let t=e.trim();if(!t)throw new w("INVALID_ARGS","Selector expression cannot be empty");let r=function(e){let t=[],r="",a=null;for(let i=0;i<e.length;i+=1){let n=e[i];if(('"'===n||"'"===n)&&!o8(e,i)){a?a===n&&(a=null):a=n,r+=n;continue}if(!a&&"|"===n&&"|"===e[i+1]){let a=r.trim();if(!a)throw new w("INVALID_ARGS",`Invalid selector fallback expression: ${e}`);t.push(a),r="",i+=1;continue}r+=n}let i=r.trim();if(!i)throw new w("INVALID_ARGS",`Invalid selector fallback expression: ${e}`);return t.push(i),t}(t);if(0===r.length)throw new w("INVALID_ARGS","Selector expression cannot be empty");return{raw:t,selectors:r.map(e=>(function(e){let t=e.trim();if(!t)throw new w("INVALID_ARGS","Selector segment cannot be empty");let r=function(e){let t=[],r="",a=null;for(let i=0;i<e.length;i+=1){let n=e[i];if(('"'===n||"'"===n)&&!o8(e,i)){a?a===n&&(a=null):a=n,r+=n;continue}if(!a&&/\s/.test(n)){r.trim().length>0&&t.push(r.trim()),r="";continue}r+=n}if(a)throw new w("INVALID_ARGS",`Unclosed quote in selector: ${e}`);return r.trim().length>0&&t.push(r.trim()),t}(t);if(0===r.length)throw new w("INVALID_ARGS",`Invalid selector segment: ${e}`);return{raw:t,terms:r.map(o3)}})(e))}}function o0(e){try{return oQ(e)}catch{return null}}function o1(e,t={}){if(0===e.length)return null;let r=t.preferTrailingValue??!1,a=0,i=[];for(;a<e.length&&function(e){let t=e.trim();if(!t)return!1;if("||"===t)return!0;let r=t.indexOf("=");if(-1!==r){let e=t.slice(0,r).trim().toLowerCase();return oY.has(e)}return oY.has(t.toLowerCase())}(e[a]);){a+=1;let t=e.slice(0,a).join(" ").trim();t&&o0(t)&&i.push(a)}if(0===i.length)return null;let n=i[i.length-1];if(r){for(let t=i.length-1;t>=0;t-=1)if(i[t]<e.length){n=i[t];break}}let o=e.slice(0,n).join(" ").trim();return o?{selectorExpression:o,rest:e.slice(n)}:null}function o2(e){let t=e[0]??"",r=o1(e.slice(1),{preferTrailingValue:"text"===t});return{predicate:t,split:r}}function o3(e){let t=e.trim();if(!t)throw new w("INVALID_ARGS","Empty selector term");let r=t.indexOf("=");if(-1===r){let r=t.toLowerCase();if(!oZ.has(r))throw new w("INVALID_ARGS",`Invalid selector term "${e}", expected key=value`);return{key:r,value:!0}}let a=t.slice(0,r).trim().toLowerCase(),i=t.slice(r+1).trim();if(!oY.has(a))throw new w("INVALID_ARGS",`Unknown selector key: ${a}`);if(!i)throw new w("INVALID_ARGS",`Missing selector value for key: ${a}`);if(oZ.has(a)){let e,t="true"===(e=o4(i).toLowerCase())||"false"!==e&&null;if(null===t)throw new w("INVALID_ARGS",`Invalid boolean value for ${a}: ${i}`);return{key:a,value:t}}return{key:a,value:o4(i)}}function o4(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/\\(["'])/g,"$1"):t}function o8(e,t){let r=0;for(let a=t-1;a>=0&&"\\"===e[a];a-=1)r+=1;return r%2==1}function o6(e,t,r){return t.terms.every(t=>(function(e,t,r){switch(t.key){case"id":return o7(e.identifier,String(t.value));case"role":var a,i;return a=e.type,i=String(t.value),function(e){return oz(e)}(a??"")===function(e){return oz(e)}(i);case"label":return o7(e.label,String(t.value));case"value":return o7(e.value,String(t.value));case"text":{let r=se(String(t.value));return se(oK(e))===r}case"visible":return o5(e)===!!t.value;case"hidden":return!o5(e)==!!t.value;case"editable":return o9(e,r)===!!t.value;case"selected":return!0===e.selected==!!t.value;case"enabled":return!1!==e.enabled==!!t.value;case"hittable":return!0===e.hittable==!!t.value;default:return!1}})(e,t,r))}function o5(e){return!0===e.hittable||!!e.rect&&e.rect.width>0&&e.rect.height>0}function o9(e,t){return oJ(e.type??"",t)&&!1!==e.enabled}function o7(e,t){return se(e??"")===se(t)}function se(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function st(e,t,r){let a=r.requireRect??!1,i=r.requireUnique??!0,n=r.disambiguateAmbiguous??!1,o=[];for(let s=0;s<t.selectors.length;s+=1){let l=t.selectors[s],d=function(e,t,r){let a=0,i=null,n=null,o=!1;for(let s of e){if(r.requireRect&&!s.rect||!o6(s,t,r.platform))continue;if(a+=1,i||(i=s),!n){n=s;continue}let e=function(e,t){let r=e.depth??0,a=t.depth??0;if(r!==a)return r>a?1:-1;let i=si(e),n=si(t);return i!==n?i<n?1:-1:0}(s,n);if(e>0){n=s,o=!1;continue}0===e&&(o=!0)}return{count:a,firstNode:i,disambiguated:o?null:n}}(e,l,{platform:r.platform,requireRect:a});if(o.push({selector:l.raw,matches:d.count}),0!==d.count&&d.firstNode){if(i&&1!==d.count){if(!n)continue;let e=d.disambiguated;if(!e)continue;return{node:e,selector:l,selectorIndex:s,matches:d.count,diagnostics:o}}return{node:d.firstNode,selector:l,selectorIndex:s,matches:d.count,diagnostics:o}}}return null}function sr(e,t,r){let a=r.requireRect??!1,i=[];for(let n=0;n<t.selectors.length;n+=1){let o=t.selectors[n],s=function(e,t,r){let a=0;for(let i of e)(!r.requireRect||i.rect)&&o6(i,t,r.platform)&&(a+=1);return a}(e,o,{platform:r.platform,requireRect:a});if(i.push({selector:o.raw,matches:s}),s>0)return{selectorIndex:n,selector:o,matches:s,diagnostics:i}}return null}function sa(e,t,r){let a=r.unique??!0;if(0===t.length)return`Selector did not match: ${e.raw}`;let i=t.map(e=>`${e.selector} -> ${e.matches}`).join(", ");return a?`Selector did not resolve uniquely (${i})`:`Selector did not match (${i})`}function si(e){return e.rect?e.rect.width*e.rect.height:1/0}function sn(e,t,r={}){let a=[],i=oz(e.type??""),n=ss(e.identifier),o=ss(e.label),s=ss(e.value),l=ss(oK(e)),d="fill"===r.action;n&&a.push(`id=${so(n)}`),i&&o&&a.push(d?`role=${so(i)} label=${so(o)} editable=true`:`role=${so(i)} label=${so(o)}`),o&&a.push(d?`label=${so(o)} editable=true`:`label=${so(o)}`),s&&a.push(d?`value=${so(s)} editable=true`:`value=${so(s)}`),l&&l!==o&&l!==s&&a.push(d?`text=${so(l)} editable=true`:`text=${so(l)}`),i&&d&&!a.some(e=>e.includes("editable=true"))&&a.push(`role=${so(i)} editable=true`);let u=tb(a);return 0===u.length&&i&&u.push(d?`role=${so(i)} editable=true`:`role=${so(i)}`),0===u.length&&o5(e)&&u.push("visible=true"),u}function so(e){return JSON.stringify(e)}function ss(e){if(!e)return null;let t=e.trim();return t||null}let sl=RegExp("\\b(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b","i"),sd=/https?:\/\/[^\s"'<>\])]+/i,su=[/\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 sc(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 sp(e,t,r){if(t){for(let e of r)if(void 0!==t[e])return sf(t[e])}for(let t of r){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=RegExp(`\\b${r}["'=: ]+(.+)$`,"i").exec(e);if(a?.[1])return a[1].trim()}}function sf(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}}function sm(e,t){return e.length<=t?e:`${e.slice(0,t)}...<truncated>`}function sh(e,t,r,a){return void 0!==e&&Number.isInteger(e)?Math.max(r,Math.min(a,e)):t}let sw="shared_prefs/ReactNativeDevPrefs.xml",sg="debug_http_host",sI="dev_server_https",sA="RCT_jsLocation",sv="RCT_packager_scheme",sy="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.",sb='<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n</map>\n';function sS(e){return void 0!==sN(e)}function sN(e){if(!e)return;let t=sT(e.metroHost),r=sF(e.metroPort),a="http",i=sT(e.bundleUrl);if(i){var n;let e;try{e=new g(i)}catch(e){throw new w("INVALID_ARGS",`Invalid runtime bundle URL: ${i}`,{},e)}("http:"===e.protocol||"https:"===e.protocol)&&(t??=sT(e.hostname),r??=sF(e.port.length>0?Number(e.port):"https:"===(n=e.protocol)?443:"http:"===n?80:void 0),a="https:"===e.protocol?"https":"http")}if(t&&r)return{host:t,port:r,scheme:a}}async function s_(e){let{device:t,appId:r,runtime:a}=e;if(!r)return;let i=sN(a);if(i){if("android"===t.platform)return void await sE(t,r,i);"ios"===t.platform&&"simulator"===t.kind&&await sx(t,r,i)}}async function sD(e){let{device:t,appId:r}=e;if(r){if("android"===t.platform)return void await sk(t,r);"ios"===t.platform&&"simulator"===t.kind&&await sM(t,r)}}async function sE(e,t,r){var a,i,n,o,s,l;let d,u;s$(t);let c=(a=await sL(e,t),i=sg,n=`${r.host}:${r.port}`,d=` <string name="${sU(i)}">${sU(n)}</string>`,sR(sP(a,i),d));o=c,s=sI,l="https"===r.scheme,u=` <boolean name="${sU(s)}" value="${l?"true":"false"}" />`,c=sR(sP(o,s),u),await sO(e,t,c)}async function sk(e,t){s$(t);let r=await sL(e,t),a=sP(r,sg),i=sP(a,sI);i!==r&&await sO(e,t,i)}async function sL(e,t){let r=await c("adb",rN(e,["shell","run-as",t,"cat",sw]),{allowFailure:!0});return 0!==r.exitCode?sb:sC(r.stdout)}async function sO(e,t,r){let a=rN(e,["shell","run-as",t,"id"]),i=await c("adb",a,{allowFailure:!0});if(0!==i.exitCode){let e=sV(i.stdout,i.stderr);throw new w("COMMAND_FAILED",e?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,{package:t,cmd:"adb",args:a,stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,hint:e?sy:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await c("adb",rN(e,["shell","run-as",t,"mkdir","-p","shared_prefs"])),await c("adb",rN(e,["shell","run-as",t,"tee",sw]),{stdin:r.trimEnd()})}catch(a){let e=f(a);if("TOOL_MISSING"===e.code)throw e;let r=sV("string"==typeof e.details?.stdout?e.details.stdout:"","string"==typeof e.details?.stderr?e.details.stderr:"");throw new w("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?sy:"adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command."},e)}}async function sx(e,t,r){await c("xcrun",ex(e,["spawn",e.id,"defaults","write",t,sA,"-string",`${r.host}:${r.port}`])),await c("xcrun",ex(e,["spawn",e.id,"defaults","write",t,sv,"-string",r.scheme]))}async function sM(e,t){await c("xcrun",ex(e,["spawn",e.id,"defaults","delete",t,sA]),{allowFailure:!0}),await c("xcrun",ex(e,["spawn",e.id,"defaults","delete",t,sv]),{allowFailure:!0})}function sC(e){let t=e.trim();return t.includes("<map")&&t.includes("</map>")?`${t}
33
- `:sb}function sR(e,t){return sC(e).replace("</map>",`${t}
34
- </map>`)}function sP(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return sC(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 sT(e){let t=e?.trim();return t&&t.length>0?t:void 0}function s$(e){if("binary"!==r4(e))return;let t=r8(e);throw new w("INVALID_ARGS",t,{package:e,hint:t})}function sF(e){if(Number.isInteger(e)&&!(e<=0)&&!(e>65535))return e}function sU(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function sV(e,t){let r=`${e}
35
- ${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))}function sG(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=/^\d+$/.test(t??""),a=o1(r?e.slice(0,-1):e.slice());return!a||a.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:a.selectorExpression,selectorTimeout:r?t:null}}function sB(e){return!!e&&!Number.isNaN(Number(e))}let sj=eb(process.env.AGENT_DEVICE_INSTALL_SOURCE_RETAIN_TTL_MS,9e5,5e3),sq=new Map;async function sH(e){let t=await a.mkdtemp(i.join(T.tmpdir(),"agent-device-materialized-"));try{let r=await sJ(e.installablePath,i.join(t,"installable")),a=e.archivePath?await sJ(e.archivePath,i.join(t,"archive")):void 0,n=u.randomUUID(),o=e.ttlMs??sj,s=Date.now()+o,l=setTimeout(()=>{sW(n)},o);return sq.set(n,{rootPath:t,installablePath:r,archivePath:a,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:s,timer:l}),{materializationId:n,installablePath:r,...a?{archivePath:a}:{},expiresAt:new Date(s).toISOString()}}catch(e){throw await a.rm(t,{recursive:!0,force:!0}),e}}async function sW(e,t){let r=sq.get(e);if(!r)throw new w("INVALID_ARGS",`Materialized paths not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new w("UNAUTHORIZED","Materialized paths belong to a different tenant");clearTimeout(r.timer),sq.delete(e),await a.rm(r.rootPath,{recursive:!0,force:!0})}async function sz(e){let t=Array.from(sq.entries()).filter(([,t])=>t.sessionName===e).map(([e])=>e);await Promise.all(t.map(async e=>{await sW(e)}))}async function sJ(e,t){let r=await a.stat(e);await a.mkdir(t,{recursive:!0});let n=i.join(t,i.basename(e));return r.isDirectory()?await a.cp(e,n,{recursive:!0}):await a.copyFile(e,n),n}async function sK(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 w("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await oP(e.session.device),e.session.device}if(!r)throw new w("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let a=await ok(e.flags??{});return await oP(a),a}async function sX(e){let{req:t,sessionName:r,sessionStore:a,deps:i}=e,n=a.get(r);try{let e,o,s,l=(o=function(e){let t=e.meta?.installSource;if(!t)throw new w("INVALID_ARGS","install_from_source requires a source payload");if("url"===t.kind){if(!t.url||0===t.url.trim().length)throw new w("INVALID_ARGS","install_from_source url source requires a non-empty url");return t}if(!t.path||0===t.path.trim().length)throw new w("INVALID_ARGS","install_from_source path source requires a non-empty path");return t}(t),(s=t.meta?.uploadedArtifactId)&&"path"===o.kind?{source:{kind:"path",path:t1(s,t.meta?.tenantId)},cleanup:()=>{t2(s)}}:{source:o,cleanup:()=>{}}),d=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 w("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),u=await (i?.resolveInstallDevice??sK)({session:n,flags:t.flags});if(!oM("install",u))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"install_from_source is not supported on this device"}};let c=(i?.getRequestSignal??ef)(t.meta?.requestId);if("ios"===u.platform){let e,o=i?.installIosInstallablePath??(await Promise.resolve().then(()=>({closeIosApp:nj,ensureBootedSimulator:i0,installIosApp:nH,installIosInstallablePath:nz,listIosApps:nY,listSimulatorApps:nQ,openIosApp:nG,openIosDevice:nB,parseIosDeviceAppsPayload:iz,pushIosNotification:nX,readIosClipboardText:nJ,reinstallIosApp:nW,resolveIosApp:nV,screenshotIos:n_,setIosSetting:nZ,uninstallIosApp:nq,writeIosClipboardText:nK}))).installIosInstallablePath,s=i?.prepareIosInstallArtifact??(await Promise.resolve().then(()=>({prepareIosInstallArtifact:i4,readIosBundleInfo:i8}))).prepareIosInstallArtifact,p=await s(l.source,{signal:c});try{if(d.enabled&&(e=await sH({archivePath:p.archivePath,installablePath:p.installablePath,tenantId:t.meta?.tenantId,sessionName:n?r:void 0,ttlMs:d.ttlMs})),await o(u,p.installablePath),!p.bundleId)throw new w("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");let i={...e?.archivePath?{archivePath:e.archivePath}:{},...e?{installablePath:e.installablePath}:{},bundleId:p.bundleId,...p.appName?{appName:p.appName}:{},launchTarget:p.bundleId,...e?{materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}};return n&&a.recordAction(n,{command:"install_source",positionals:[],flags:t.flags??{},result:i}),{ok:!0,data:i}}catch(r){throw e&&await sW(e.materializationId,t.meta?.tenantId).catch(()=>{}),r}finally{await p.cleanup(),l.cleanup()}}let p=i?.prepareAndroidInstallArtifact??(await Promise.resolve().then(()=>({prepareAndroidInstallArtifact:aw}))).prepareAndroidInstallArtifact,f=i?.installAndroidInstallablePathAndResolvePackageName??(await Promise.resolve().then(()=>({appSwitcherAndroid:a7,backAndroid:a5,closeAndroidApp:aP,dismissAndroidKeyboard:iw,ensureAdb:r_,fillAndroid:ia,focusAndroid:ir,getAndroidAppState:ak,getAndroidKeyboardState:ih,homeAndroid:a9,inferAndroidAppName:aE,installAndroidApp:aW,installAndroidInstallablePath:aq,installAndroidInstallablePathAndResolvePackageName:aH,isAmStartError:aM,listAndroidApps:aS,longPressAndroid:ie,openAndroidApp:aO,openAndroidDevice:aR,parseAndroidLaunchComponent:aC,pressAndroid:a8,pushAndroidNotification:ix,readAndroidClipboardText:ig,reinstallAndroidApp:az,resolveAndroidApp:ab,screenshotAndroid:iR,scrollAndroid:ii,scrollIntoViewAndroid:io,setAndroidSetting:iN,snapshotAndroid:a0,swipeAndroid:a6,typeAndroid:it,writeAndroidClipboardText:iI}))).installAndroidInstallablePathAndResolvePackageName,m=await p(l.source,{signal:c});try{d.enabled&&(e=await sH({archivePath:m.archivePath,installablePath:m.installablePath,tenantId:t.meta?.tenantId,sessionName:n?r:void 0,ttlMs:d.ttlMs}));let o=await f(u,m.installablePath,m.packageName);if(!o)throw new w("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let s=(i?.inferAndroidAppName??(await Promise.resolve().then(()=>({appSwitcherAndroid:a7,backAndroid:a5,closeAndroidApp:aP,dismissAndroidKeyboard:iw,ensureAdb:r_,fillAndroid:ia,focusAndroid:ir,getAndroidAppState:ak,getAndroidKeyboardState:ih,homeAndroid:a9,inferAndroidAppName:aE,installAndroidApp:aW,installAndroidInstallablePath:aq,installAndroidInstallablePathAndResolvePackageName:aH,isAmStartError:aM,listAndroidApps:aS,longPressAndroid:ie,openAndroidApp:aO,openAndroidDevice:aR,parseAndroidLaunchComponent:aC,pressAndroid:a8,pushAndroidNotification:ix,readAndroidClipboardText:ig,reinstallAndroidApp:az,resolveAndroidApp:ab,screenshotAndroid:iR,scrollAndroid:ii,scrollIntoViewAndroid:io,setAndroidSetting:iN,snapshotAndroid:a0,swipeAndroid:a6,typeAndroid:it,writeAndroidClipboardText:iI}))).inferAndroidAppName)(o),l={...e?.archivePath?{archivePath:e.archivePath}:{},...e?{installablePath:e.installablePath}:{},packageName:o,...s?{appName:s}:{},launchTarget:o,...e?{materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}};return n&&a.recordAction(n,{command:"install_source",positionals:[],flags:t.flags??{},result:l}),{ok:!0,data:l}}catch(r){throw e&&await sW(e.materializationId,t.meta?.tenantId).catch(()=>{}),r}finally{await m.cleanup(),l.cleanup()}}catch(e){return{ok:!1,error:y(e)}}}async function sZ(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new w("INVALID_ARGS","release_materialized_paths requires a materializationId");return await sW(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:y(e)}}}async function sY(e){let t,r,a,{deviceName:i,runtime:n,simulatorSetPath:o,reuseExisting:s,boot:l,ensureReady:d}=e;if("darwin"!==process.platform)throw new w("UNSUPPORTED_PLATFORM","ensure-simulator is only available on macOS");let u={simulatorSetPath:o??void 0};if(s){let e=await sQ({deviceName:i,runtime:n,simctlOpts:u});e?(t=e.udid,r=e.runtime,a=!1):(t=(await s0({deviceName:i,runtime:n,simctlOpts:u})).udid,r=await s1(t,u),a=!0)}else t=(await s0({deviceName:i,runtime:n,simctlOpts:u})).udid,r=await s1(t,u),a=!0;let c=!1;if(l){let e={platform:"ios",id:t,name:i,kind:"simulator",target:"mobile",...o?{simulatorSetPath:o}:{}};await d(e),c=!0}return{udid:t,device:i,runtime:r,created:a,booted:c}}async function sQ(e){let{deviceName:t,runtime:r,simctlOpts:a}=e,i=await c("xcrun",eO(["list","devices","-j"],a),{allowFailure:!0,timeoutMs:iU});if(0!==i.exitCode)return null;try{let e=JSON.parse(String(i.stdout??""));for(let[a,i]of Object.entries(e.devices??{}))if(!r||s2(a).includes(s2(r))){for(let e of i)if(e.isAvailable&&e.name.toLowerCase()===t.toLowerCase())return{udid:e.udid,runtime:a}}return null}catch{return null}}async function s0(e){let{deviceName:t,runtime:r,simctlOpts:a}=e,i=r?["create",t,t,r]:["create",t,t],n=await c("xcrun",eO(i,a),{allowFailure:!0});if(0!==n.exitCode)throw new w("COMMAND_FAILED","Failed to create iOS simulator",{deviceName:t,runtime:r,stdout:String(n.stdout??""),stderr:String(n.stderr??""),exitCode:n.exitCode,hint:"Ensure the device type and runtime identifiers are valid. Run `xcrun simctl list devicetypes` and `xcrun simctl list runtimes` to see available options."});let o=String(n.stdout??"").trim();if(!o)throw new w("COMMAND_FAILED","simctl create returned no UDID",{deviceName:t,runtime:r,stdout:String(n.stdout??""),stderr:String(n.stderr??"")});return{udid:o}}async function s1(e,t){let r=await c("xcrun",eO(["list","devices","-j"],t),{allowFailure:!0,timeoutMs:iU});if(0!==r.exitCode)return"";try{let t=JSON.parse(String(r.stdout??""));for(let[r,a]of Object.entries(t.devices??{}))if(a.some(t=>t.udid===e))return r;return""}catch{return""}}function s2(e){return e.toLowerCase().replace(/[._-]/g,"")}let s3=eb(process.env.AGENT_DEVICE_IOS_SIMULATOR_POST_CLOSE_SETTLE_MS,300,0),s4=eb(process.env.AGENT_DEVICE_IOS_SIMULATOR_POST_OPEN_SETTLE_MS,300,0);function s8(e,t,r){return t||s6(r)?null:{ok:!1,error:{code:"INVALID_ARGS",message:`${e} requires an active session or an explicit device selector (e.g. --platform ios).`}}}function s6(e){return!!(e?.platform||e?.target||e?.device||e?.udid||e?.serial)}function s5(e){return"ios"===e.platform&&"simulator"===e.kind}async function s9(e,t){s5(e)&&!(t<=0)&&await new Promise(e=>setTimeout(e,t))}async function s7(e){let t=s6(e.flags)||!e.session?await e.resolveTargetDeviceFn(e.flags??{}):await le(e.session.device,e.resolveTargetDeviceFn);return!1!==e.ensureReady&&await e.ensureReadyFn(t),t}async function le(e,t){if("ios"!==e.platform||"simulator"!==e.kind||"darwin"!==process.platform)return e;let r={platform:"ios",target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await t(r)}catch(e){if(!(e instanceof w)||"DEVICE_NOT_FOUND"!==e.code)throw e}return await t({platform:"ios",target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function lt(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 lr=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function la(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function li(e){let t=e?.trim();return t&&t.length>0?t:void 0}function ln(e,t){if(void 0!==e){if("string"!=typeof e)throw new w("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return li(e)}}function lo(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new w("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function ls(e){if("ios"===e||"android"===e)return e}function ll(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:a,device:i}=e,n=r.getRuntimeHints(a),o=function(e){let{runtime:t,sessionName:r,platform:a}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new w("INVALID_ARGS","open runtime must be an object.");let i=Object.keys(t).find(e=>!lr.includes(e));if(i)throw new w("INVALID_ARGS",`Invalid open runtime field: ${i}. Supported fields are ${lr.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new w("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new w("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,a),metroHost:ln(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new w("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return lo(e)}}(t.metroPort),bundleUrl:ln(t.bundleUrl,"bundleUrl"),launchUrl:ln(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:ls(i.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let a=e.getRuntimeHints(t);if(!a)return;let i=r?.platform,n=ls(i);if(a.platform&&r&&!n)throw new w("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${i}.`);if(a.platform&&n&&a.platform!==n)throw new w("INVALID_ARGS",`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${i}. Clear the runtime hints or use a different session.`);return n&&a.platform!==n?{...a,platform:n}:a}(r,a,i),previousRuntime:n,replacedStoredRuntime:!1}:{runtime:o&&la(o)>0?o:void 0,previousRuntime:n,replacedStoredRuntime:!0}}(e)}}catch(t){let e=f(t);return{ok:!1,response:{ok:!1,error:{code:e.code,message:e.message,details:e.details}}}}}async function ld(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:i,clearRuntimeHints:n}=e;!t||!i?.appBundleId||!sS(r)||sS(a)||await n({device:i.device,appId:i.appBundleId})}async function lu(e){var t,r;let{req:a,sessionName:i,sessionStore:n,clearRuntimeHints:o=sD}=e,s=(a.positionals?.[0]??"show").toLowerCase(),l=n.get(i),d=n.getRuntimeHints(i);if(!["set","show","clear"].includes(s))return{ok:!1,error:{code:"INVALID_ARGS",message:"runtime requires set, show, or clear"}};if("clear"===s){sS(d)&&l?.appBundleId&&await o({device:l.device,appId:l.appBundleId});let e=n.clearRuntimeHints(i);return{ok:!0,data:{session:i,cleared:e}}}if("show"===s)return{ok:!0,data:{session:i,configured:!!d,runtime:d}};let u=ls(a.flags?.platform??d?.platform??l?.device.platform);if(!u)return{ok:!1,error:{code:"INVALID_ARGS",message:"runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first."}};if(l&&l.device.platform!==u)return{ok:!1,error:{code:"INVALID_ARGS",message:`runtime set targets ${u}, but session "${i}" is already bound to ${l.device.platform}.`}};let c={platform:(t=a.flags,r={platform:u,metroHost:li(t?.metroHost),metroPort:lo(t?.metroPort),bundleUrl:li(t?.bundleUrl),launchUrl:li(t?.launchUrl)}).platform??d?.platform,metroHost:r.metroHost??d?.metroHost,metroPort:r.metroPort??d?.metroPort,bundleUrl:r.bundleUrl??d?.bundleUrl,launchUrl:r.launchUrl??d?.launchUrl};return 0===la(c)?{ok:!1,error:{code:"INVALID_ARGS",message:"runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."}}:(n.setRuntimeHints(i,c),{ok:!0,data:{session:i,configured:!0,runtime:c}})}async function lc(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return rk(t)?"macos"===e.platform?void 0:"device"===e.kind?rL(r,t):void 0:await lp(e,t)}async function lp(e,t){try{let{resolveIosApp:r}=await Promise.resolve().then(()=>({resolveIosApp:nV}));return await r(e,t)}catch{return}}async function lf(e,t){if(!("android"!==e.platform||!t||rk(t)))try{let{resolveAndroidApp:r}=await Promise.resolve().then(()=>({resolveAndroidApp:ab})),a=await r(e,t);return"package"===a.type?a.value:void 0}catch{return}}async function lm(e,t,r,a){return await lc(e,t,r)??await a(e,t)??("android"===e.platform&&t&&rk(t)?r:void 0)}let lh="open-command-roundtrip",lw="Not implemented for this platform in this release.";async function lg(e){let{device:t,closeTarget:r,stopIosRunner:a,dispatch:i,outFlag:n,context:o,settleSimulator:s}=e;"android"!==t.platform&&await a(t.id),await i(t,"close",[r],n,o),await s(t,s3)}async function lI(e){let{runtime:t,device:r,dispatch:a,req:i,logPath:n,appBundleId:o,traceLogPath:s,openPositionals:l}=e,d=t?.launchUrl;if(!d||0===l.length||l.length>1)return;let u=l[0]?.trim();!u||rk(u)||await a(r,"open",[d],i.flags?.out,{...oC(n,i.flags,o,s)})}async function lA(e){var t,r,a;let{req:i,sessionName:n,sessionStore:o,logPath:s,device:l,dispatch:d,applyRuntimeHints:u,stopIosRunner:c,settleSimulator:p,openTarget:f,openPositionals:m,appBundleId:h,runtime:w,existingSession:g}=e,I=i.flags?.relaunch===!0,A=g?.trace?.outPath;if(I&&f){let e=h??f;await lg({device:l,closeTarget:e,stopIosRunner:c,dispatch:d,outFlag:i.flags?.out,context:{...oC(s,i.flags,h??g?.appBundleId,A)},settleSimulator:p})}await u({device:l,appId:h,runtime:w});let v=Date.now();await d(l,"open",m,i.flags?.out,{...oC(s,i.flags,h)}),await lI({runtime:w,device:l,dispatch:d,req:i,logPath:s,appBundleId:h,traceLogPath:A,openPositionals:m});let y=f?{durationMs:Math.max(0,Date.now()-v),measuredAt:new Date().toISOString(),method:lh,appTarget:f,appBundleId:h}:void 0;await p(l,s4);let b=function(e){let{existingSession:t,sessionName:r,device:a,appBundleId:i,openTarget:n,saveScript:o}=e;return t?{...t,device:a,appBundleId:i,appName:n,recordSession:t.recordSession||o,snapshot:void 0}:{name:r,device:a,createdAt:Date.now(),appBundleId:i,appName:n,recordSession:o,actions:[]}}({existingSession:g,sessionName:n,device:l,appBundleId:h,openTarget:f,saveScript:!!i.flags?.saveScript});void 0!==i.runtime&&(t=o,r=n,(a=w)&&(0===la(a)?t.clearRuntimeHints(r):t.setRuntimeHints(r,a)));let S=function(e){let{sessionName:t,appName:r,appBundleId:a,startup:i,device:n,runtime:o}=e,s={session:t};return r&&(s.appName=r),a&&(s.appBundleId=a),i&&(s.startup=i),o&&la(o)>0&&(s.runtime=o),n&&(s.platform=n.platform,s.target=n.target??"mobile",s.device=n.name,s.id=n.id,s.kind=n.kind,"android"===n.platform&&(s.serial=n.id)),n?.platform==="ios"&&(s.device_udid=n.id,s.ios_simulator_device_set=n.simulatorSetPath??null),s}({sessionName:n,appName:f,appBundleId:h,startup:y,device:l,runtime:w});return o.recordAction(b,{command:"open",positionals:m,flags:i.flags??{},runtime:void 0!==i.runtime?w:void 0,result:S}),o.set(n,b),{ok:!0,data:S}}async function lv(e){let{req:t,sessionName:r,logPath:a,sessionStore:i,dispatch:n,ensureReady:o,resolveDevice:s,applyRuntimeHints:l=s_,clearRuntimeHints:d=sD,stopIosRunner:u=tp,settleSimulator:c=s9,resolveAndroidPackageForOpen:p=lf}=e,f=t.flags?.relaunch===!0;if(i.has(r)){let e=i.get(r),m=t.positionals?.[0],h=m??(f?e?.appName:void 0);if(!e||!h)return f?{ok:!1,error:{code:"INVALID_ARGS",message:"open --relaunch requires an app name or an active session app."}}:{ok:!1,error:{code:"INVALID_ARGS",message:"Session already active. Close it first or pass a new --session name."}};if(f&&rk(h))return{ok:!1,error:{code:"INVALID_ARGS",message:"open --relaunch does not support URL targets."}};if(f&&"android"===e.device.platform&&"binary"===r4(h))return{ok:!1,error:{code:"INVALID_ARGS",message:r8(h)}};let w=await le(e.device,s);await o(w);let g=await lm(w,h,e.appBundleId,p),I=ll({req:t,sessionStore:i,sessionName:r,device:w});if(!I.ok)return I.response;let{runtime:A,previousRuntime:v,replacedStoredRuntime:y}=I.data;await ld({replacedStoredRuntime:y,previousRuntime:v,runtime:A,session:e,clearRuntimeHints:d});let b=m?t.positionals??[]:[h];return await lA({req:t,sessionName:r,sessionStore:i,logPath:a,device:w,dispatch:n,applyRuntimeHints:l,stopIosRunner:u,settleSimulator:c,openTarget:h,openPositionals:b,appBundleId:g,runtime:A,existingSession:e})}let m=t.positionals?.[0];if(f&&!m)return{ok:!1,error:{code:"INVALID_ARGS",message:"open --relaunch requires an app argument."}};if(f&&m&&rk(m))return{ok:!1,error:{code:"INVALID_ARGS",message:"open --relaunch does not support URL targets."}};let h=await s(t.flags??{});if(f&&"android"===h.platform&&m&&"binary"===r4(m))return{ok:!1,error:{code:"INVALID_ARGS",message:r8(m)}};let w=i.toArray().find(e=>e.device.id===h.id);if(w)return{ok:!1,error:{code:"DEVICE_IN_USE",message:`Device is already in use by session "${w.name}".`,details:{session:w.name,deviceId:h.id,deviceName:h.name}}};await o(h);let g=await lm(h,m,void 0,p),I=ll({req:t,sessionStore:i,sessionName:r,device:h});if(!I.ok)return I.response;let{runtime:A}=I.data;return await lA({req:t,sessionName:r,sessionStore:i,logPath:a,device:h,dispatch:n,applyRuntimeHints:l,stopIosRunner:u,settleSimulator:c,openTarget:m,openPositionals:t.positionals??[],appBundleId:g,runtime:A})}async function ly(e){let t=await c("adb",["-s",e.id,"emu","kill"],{allowFailure:!0,timeoutMs:15e3});return{success:0===t.exitCode,exitCode:t.exitCode,stdout:String(t.stdout??""),stderr:String(t.stderr??"")}}async function lb(e){let{device:t,shutdownRequested:r,shutdownSimulator:a,shutdownAndroidEmulator:i}=e;if(r&&(s5(t)||"android"===t.platform&&"emulator"===t.kind))try{return s5(t)?await a(t):await i(t)}catch(t){let e=y(t);return{success:!1,exitCode:-1,stdout:"",stderr:e.message,error:e}}}async function lS(e){let{req:t,sessionName:r,logPath:a,sessionStore:i,dispatch:n,stopIosRunner:o=tp,clearRuntimeHints:s=sD,settleSimulator:l=s9,shutdownSimulator:d=i1,shutdownAndroidEmulator:u=ly,appLogOps:c}=e,p=i.get(r);if(!p)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session"}};p.appLog&&await c.stop(p.appLog),t.positionals&&t.positionals.length>0&&("ios"===p.device.platform&&await o(p.device.id),await n(p.device,"close",t.positionals,t.flags?.out,{...oC(a,t.flags,p.appBundleId,p.trace?.outPath)}),await l(p.device,s3)),"ios"===p.device.platform&&await o(p.device.id),sS(i.getRuntimeHints(r))&&p.appBundleId&&await s({device:p.device,appId:p.appBundleId}).catch(()=>{}),i.recordAction(p,{command:"close",positionals:t.positionals??[],flags:t.flags??{},result:{session:r}}),t.flags?.saveScript&&(p.recordSession=!0),i.writeSessionLog(p),await sz(r).catch(()=>{}),i.delete(r);let f=await lb({device:p.device,shutdownRequested:t.flags?.shutdown,shutdownSimulator:d,shutdownAndroidEmulator:u});return f?{ok:!0,data:{session:r,shutdown:f}}:{ok:!0,data:{session:r}}}let lN={ios:async(e,t,r)=>{let{reinstallIosApp:a}=await Promise.resolve().then(()=>({reinstallIosApp:nW}));return await a(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:a}=await Promise.resolve().then(()=>({reinstallAndroidApp:az}));return await a(e,t,r)}},l_={ios:async(e,t,r)=>{let{installIosApp:a}=await Promise.resolve().then(()=>({installIosApp:nH})),i=await a(e,r,{appIdentifierHint:t});return{bundleId:i.bundleId,appName:i.appName,launchTarget:i.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:a}=await Promise.resolve().then(()=>({installAndroidApp:aW})),i=await a(e,r);return{package:i.packageName,appName:i.appName,launchTarget:i.launchTarget}}};async function lD(e){let{req:t,command:r,sessionName:a,sessionStore:i,ensureReady:n,resolveDevice:o,deployOps:s}=e,l=i.get(a),d=t.flags??{},u=s8(r,l,d);if(u)return u;let c=t.positionals?.[0]?.trim(),p=t.positionals?.[1]?.trim();if(!c||!p)return{ok:!1,error:{code:"INVALID_ARGS",message:`${r} requires: ${r} <app> <path-to-app-binary>`}};let f=t.meta?.uploadedArtifactId;try{let e,a=f?t1(f,t.meta?.tenantId):tP.expandHome(p);if(!R.existsSync(a))return{ok:!1,error:{code:"INVALID_ARGS",message:`App binary not found: ${a}`}};let u=await s7({session:l,flags:d,ensureReadyFn:n,resolveTargetDeviceFn:o,ensureReady:!1});if(!oM(r,u))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:`${r} is not supported on this device`}};if("ios"===u.platform){let t=await s.ios(u,c,a),r=t.bundleId;e=r?{app:c,appPath:a,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:c,appPath:a,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await s.android(u,c,a),r=t.package;e=r?{app:c,appPath:a,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:c,appPath:a,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}return l&&i.recordAction(l,{command:r,positionals:t.positionals??[],flags:t.flags??{},result:e}),{ok:!0,data:e}}finally{f&&t2(f)}}let lE=["platform","target","device","udid","serial","verbose","out"];async function lk(e,t,r){let a=e.flags?.batchOnError??"stop";if("stop"!==a)return{ok:!1,error:{code:"INVALID_ARGS",message:`Unsupported batch on-error mode: ${a}.`}};let i=e.flags?.batchMaxSteps??B;if(!Number.isInteger(i)||i<1||i>1e3)return{ok:!1,error:{code:"INVALID_ARGS",message:`Invalid batch max-steps: ${String(e.flags?.batchMaxSteps)}`}};try{let a=q(e.flags?.batchSteps,i),n=Date.now(),o=[];for(let i=0;i<a.length;i+=1){let n=a[i],s=await lL(e,t,n,r,i+1);if(!s.ok)return{ok:!1,error:{code:s.error.code,message:`Batch failed at step ${s.step} (${n.command}): ${s.error.message}`,hint:s.error.hint,diagnosticId:s.error.diagnosticId,logPath:s.error.logPath,details:{...s.error.details??{},step:s.step,command:n.command,positionals:n.positionals,executed:i,total:a.length,partialResults:o}}};o.push(s.result)}return{ok:!0,data:{total:a.length,executed:a.length,totalDurationMs:Date.now()-n,results:o}}}catch(t){let e=f(t);return{ok:!1,error:{code:e.code,message:e.message,details:e.details}}}}async function lL(e,t,r,a,i){let n=Date.now(),o=function(e,t){let{batchSteps:r,batchOnError:a,batchMaxSteps:i,...n}=t??{},o=e??{};for(let e of lE)void 0===n[e]&&void 0!==o[e]&&(n[e]=o[e]);return n}(e.flags,r.flags);void 0===o.session&&(o.session=t);let s=await a({token:e.token,session:t,command:r.command,positionals:r.positionals,flags:o,runtime:r.runtime,meta:e.meta}),l=Date.now()-n;return s.ok?{ok:!0,step:i,result:{step:i,command:r.command,ok:!0,data:s.data??{},durationMs:l}}:{ok:!1,step:i,error:s.error}}let lO='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',lx='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").',lM=["platform","target","device","udid","serial","verbose","out"],lC=["path","start","stop","doctor","mark","clear"],lR=`logs requires ${lC.slice(0,-1).join(", ")}, or ${lC.at(-1)}`,lP=["dump","log"],lT=`network requires ${lP.join(" or ")}`,l$=["summary","headers","body","all"],lF=`network include mode must be one of: ${l$.join(", ")}`,lU=async({avdName:e,serial:t,headless:r})=>{let{ensureAndroidEmulatorBooted:a}=await Promise.resolve().then(()=>({ensureAndroidEmulatorBooted:rQ}));return await a({avdName:e,serial:t,headless:r})};async function lV(e){let{req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:n,resolveDevice:o,dispatch:s,command:l,positionals:d,recordPositionals:u,deriveNextSession:c}=e,p=i.get(r),f=t.flags??{},m=s8(l,p,f);if(m)return m;let h=await s7({session:p,flags:f,ensureReadyFn:n,resolveTargetDeviceFn:o,ensureReady:!0});if(!oM(l,h))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:`${l} is not supported on this device`}};let w=await s(h,l,d,t.flags?.out,{...oC(a,t.flags,p?.appBundleId,p?.trace?.outPath)});if(p){let e=c?await c(p,w,h):p;i.recordAction(e,{command:l,positionals:u??d,flags:t.flags??{},result:w??{}}),e!==p&&i.set(r,e)}return{ok:!0,data:w??{}}}function lG(e){return e.appLog?e.appLog.backend:"ios"===e.device.platform?"device"===e.device.kind?"ios-device":"ios-simulator":"android"}async function lB(e){let{req:t,sessionName:r,sessionStore:a,ensureReady:i,resolveDevice:n}=e,o=a.get(r),s=t.flags??{},l=s.platform;if(!o&&"string"==typeof s?.session&&s.session.trim().length>0)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"ios"===l?`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 d=s8("appstate",o,s);if(d)return d;let u=(o?.device.platform==="ios"||o?.device.platform==="macos")&&function(e,t){if(!t)return!1;if(!s6(e))return!0;let r=e?.platform;return!(r&&!eX(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())}(s,o);if("ios"===l&&!u)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:lO}};if("macos"===l&&!u)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:lx}};if(u&&o){let e=o.appName??o.appBundleId;if(!o.appName&&!o.appBundleId){let e="macos"===o.device.platform?"macOS":"iOS";return{ok:!1,error:{code:"COMMAND_FAILED",message:`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`}}}return{ok:!0,data:{platform:o.device.platform,appName:e??"unknown",appBundleId:o.appBundleId,source:"session",..."ios"===o.device.platform?{device_udid:o.device.id,ios_simulator_device_set:o.device.simulatorSetPath??null}:{}}}}let c=await s7({session:o,flags:s,ensureReadyFn:i,resolveTargetDeviceFn:n,ensureReady:!0});if("ios"===c.platform)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:lO}};if("macos"===c.platform)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:lx}};let{getAndroidAppState:p}=await Promise.resolve().then(()=>({getAndroidAppState:ak})),f=await p(c);return{ok:!0,data:{platform:"android",package:f.package,activity:f.activity}}}async function lj(e){let{req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:n,resolveDevice:o,dispatch:s}=e,l=i.get(r),d=t.flags??{},u=s8("clipboard",l,d);if(u)return u;let c=(t.positionals?.[0]??"").toLowerCase();if("read"!==c&&"write"!==c)return{ok:!1,error:{code:"INVALID_ARGS",message:"clipboard requires a subcommand: read or write"}};let p=await s7({session:l,flags:d,ensureReadyFn:n,resolveTargetDeviceFn:o,ensureReady:!0});if(!oM("clipboard",p))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"clipboard is not supported on this device"}};let f=await s(p,"clipboard",t.positionals??[],t.flags?.out,{...oC(a,t.flags,l?.appBundleId,l?.trace?.outPath)});return l&&i.recordAction(l,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:f??{}}),{ok:!0,data:{platform:p.platform,...f??{}}}}async function lq(e){let{req:t,sessionName:r,logPath:a,sessionStore:i,invoke:n,dispatch:o,ensureReady:s,resolveTargetDevice:l,installOps:d=l_,reinstallOps:u=lN,stopIosRunner:c,appLogOps:p={start:tJ,stop:tK},ensureAndroidEmulatorBoot:m=lU,resolveAndroidPackageForOpen:h=lf,applyRuntimeHints:g=s_,clearRuntimeHints:I=sD,settleSimulator:A,shutdownSimulator:v,shutdownAndroidEmulator:b,listAndroidDevices:S,listAppleDevices:N,listAppleApps:_}=e,D=o??oL,E=s??oP,k=l??ok,L=c??tp,O=A??s9,x=t.command;if("session_list"===x)return{ok:!0,data:{sessions:i.toArray().map(e=>({name:e.name,platform:e.device.platform,target:e.device.target??"mobile",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("runtime"===x)return await lu({req:t,sessionName:r,sessionStore:i,clearRuntimeHints:I});if("ensure-simulator"===x)try{let e=t.flags??{},r=e.device,a=e.runtime,i=eE(e.iosSimulatorDeviceSet);if(!r)return{ok:!1,error:{code:"INVALID_ARGS",message:"ensure-simulator requires --device <name>"}};let n=!0===e.boot,o=!1!==e.reuseExisting,s=await sY({deviceName:r,runtime:a,simulatorSetPath:i,reuseExisting:o,boot:n,ensureReady:E});return{ok:!0,data:{udid:s.udid,device:s.device,runtime:s.runtime,ios_simulator_device_set:i??null,created:s.created,booted:s.booted}}}catch(t){let e=f(t);return{ok:!1,error:{code:e.code,message:e.message,details:e.details}}}if("devices"===x)try{let e=[],r=eL(t.flags?.androidDeviceAllowlist),a=t.flags?.platform,i=eZ({simulatorSetPath:eE(t.flags?.iosSimulatorDeviceSet),platform:a,target:t.flags?.target});if("android"===a){let t=S??(await Promise.resolve().then(()=>({ensureAndroidEmulatorBooted:rQ,ensureAndroidEmulatorHeadlessBooted:r0,listAndroidDevices:rH,parseAndroidAvdList:rz,parseAndroidEmulatorAvdNameOutput:rP,parseAndroidFeatureListForTv:rG,parseAndroidTargetFromCharacteristics:rV,resolveAndroidAvdName:rJ,resolveAndroidEmulatorAvdName:rU,waitForAndroidBoot:r1}))).listAndroidDevices;e.push(...await t({serialAllowlist:r}))}else if("ios"===a||"macos"===a){let t=N??(await Promise.resolve().then(()=>({findBootableIosSimulator:o_,isAppleProductType:oA,isAppleTvProductType:ov,isSupportedAppleDevicectlDevice:oN,listAppleDevices:oD,listIosDevices:oD,resolveAppleTargetFromDevicectlDevice:oS}))).listAppleDevices;e.push(...await t({simulatorSetPath:i}))}else{if("apple"!==a){let t=S??(await Promise.resolve().then(()=>({ensureAndroidEmulatorBooted:rQ,ensureAndroidEmulatorHeadlessBooted:r0,listAndroidDevices:rH,parseAndroidAvdList:rz,parseAndroidEmulatorAvdNameOutput:rP,parseAndroidFeatureListForTv:rG,parseAndroidTargetFromCharacteristics:rV,resolveAndroidAvdName:rJ,resolveAndroidEmulatorAvdName:rU,waitForAndroidBoot:r1}))).listAndroidDevices;try{e.push(...await t({serialAllowlist:r}))}catch{}}let t=N??(await Promise.resolve().then(()=>({findBootableIosSimulator:o_,isAppleProductType:oA,isAppleTvProductType:ov,isSupportedAppleDevicectlDevice:oN,listAppleDevices:oD,listIosDevices:oD,resolveAppleTargetFromDevicectlDevice:oS}))).listAppleDevices;try{e.push(...await t({simulatorSetPath:i}))}catch{}}let n="ios"===a||"macos"===a?e.filter(e=>e.platform===a):e,o=(t.flags?.target?n.filter(e=>(e.target??"mobile")===t.flags?.target):n).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=f(t);return{ok:!1,error:{code:e.code,message:e.message,details:e.details}}}if("apps"===x){let e=i.get(r),a=t.flags??{},n=s8(x,e,a);if(n)return n;let o=await s7({session:e,flags:a,ensureReadyFn:E,resolveTargetDeviceFn:k,ensureReady:!0});if(!oM("apps",o))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"apps is not supported on this device"}};let s=t.flags?.appsFilter??"all";if(eK(o.platform)){let e=_??(await Promise.resolve().then(()=>({closeIosApp:nj,ensureBootedSimulator:i0,installIosApp:nH,installIosInstallablePath:nz,listIosApps:nY,listSimulatorApps:nQ,openIosApp:nG,openIosDevice:nB,parseIosDeviceAppsPayload:iz,pushIosNotification:nX,readIosClipboardText:nJ,reinstallIosApp:nW,resolveIosApp:nV,screenshotIos:n_,setIosSetting:nZ,uninstallIosApp:nq,writeIosClipboardText:nK}))).listIosApps;return{ok:!0,data:{apps:(await e(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}}let{listAndroidApps:l}=await Promise.resolve().then(()=>({listAndroidApps:aS}));return{ok:!0,data:{apps:(await l(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}if("boot"===x){let e,a=i.get(r),n=t.flags??{},o=s8(x,a,n);if(o)return o;let s="android"===(n.platform??a?.device.platform),l=!0===n.headless;if(l&&!s)return{ok:!1,error:{code:"INVALID_ARGS",message:"boot --headless is supported only for Android emulators."}};let d=lt({flags:n,sessionDevice:a?.device}),u=s&&!!d,c=!1;try{e=await s7({session:a,flags:n,ensureReadyFn:E,resolveTargetDeviceFn:k,ensureReady:!1})}catch(r){let t=f(r);if(s&&l&&!d&&"DEVICE_NOT_FOUND"===t.code)return{ok:!1,error:{code:"INVALID_ARGS",message:"boot --headless requires --device <avd-name> (or an Android emulator session target)."}};if(!u||"DEVICE_NOT_FOUND"!==t.code||!d)throw r;e=await m({avdName:d,serial:n.serial,headless:l}),c=!0}if(n.target&&(e.target??"mobile")!==n.target)return{ok:!1,error:{code:"DEVICE_NOT_FOUND",message:`No ${e.platform} device found matching --target ${n.target}.`}};if(s&&l){if("android"!==e.platform||"emulator"!==e.kind)return{ok:!1,error:{code:"INVALID_ARGS",message:"boot --headless is supported only for Android emulators."}};if(!c){let t=lt({flags:n,sessionDevice:a?.device,resolvedDevice:e});if(!t)return{ok:!1,error:{code:"INVALID_ARGS",message:"boot --headless requires --device <avd-name> (or an Android emulator session target)."}};e=await m({avdName:t,serial:n.serial,headless:!0})}await E(e)}else("android"!==e.platform||!0!==e.booted)&&await E(e);return oM("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"boot is not supported on this device"}}}if("appstate"===x)return await lB({req:t,sessionName:r,sessionStore:i,ensureReady:E,resolveDevice:k});if("clipboard"===x)return await lj({req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:E,resolveDevice:k,dispatch:D});if("keyboard"===x)return await lV({req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:E,resolveDevice:k,dispatch:D,command:"keyboard",positionals:t.positionals??[]});if("perf"===x){let e,t,a,n=i.get(r);return n?{ok:!0,data:(a=(t=(e=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===lh&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:lh,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)}(n.actions)).at(-1))?{available:!0,lastDurationMs:t.durationMs,lastMeasuredAt:t.measuredAt,method:lh,sampleCount:e.length,samples:e}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:lh},{session:n.name,platform:n.device.platform,device:n.device.name,deviceId:n.device.id,metrics:{startup:a,fps:{available:!1,reason:lw},memory:{available:!1,reason:lw},cpu:{available:!1,reason:lw}},sampling:{startup:{method:lh,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"}}})}:{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"perf requires an active session. Run open first."}}}if("install"===x||"reinstall"===x)return await lD({req:t,command:x,sessionName:r,sessionStore:i,ensureReady:E,resolveDevice:k,deployOps:"install"===x?d:u});if("install_source"===x)return await sX({req:t,sessionName:r,sessionStore:i});if("release_materialized_paths"===x)return await sZ({req:t});if("push"===x){let e,n=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();if(!n||!o)return{ok:!1,error:{code:"INVALID_ARGS",message:"push requires <bundle|package> <payload.json|inline-json>"}};let s="file"===(e=oo(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>tP.expandHome(e,t)})).kind?e.path:e.text;return await lV({req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:E,resolveDevice:k,dispatch:D,command:"push",positionals:[n,s],recordPositionals:[n,o]})}if("trigger-app-event"===x)return await lV({req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:E,resolveDevice:k,dispatch:D,command:"trigger-app-event",positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,a=r?await lm(e.device,r,e.appBundleId,h)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}});if("open"===x)return await lv({req:t,sessionName:r,logPath:a,sessionStore:i,dispatch:D,ensureReady:E,resolveDevice:k,applyRuntimeHints:g,clearRuntimeHints:I,stopIosRunner:L,settleSimulator:O,resolveAndroidPackageForOpen:h});if("replay"===x){let e=t.positionals?.[0];if(!e)return{ok:!1,error:{code:"INVALID_ARGS",message:"replay requires a path"}};try{let o=tP.expandHome(e,t.meta?.cwd),s=R.readFileSync(o,"utf8"),l=s.trimStart()[0];if("{"===l||"["===l)return{ok:!1,error:{code:"INVALID_ARGS",message:"replay accepts .ad script files. JSON replay payloads are no longer supported."}};let d=function(e){let t=[];for(let r of e.split(/\r?\n/)){let e=function(e){let t=e.trim();if(0===t.length||t.startsWith("#"))return null;let r=function(e){let t=[],r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;if('"'===e[r]){let a=r+1,i=!1;for(;a<e.length;){let t=e[a];if('"'===t&&!i)break;i="\\"===t&&!i,"\\"!==t&&(i=!1),a+=1}if(a>=e.length)throw new w("INVALID_ARGS",`Invalid replay script line: ${e}`);let n=e.slice(r,a+1);t.push(JSON.parse(n)),r=a+1;continue}let a=r;for(;a<e.length&&!/\s/.test(e[a]);)a+=1;t.push(e.slice(r,a)),r=a}return t}(t);if(0===r.length)return null;let[a,...i]=r;if("context"===a)return null;let n={ts:Date.now(),command:a,positionals:[],flags:{}};if("snapshot"===a){n.positionals=[];for(let e=0;e<i.length;e+=1){let t=i[e];if("-i"===t){n.flags.snapshotInteractiveOnly=!0;continue}if("-c"===t){n.flags.snapshotCompact=!0;continue}if("--raw"===t){n.flags.snapshotRaw=!0;continue}if(("-d"===t||"--depth"===t)&&e+1<i.length){let t=Number(i[e+1]);Number.isFinite(t)&&t>=0&&(n.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if(("-s"===t||"--scope"===t)&&e+1<i.length){n.flags.snapshotScope=i[e+1],e+=1;continue}if("--backend"===t&&e+1<i.length){e+=1;continue}}return n}if("open"===a){let e=function(e){var t;let r=[],a={};for(let t of e){if("--relaunch"===t){a.relaunch=!0;continue}r.push(t)}let i=tM(r);return{positionals:i.positionals,flags:a,runtime:(t=i.flags).platform||t.metroHost||void 0!==t.metroPort||t.bundleUrl||t.launchUrl?i.flags:void 0}}(i);return n.positionals=e.positionals,Object.assign(n.flags,e.flags),n.runtime=e.runtime,n}if("runtime"===a){let e=tM(i);return n.positionals=e.positionals,Object.assign(n.flags,e.flags),n}if(tD(a)){let e=tx(a,i);if(Object.assign(n.flags,e.flags),0===e.positionals.length)return n;let t=e.positionals[0];if(t.startsWith("@"))return n.positionals=[t],e.positionals[1]&&(n.result={refLabel:e.positionals[1]}),n;let r=e.positionals[0],o=e.positionals[1];return sB(r)&&sB(o)&&e.positionals.length>=2?n.positionals=[r,o]:n.positionals=[e.positionals.join(" ")],n}if("fill"===a){if(i.length<2)return n.positionals=i,n;let e=i[0];return e.startsWith("@")?(i.length>=3?(n.positionals=[e,i.slice(2).join(" ")],n.result={refLabel:i[1]}):n.positionals=[e,i[1]],n):(n.positionals=[e,i.slice(1).join(" ")],n)}if("get"===a){if(i.length<2)return n.positionals=i,n;let e=i[0],t=i[1];return t.startsWith("@")?(n.positionals=[e,t],i[2]&&(n.result={refLabel:i[2]})):n.positionals=[e,i.slice(1).join(" ")],n}if("swipe"===a){let e=tx(a,i);return Object.assign(n.flags,e.flags),n.positionals=e.positionals,n}return n.positionals=i,n}(r);e&&t.push(e)}return t}(s),u=t.flags?.replayUpdate===!0,c=0;for(let e=0;e<d.length;e+=1){let s=d[e];if(!s||"replay"===s.command)continue;let l=await n({token:t.token,session:r,command:s.command,positionals:s.positionals??[],flags:lW(t.flags,s.flags),runtime:s.runtime,meta:t.meta});if(l.ok)continue;if(!u)return lH(l,s,e,o);let p=await lz({action:s,sessionName:r,logPath:a,sessionStore:i,dispatch:D});if(!p)return lH(l,s,e,o);if(d[e]=p,!(l=await n({token:t.token,session:r,command:p.command,positionals:p.positionals??[],flags:lW(t.flags,p.flags),runtime:p.runtime,meta:t.meta})).ok)return lH(l,p,e,o);c+=1}if(u&&c>0){let e=i.get(r);!function(e,t,r){let a=[];if(r){let e=r.device.name.replace(/"/g,'\\"'),t=r.device.kind?` kind=${r.device.kind}`:"",i=r.device.target?` target=${r.device.target}`:"";a.push(`context platform=${r.device.platform}${i} device="${e}"${t} theme=unknown`)}for(let e of t)a.push(function(e){let t=[e.command];if("snapshot"===e.command)return e.flags?.snapshotInteractiveOnly&&t.push("-i"),e.flags?.snapshotCompact&&t.push("-c"),"number"==typeof e.flags?.snapshotDepth&&t.push("-d",String(e.flags.snapshotDepth)),e.flags?.snapshotScope&&t.push("-s",tE(e.flags.snapshotScope)),e.flags?.snapshotRaw&&t.push("--raw"),t.join(" ");if("open"===e.command)return tR(t,e),t.join(" ");if("runtime"===e.command){for(let r of e.positionals??[])t.push(tk(r));return tO(t,e.flags),t.join(" ")}for(let r of e.positionals??[])t.push(tE(r));return tL(t,e),t.join(" ")}(e));let i=`${a.join("\n")}
36
- `,n=`${e}.tmp-${process.pid}-${Date.now()}`;R.writeFileSync(n,i),R.renameSync(n,e)}(o,d,e)}return{ok:!0,data:{replayed:d.length,healed:c,session:r}}}catch(t){let e=f(t);return{ok:!1,error:{code:e.code,message:e.message}}}}if("logs"===x){let e=i.get(r);if(!e)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"logs requires an active session"}};if(!oM("logs",e.device))return{ok:!1,error:y(new w("UNSUPPORTED_OPERATION","logs is not supported on this device"))};let a=(t.positionals?.[0]??"path").toLowerCase(),n=!!t.flags?.restart;if(!lC.includes(a))return{ok:!1,error:{code:"INVALID_ARGS",message:lR}};if(n&&"clear"!==a)return{ok:!1,error:{code:"INVALID_ARGS",message:"logs --restart is only supported with logs clear"}};if("path"===a){let t=i.resolveAppLogPath(r),a=function(e){if(!R.existsSync(e))return{exists:!1,sizeBytes:0};let t=R.statSync(e);return{exists:!0,sizeBytes:t.size,modifiedAt:t.mtime.toISOString()}}(t),n=lG(e);return{ok:!0,data:{path:t,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:n,sizeBytes:a.sizeBytes,modifiedAt:a.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>'}}}if("doctor"===a){let t=i.resolveAppLogPath(r),a=await tX(e.device,e.appBundleId);return{ok:!0,data:{path:t,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:a.checks,notes:a.notes}}}if("mark"===a){let e,a=t.positionals?.slice(1).join(" ")??"",n=i.resolveAppLogPath(r);return tz(n),e=`[agent-device][mark][${new Date().toISOString()}] ${a.trim()||"marker"}
37
- `,R.appendFileSync(n,e,"utf8"),{ok:!0,data:{path:n,marked:!0}}}if("clear"===a){if(e.appLog&&!n)return{ok:!1,error:{code:"INVALID_ARGS",message:"logs clear requires logs to be stopped first; run logs stop"}};if(n&&!e.appBundleId)return{ok:!1,error:{code:"INVALID_ARGS",message:"logs clear --restart requires an app session; run open <app> first"}};let t=i.resolveAppLogPath(r);if(n){e.appLog&&await p.stop(e.appLog);let a=tZ(t),n=i.resolveAppLogPidPath(r);try{let o=await p.start(e.device,e.appBundleId,t,n),s={...e,appLog:{platform:e.device.platform,backend:o.backend,outPath:t,startedAt:o.startedAt,getState:o.getState,stop:o.stop,wait:o.wait}};return i.set(r,s),{ok:!0,data:{...a,restarted:!0}}}catch(a){let t=y(a);return i.set(r,{...e,appLog:void 0}),{ok:!1,error:t}}}return{ok:!0,data:tZ(t)}}if("start"===a){if(e.appLog)return{ok:!1,error:{code:"INVALID_ARGS",message:"app log already streaming; run logs stop first"}};if(!e.appBundleId)return{ok:!1,error:{code:"INVALID_ARGS",message:"logs start requires an app session; run open <app> first"}};let t=i.resolveAppLogPath(r),a=i.resolveAppLogPidPath(r);try{let n=await p.start(e.device,e.appBundleId,t,a),o={...e,appLog:{platform:e.device.platform,backend:n.backend,outPath:t,startedAt:n.startedAt,getState:n.getState,stop:n.stop,wait:n.wait}};return i.set(r,o),{ok:!0,data:{path:t,started:!0}}}catch(e){return{ok:!1,error:y(e)}}}if("stop"===a){if(!e.appLog)return{ok:!1,error:{code:"INVALID_ARGS",message:"no app log stream active"}};let t=e.appLog.outPath;return await p.stop(e.appLog),i.set(r,{...e,appLog:void 0}),{ok:!0,data:{path:t,stopped:!0}}}}if("network"===x){let e=i.get(r);if(!e)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"network requires an active session"}};if(!oM("network",e.device))return{ok:!1,error:y(new w("UNSUPPORTED_OPERATION","network is not supported on this device"))};let a=(t.positionals?.[0]??"dump").toLowerCase();if(!lP.includes(a))return{ok:!1,error:{code:"INVALID_ARGS",message:lT}};let n=t.positionals?.[1],o=n?Number.parseInt(n,10):25;if(!Number.isInteger(o)||o<1||o>200)return{ok:!1,error:{code:"INVALID_ARGS",message:"network dump limit must be an integer in range 1..200"}};let s=(t.positionals?.[2]??"summary").toLowerCase();if(!l$.includes(s))return{ok:!1,error:{code:"INVALID_ARGS",message:lF}};let l=function(e,t){let r=sh(t?.maxEntries,25,1,200),a=t?.include??"summary",i=sh(t?.maxPayloadChars,2048,64,16384),n=sh(t?.maxScanLines,4e3,100,2e4);if(!R.existsSync(e))return{path:e,exists:!1,scannedLines:0,matchedLines:0,entries:[],include:a,limits:{maxEntries:r,maxPayloadChars:i,maxScanLines:n}};let o=R.readFileSync(e,"utf8").split("\n"),s=Math.max(0,o.length-n),l=o.slice(s),d=[];for(let e=l.length-1;e>=0&&d.length<r;e-=1){let t=l[e]?.trim();if(!t)continue;let r=function(e,t,r,a){let i=function(e){let t=e.indexOf("{");if(t<0)return null;let r=e.lastIndexOf("}");if(r<=t)return null;let a=e.slice(t,r+1);try{let e=JSON.parse(a);return e&&"object"==typeof e?e:null}catch{return null}}(e),n=sc(i,["method","httpMethod"]),o=sc(i,["url","requestUrl"]),s=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}(i,["status","statusCode","responseCode"]),l=sl.exec(e),d=/\bmethod["'=: ]+([A-Z]+)\b/i.exec(e),u=(n??d?.[1]??l?.[1])?.toUpperCase(),c=sd.exec(e),p=o??c?.[0];if(!p)return null;let f={method:u,url:p,status:s??function(e){for(let t of su){let r=t.exec(e);if(!r)continue;let a=Number.parseInt(r[1]??"",10);if(Number.isInteger(a))return a}return null}(e)??void 0,timestamp:function(e){let t=/\b\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z)?\b/.exec(e);return t?.[0]}(e),raw:sm(e,a),line:t};if("headers"===r||"all"===r){let t=function(e,t){if(t){let e=t.headers??t.requestHeaders??t.responseHeaders;if(void 0!==e)return sf(e)}let r=/\bheaders?["'=: ]+(\{.*\})/i.exec(e);return r?.[1]?.trim()}(e,i);t&&(f.headers=sm(t,a))}if("body"===r||"all"===r){let t=sp(e,i,["requestBody","body","payload","request"]),r=sp(e,i,["responseBody","response"]);t&&(f.requestBody=sm(t,a)),r&&(f.responseBody=sm(r,a))}return f}(t,s+e+1,a,i);r&&d.push(r)}return{path:e,exists:!0,scannedLines:l.length,matchedLines:d.length,entries:d,include:a,limits:{maxEntries:r,maxPayloadChars:i,maxScanLines:n}}}(i.resolveAppLogPath(r),{maxEntries:o,include:s,maxPayloadChars:2048,maxScanLines:4e3}),d=lG(e),u=[];return e.appLog||u.push("Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests."),0===l.entries.length&&u.push("No HTTP(s) entries were found in recent session app logs."),{ok:!0,data:{...l,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:d,notes:u}}}return"batch"===x?await lk(t,r,n):"close"===x?await lS({req:t,sessionName:r,logPath:a,sessionStore:i,dispatch:D,stopIosRunner:L,clearRuntimeHints:I,settleSimulator:O,shutdownSimulator:v??i1,shutdownAndroidEmulator:b,appLogOps:{stop:p.stop}}):null}function lH(e,t,r,a){if(e.ok)return e;let i=r+1,n=function(e){let t;return t=(e.positionals??[]).map(e=>tE(e)),[e.command,...t].join(" ")}(t),o={...e.error.details??{},replayPath:a,step:i,action:t.command,positionals:t.positionals??[]};return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${i} (${n}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:o}}}function lW(e,t){let r={...t??{}},a=e??{};for(let e of lM)void 0===r[e]&&void 0!==a[e]&&(r[e]=a[e]);return r}async function lz(e){let{action:t,sessionName:r,logPath:a,sessionStore:i,dispatch:n}=e;if(!(tD(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let o=i.get(r);if(!o)return null;let s=tD(t.command)||"fill"===t.command,l=tD(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",d=await lJ(o,t,a,s,n,i);for(let e of 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),tD(e.command)){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&t.push(e.positionals.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}=o2(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=sG(e.positionals??[]);r&&t.push(r)}let a="string"==typeof e.result?.refLabel?e.result.refLabel.trim():"";if(a.length>0){let r=JSON.stringify(a);"fill"===e.command?(t.push(`id=${r} editable=true`),t.push(`label=${r} editable=true`),t.push(`text=${r} editable=true`),t.push(`value=${r} editable=true`)):(t.push(`id=${r}`),t.push(`label=${r}`),t.push(`text=${r}`),t.push(`value=${r}`))}return tb(t).filter(e=>e.trim().length>0)}(t)){let r=o0(e);if(!r)continue;let a=st(d.nodes,r,{platform:o.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!a)continue;let i=sn(a.node,o.device.platform,{action:tD(t.command)?"click":"fill"===t.command?"fill":"get"}).join(" || ");if(tD(t.command))return{...t,positionals:[i]};if("fill"===t.command){let e=ty(t);if(!e)continue;return{...t,positionals:[i,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,i]}}if("is"===t.command){let{predicate:e,split:r}=o2(t.positionals);if(!e)continue;let a=r?.rest.join(" ").trim()??"",n=[e,i];return"text"===e&&a.length>0&&n.push(a),{...t,positionals:n}}if("wait"===t.command){let{selectorTimeout:e}=sG(t.positionals??[]),r=[i];return e&&r.push(e),{...t,positionals:r}}}let u=function(e,t,r){if("get"!==e.command||e.positionals?.[0]!=="text")return null;let a=e.positionals?.[1];if(!a)return null;let i=o0(a);if(!i)return null;let n=new Set,o=!1;for(let e of i.selectors)for(let t of e.terms)"role"===t.key&&"string"==typeof t.value&&n.add(oz(t.value)),("text"===t.key||"label"===t.key||"value"===t.key)&&"string"==typeof t.value&&/^\d+$/.test(t.value.trim())&&(o=!0);if(!o)return null;let s=t.nodes.filter(e=>{let t=oK(e).trim();return!!/^\d+$/.test(t)&&(0===n.size||n.has(oz(e.type??"")))});if(0===s.length||1!==tb(s.map(e=>oK(e).trim())).length)return null;let l=s[0];if(!l)return null;let d=sn(l,r.device.platform,{action:"get"});return 0===d.length?null:{...e,positionals:["text",d.join(" || ")]}}(t,d,o);return u||null}async function lJ(e,t,r,a,i,n){let o=await i(e.device,"snapshot",[],t.flags?.out,{...oC(r,{...t.flags??{},snapshotInteractiveOnly:a,snapshotCompact:a},e.appBundleId,e.trace?.outPath)}),s=o?.nodes??[],l={nodes:oU(t.flags?.snapshotRaw?s:oW(s)),truncated:o?.truncated,createdAt:Date.now(),backend:o?.backend};return e.snapshot=l,n.set(e.name,e),l}function lK(e,t){let r=j(e.type??"Element"),a=W(e,r),i=!1===e.enabled?"disabled":"enabled",n=!0===e.selected?"selected":"unselected",o=!0===e.hittable?"hittable":"not-hittable";return[String(t??e.depth??0),r,a,i,n,o].join("|")}function lX(e,t){return t.flatten?e.map(e=>({text:J(e,0,!1),comparable:lK(e,0)})):G(e).map(e=>({text:e.text,comparable:lK(e.node,e.depth)}))}function lZ(e,t){return e.get(t)??0}async function lY(e){let{dispatchSnapshotCommand:t,device:r,session:a,req:i,logPath:n,snapshotScope:o}=e;return{snapshot:lQ(await t(r,"snapshot",[],i.flags?.out,{...oC(n,{...i.flags,snapshotScope:o},a?.appBundleId,a?.trace?.outPath)}),i.flags?.snapshotRaw)}}function lQ(e,t){let r=e?.nodes??[];return{nodes:oU(t?r:oW(r)),truncated:e?.truncated,createdAt:Date.now(),backend:e?.backend}}function l0(e,t){if(!e||!e.trim().startsWith("@"))return{ok:!0,scope:e};if(!t?.snapshot)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:"Ref scope requires an existing snapshot in session."}}};let r=oV(e.trim());if(!r)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:`Invalid ref scope: ${e}`}}};let a=oG(t.snapshot.nodes,r),i=a?oq(a,t.snapshot.nodes):void 0;return i?{ok:!0,scope:i}:{ok:!1,response:{ok:!1,error:{code:"COMMAND_FAILED",message:`Ref ${e} not found or has no label`}}}}async function l1(e,t,r){let a=e.get(t),i=a?.device??await ok(r??{});return a||await oP(i),{session:a,device:i}}async function l2(e,t,r){let a=!e&&"ios"===t.platform;try{return await r()}finally{a&&await tp(t.id)}}function l3(e,t,r,a){t&&e.recordAction(t,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:a})}function l4(e){let{session:t,sessionName:r,device:a,snapshot:i,appBundleId:n}=e;return t?{...t,snapshot:i}:{name:r,device:a,createdAt:Date.now(),appBundleId:n,snapshot:i,actions:[]}}function l8(e){if(!e)return null;let t=Number(e);return Number.isFinite(t)?t:null}async function l6(e){let{parsed:t,req:r,sessionName:a,logPath:i,sessionStore:n,session:o,device:s}=e,l=e.dispatchSnapshotCommand??oL,d=e.runnerCommand??tA;if("sleep"===t.kind)return await new Promise(e=>setTimeout(e,t.durationMs)),l3(n,o,r,{waitedMs:t.durationMs}),{ok:!0,data:{waitedMs:t.durationMs}};if(!oM("wait",s))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"wait is not supported on this device"}};if("selector"===t.kind)return await l5({dispatchSnapshotCommand:l,device:s,logPath:i,parsed:t,req:r,session:o,sessionName:a,sessionStore:n});let u=function(e,t){if("ref"===e.kind){if(!t?.snapshot)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:"Ref wait requires an existing snapshot in session."}}};let r=oV(e.rawRef);if(!r)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:`Invalid ref: ${e.rawRef}`}}};let a=oG(t.snapshot.nodes,r),i=a?oq(a,t.snapshot.nodes):void 0;return i?{ok:!0,text:i,timeoutMs:e.timeoutMs}:{ok:!1,response:{ok:!1,error:{code:"COMMAND_FAILED",message:`Ref ${e.rawRef} not found or has no label`}}}}return e.text?{ok:!0,text:e.text,timeoutMs:e.timeoutMs}:{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:"wait requires text"}}}}(t,o);return u.ok?await l9({device:s,logPath:i,req:r,runnerCommand:d,session:o,sessionStore:n,text:u.text,timeoutMs:u.timeoutMs}):u.response}async function l5(e){let{dispatchSnapshotCommand:t,device:r,logPath:a,parsed:i,req:n,session:o,sessionName:s,sessionStore:l}=e,d=i.timeoutMs??1e4,u=Date.now();for(;Date.now()-u<d;){let e=lQ(await t(r,"snapshot",[],n.flags?.out,{...oC(a,{...n.flags,snapshotInteractiveOnly:!1,snapshotCompact:!1},o?.appBundleId,o?.trace?.outPath)}),n.flags?.snapshotRaw),d=e.nodes;o&&(o.snapshot=e,l.set(s,o));let c=sr(d,i.selector,{platform:r.platform});if(c)return l3(l,o,n,{selector:c.selector.raw,waitedMs:Date.now()-u}),{ok:!0,data:{selector:c.selector.raw,waitedMs:Date.now()-u}};await new Promise(e=>setTimeout(e,300))}return{ok:!1,error:{code:"COMMAND_FAILED",message:`wait timed out for selector: ${i.selectorExpression}`}}}async function l9(e){let{device:t,logPath:r,req:a,runnerCommand:i,session:n,sessionStore:o,text:s,timeoutMs:l}=e,d=l??1e4,u=Date.now();for(;Date.now()-u<d;){if(eK(t.platform)){let e=await i(t,{command:"findText",text:s,appBundleId:n?.appBundleId},{verbose:a.flags?.verbose,logPath:r,traceLogPath:n?.trace?.outPath,requestId:a.meta?.requestId});if(e?.found)return l3(o,n,a,{text:s,waitedMs:Date.now()-u}),{ok:!0,data:{text:s,waitedMs:Date.now()-u}}}else if("android"===t.platform&&oj(oU((await a0(t,{scope:s})).nodes??[]),s))return l3(o,n,a,{text:s,waitedMs:Date.now()-u}),{ok:!0,data:{text:s,waitedMs:Date.now()-u}};await new Promise(e=>setTimeout(e,300))}return{ok:!1,error:{code:"COMMAND_FAILED",message:`wait timed out for text: ${s}`}}}async function l7(e){let{req:t,logPath:r,sessionStore:a,session:i,device:n}=e,o=e.runnerCommand??tA,s=(t.positionals?.[0]??"get").toLowerCase();if(!oM("alert",n))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"alert is only supported on iOS simulators"}};if("wait"===s){let e=l8(t.positionals?.[1])??1e4,s=Date.now();for(;Date.now()-s<e;){try{let e=await o(n,{command:"alert",action:"get",appBundleId:i?.appBundleId},{verbose:t.flags?.verbose,logPath:r,traceLogPath:i?.trace?.outPath,requestId:t.meta?.requestId});return l3(a,i,t,e),{ok:!0,data:e}}catch{}await new Promise(e=>setTimeout(e,300))}return{ok:!1,error:{code:"COMMAND_FAILED",message:"alert wait timed out"}}}let l="accept"===s||"dismiss"===s?s:"get",d={verbose:t.flags?.verbose,logPath:r,traceLogPath:i?.trace?.outPath,requestId:t.meta?.requestId};if("accept"===l||"dismiss"===l){let e,r=Date.now();for(;Date.now()-r<2e3;){try{let e=await o(n,{command:"alert",action:l,appBundleId:i?.appBundleId},d);return l3(a,i,t,e),{ok:!0,data:e}}catch(r){e=r;let t=String(r?.message??"").toLowerCase();if(!t.includes("alert not found")&&!t.includes("no alert"))break}await new Promise(e=>setTimeout(e,300))}throw e}let u=await o(n,{command:"alert",action:l,appBundleId:i?.appBundleId},d);return l3(a,i,t,u),{ok:!0,data:u}}async function de(e){let{req:t,logPath:r,sessionStore:a,session:i,device:n,parsed:o}=e,{setting:s,state:l,permissionTarget:d}=o;if(!oM("settings",n))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"settings is not supported on this device"}};let u=i?.appBundleId,c="permission"===s?[s,l,d??"",t.positionals?.[3]??"",u??""]:[s,l,u??""],p=await oL(n,"settings",c,t.flags?.out,{...oC(r,t.flags,u,i?.trace?.outPath)});return l3(a,i,t,p??{setting:s,state:l}),{ok:!0,data:p??{setting:s,state:l}}}async function dt(e){let{req:t,sessionName:r,logPath:a,sessionStore:i}=e,n=e.dispatchSnapshotCommand??oL,o=e.runnerCommand??tA,s=e.sessionlessRunnerCleanup??l2,l=t.command;if("snapshot"===l){let{session:e,device:o}=await l1(i,r,t.flags);if(!oM("snapshot",o))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"snapshot is not supported on this device"}};let l=l0(t.flags?.snapshotScope,e);return l.ok?await s(e,o,async()=>{let s=await lY({dispatchSnapshotCommand:n,device:o,session:e,req:t,logPath:a,snapshotScope:l.scope}),d=l4({session:e,sessionName:r,device:o,snapshot:s.snapshot,appBundleId:e?.appBundleId});return l3(i,d,t,{nodes:s.snapshot.nodes.length,truncated:s.snapshot.truncated??!1}),i.set(r,d),{ok:!0,data:{nodes:s.snapshot.nodes,truncated:s.snapshot.truncated??!1,appName:d.appBundleId?d.appName??d.appBundleId:void 0,appBundleId:d.appBundleId}}}):l.response}if("diff"===l){if(t.positionals?.[0]!=="snapshot")return{ok:!1,error:{code:"INVALID_ARGS",message:"diff currently supports only: diff snapshot"}};let{session:e,device:o}=await l1(i,r,t.flags);if(!oM("diff",o))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"diff is not supported on this device"}};let l=l0(t.flags?.snapshotScope,e);if(!l.ok)return l.response;let d=t.flags?.snapshotInteractiveOnly===!0;return await s(e,o,async()=>{let s=(await lY({dispatchSnapshotCommand:n,device:o,session:e,req:t,logPath:a,snapshotScope:l.scope})).snapshot;if(!e?.snapshot){let a=function(e,t={}){return lX(e,t).length}(s.nodes,{flatten:d}),n=l4({session:e,sessionName:r,device:o,snapshot:s,appBundleId:e?.appBundleId});return l3(i,n,t,{mode:"snapshot",baselineInitialized:!0,summary:{additions:0,removals:0,unchanged:a}}),i.set(r,n),{ok:!0,data:{mode:"snapshot",baselineInitialized:!0,summary:{additions:0,removals:0,unchanged:a},lines:[]}}}let u=function(e,t,r={}){let a=function(e,t){let r=e.length,a=t.length,i=r+a,n=new Map,o=[];n.set(1,0);for(let s=0;s<=i;s+=1){o.push(new Map(n));for(let i=-s;i<=s;i+=2){let l=i===-s||i!==s&&lZ(n,i-1)<lZ(n,i+1)?lZ(n,i+1):lZ(n,i-1)+1,d=l-i;for(;l<r&&d<a&&e[l].comparable===t[d].comparable;)l+=1,d+=1;if(n.set(i,l),l>=r&&d>=a)return function(e,t,r,a,i){let n=[],o=a,s=i;for(let a=e.length-1;a>=0;a-=1){let i=e[a],l=o-s,d=l===-a||l!==a&&lZ(i,l-1)<lZ(i,l+1)?l+1:l-1,u=lZ(i,d),c=u-d;for(;o>u&&s>c;)n.push({kind:"unchanged",text:r[s-1].text}),o-=1,s-=1;if(0===a)break;o===u?(n.push({kind:"added",text:r[c].text}),s=c):(n.push({kind:"removed",text:t[u].text}),o=u)}return n.reverse(),n}(o,e,t,r,a)}}return[]}(lX(e,r),lX(t,r)),i={additions:0,removals:0,unchanged:0};for(let e of a)"added"===e.kind&&(i.additions+=1),"removed"===e.kind&&(i.removals+=1),"unchanged"===e.kind&&(i.unchanged+=1);return{summary:i,lines:a}}(e.snapshot.nodes,s.nodes,{flatten:d}),c={...e,snapshot:s};return l3(i,c,t,{mode:"snapshot",baselineInitialized:!1,summary:u.summary}),i.set(r,c),{ok:!0,data:{mode:"snapshot",baselineInitialized:!1,summary:u.summary,lines:u.lines}}})}if("wait"===l){let{session:e,device:l}=await l1(i,r,t.flags),d=function(e){if(0===e.length)return null;let t=l8(e[0]);if(null!==t)return{kind:"sleep",durationMs:t};if("text"===e[0]){let t=l8(e[e.length-1]);return{kind:"text",text:(null!==t?e.slice(1,-1).join(" "):e.slice(1).join(" ")).trim(),timeoutMs:t}}if(e[0].startsWith("@")){let t=l8(e[e.length-1]);return{kind:"ref",rawRef:e[0],timeoutMs:t}}let r=l8(e[e.length-1]),a=o1(null!==r?e.slice(0,-1):e.slice());if(a&&0===a.rest.length){let e=o0(a.selectorExpression);if(e)return{kind:"selector",selector:e,selectorExpression:a.selectorExpression,timeoutMs:r}}return{kind:"text",text:(null!==r?e.slice(0,-1).join(" "):e.join(" ")).trim(),timeoutMs:r}}(t.positionals??[]);if(!d)return{ok:!1,error:{code:"INVALID_ARGS",message:"wait requires a duration or text"}};let u=()=>l6({parsed:d,req:t,sessionName:r,logPath:a,sessionStore:i,session:e,device:l,dispatchSnapshotCommand:n,runnerCommand:o});return"sleep"===d.kind?await u():await s(e,l,u)}if("alert"===l){let{session:e,device:n}=await l1(i,r,t.flags);return await s(e,n,async()=>await l7({req:t,logPath:a,sessionStore:i,session:e,device:n,runnerCommand:o}))}if("settings"===l){let e,n,o,l=(e=t.positionals?.[0]?.toLowerCase(),n=t.positionals?.[1]?.toLowerCase(),o=t.positionals?.[2]?.toLowerCase(),e&&n&&("permission"!==e||o)?{ok:!0,parsed:{setting:e,state:n,permissionTarget:o}}:{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:H}}});if(!l.ok)return l.response;let{session:d,device:u}=await l1(i,r,t.flags);return await s(d,u,async()=>await de({req:t,logPath:a,sessionStore:i,session:d,device:u,parsed:l.parsed}))}return null}function dr(e,t,r,a={}){let i=di(r);if(!i)return{matches:[],score:0};let n=0,o=[];for(let r of e){if(a.requireRect&&!r.rect)continue;let e=function(e,t,r){switch(t){case"role":return function(e,t){let r=function(e){let t=e.trim();return t?t=(t.split(".").pop()??t).replace(/XCUIElementType/gi,"").toLowerCase():""}(e??"");return r?r===t?2:+!!r.includes(t):0}(e.type,r);case"label":return da(e.label,r);case"value":return da(e.value,r);case"id":return da(e.identifier,r);default:return Math.max(da(e.label,r),da(e.value,r),da(e.identifier,r))}}(r,t,i);if(!(e<=0)){if(e>n){n=e,o.length=0,o.push(r);continue}e===n&&o.push(r)}}return{matches:o,score:n}}function da(e,t){let r=di(e??"");return r?r===t?2:+!!r.includes(t):0}function di(e){return e.trim().toLowerCase().replace(/\s+/g," ")}async function dn(e){let{req:t,sessionName:r,logPath:a,sessionStore:i,invoke:n}=e,o=e.dispatch??oL,s=t.command;if("find"!==s)return null;let l=t.positionals??[];if(0===l.length)return{ok:!1,error:{code:"INVALID_ARGS",message:"find requires a locator or text"}};let{locator:d,query:u,action:c,value:p,timeoutMs:f}=function(e){let t="any",r=0;["text","label","value","role","id"].includes(e[0])&&(t=e[0],r=1);let a=e[r]??"",i=e.slice(r+1);if(0===i.length)return{locator:t,query:a,action:"click"};let n=i[0].toLowerCase();if("get"===n){let e=i[1]?.toLowerCase();if("text"===e)return{locator:t,query:a,action:"get_text"};if("attrs"===e)return{locator:t,query:a,action:"get_attrs"};throw new w("INVALID_ARGS","find get only supports text or attrs")}if("wait"===n)return{locator:t,query:a,action:"wait",timeoutMs:l8(i[1])??void 0};if("exists"===n)return{locator:t,query:a,action:"exists"};if("click"===n)return{locator:t,query:a,action:"click"};if("focus"===n)return{locator:t,query:a,action:"focus"};if("fill"===n)return{locator:t,query:a,action:"fill",value:i.slice(1).join(" ")};if("type"===n)return{locator:t,query:a,action:"type",value:i.slice(1).join(" ")};throw new w("INVALID_ARGS",`Unsupported find action: ${i[0]}`)}(l);if(!u)return{ok:!1,error:{code:"INVALID_ARGS",message:"find requires a value"}};let m=i.get(r);if(!m&&"exists"!==c&&"wait"!==c&&"get_text"!==c&&"get_attrs"!==c)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};let h=m?.device??await ok(t.flags??{});m||await oP(h);let g=m?.appBundleId,I="role"!==d?u:void 0,A="click"===c||"focus"===c||"fill"===c||"type"===c,v=0,y=null,b=async()=>{let e=Date.now();if(y&&e-v<750)return{nodes:y};let n=await o(h,"snapshot",[],t.flags?.out,{...oC(a,{...t.flags,snapshotScope:I,snapshotInteractiveOnly:A,snapshotCompact:A},g,m?.trace?.outPath)}),s=n?.nodes??[],l=oU(t.flags?.snapshotRaw?s:oW(s));return v=e,y=l,m&&(m.snapshot={nodes:l,truncated:n?.truncated,createdAt:Date.now(),backend:n?.backend},i.set(r,m)),{nodes:l,truncated:n?.truncated,backend:n?.backend}};if("wait"===c){let e=f??1e4,r=Date.now();for(;Date.now()-r<e;){let{nodes:e}=await b();if(dr(e,d,u,{requireRect:!1}).matches[0])return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{found:!0,waitedMs:Date.now()-r}}),{ok:!0,data:{found:!0,waitedMs:Date.now()-r}};await new Promise(e=>setTimeout(e,300))}return{ok:!1,error:{code:"COMMAND_FAILED",message:"find wait timed out"}}}let{nodes:S}=await b(),N=dr(S,d,u,{requireRect:A});if(A&&N.matches.length>1){let e=N.matches.slice(0,8).map(e=>{let t=oK(e)||e.label||e.identifier||e.type||"";return`@${e.ref}${t?`(${t})`:""}`});return{ok:!1,error:{code:"AMBIGUOUS_MATCH",message:`find matched ${N.matches.length} elements for ${d} "${u}". Use a more specific locator or selector.`,details:{locator:d,query:u,matches:N.matches.length,candidates:e}}}}let _=N.matches[0]??null;if(!_)return{ok:!1,error:{code:"COMMAND_FAILED",message:"find did not match any element"}};let D="click"===c||"focus"===c||"fill"===c||"type"===c?function(e,t){if(t.hittable)return t;let r=t,a=new Set;for(;void 0!==r.parentIndex&&!a.has(r.ref);){a.add(r.ref);let t=e[r.parentIndex];if(!t)break;if(t.hittable)return t;r=t}return null}(S,_)??_:_,E=`@${D.ref}`,k={...t.flags??{},noRecord:!0};if("exists"===c)return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{found:!0}}),{ok:!0,data:{found:!0}};if("get_text"===c){let e=oK(_);return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:E,action:"get text",text:e}}),{ok:!0,data:{ref:E,text:e,node:_}}}if("get_attrs"===c)return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:E,action:"get attrs"}}),{ok:!0,data:{ref:E,node:_}};if("click"===c){let e=await n({token:t.token,session:r,command:"click",positionals:[E],flags:k});if(!e.ok)return e;let a=D.rect?oB(D.rect):null,o={ref:E,locator:d,query:u};return a&&(o.x=a.x,o.y=a.y),m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:E,action:"click",locator:d,query:u}}),{ok:!0,data:o}}if("fill"===c){if(!p)return{ok:!1,error:{code:"INVALID_ARGS",message:"find fill requires text"}};let e=await n({token:t.token,session:r,command:"fill",positionals:[E,p],flags:k});return e.ok&&m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:E,action:"fill"}}),e}if("focus"===c){let e=_.rect?oB(_.rect):null;if(!e)return{ok:!1,error:{code:"COMMAND_FAILED",message:"matched element has no bounds"}};let r=await o(h,"focus",[String(e.x),String(e.y)],t.flags?.out,{...oC(a,t.flags,m?.appBundleId,m?.trace?.outPath)});return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:E,action:"focus"}}),{ok:!0,data:r??{ref:E}}}if("type"===c){if(!p)return{ok:!1,error:{code:"INVALID_ARGS",message:"find type requires text"}};let e=_.rect?oB(_.rect):null;if(!e)return{ok:!1,error:{code:"COMMAND_FAILED",message:"matched element has no bounds"}};await o(h,"focus",[String(e.x),String(e.y)],t.flags?.out,{...oC(a,t.flags,m?.appBundleId,m?.trace?.outPath)});let r=await o(h,"type",[p],t.flags?.out,{...oC(a,t.flags,m?.appBundleId,m?.trace?.outPath)});return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:E,action:"type"}}),{ok:!0,data:r??{ref:E}}}return null}function ds(e){return e instanceof Error?e.message:String(e)}function dl(e){let t=e.appBundleId?.trim();return t&&t.length>0?t:void 0}function dd(e,t,r){return{verbose:e.flags?.verbose,logPath:t,traceLogPath:r.trace?.outPath}}async function du(e){let{deps:t,device:r,sessionStore:a,session:i,req:n,logPath:o,fps:s,appBundleId:l,runnerOutPath:d}=e,u=dd(n,o,i),c=async()=>{await t.runIosRunnerCommand(r,{command:"recordStart",outPath:d,fps:s,appBundleId:l},u)};try{await c()}catch(e){if(!ds(e).toLowerCase().includes("recording already in progress"))return{ok:!1,error:{code:"COMMAND_FAILED",message:`failed to start recording: ${ds(e)}`}};{var p,f;L({level:"warn",phase:"record_start_runner_desynced",data:{platform:r.platform,kind:r.kind,deviceId:r.id,session:i.name,error:ds(e)}});let n=(p=r.id,f=i.name,a.toArray().find(e=>e.name!==f&&e.device.id===p&&(e.recording?.platform==="ios-device-runner"||e.recording?.platform==="macos-runner")));if(n)return{ok:!1,error:{code:"COMMAND_FAILED",message:`failed to start recording: recording already in progress in session '${n.name}'`}};try{await t.runIosRunnerCommand(r,{command:"recordStop",appBundleId:l},u)}catch{}try{await c()}catch(e){return{ok:!1,error:{code:"COMMAND_FAILED",message:`failed to start recording: ${ds(e)}`}}}}}return{recording:e.recording}}async function dc(e){let{req:t,sessionName:r,sessionStore:a,logPath:n}=e,o=e.deps??{runCmd:c,runCmdBackground:d,runIosRunnerCommand:tA},s=t.command;if("record"===s){let e=(t.positionals?.[0]??"").toLowerCase();if(!["start","stop"].includes(e))return{ok:!1,error:{code:"INVALID_ARGS",message:"record requires start|stop"}};let l=a.get(r),d=l?.device??await ok(t.flags??{});l||await oP(d);let u=l??{name:r,device:d,createdAt:Date.now(),actions:[]};if("start"===e){if(u.recording)return{ok:!1,error:{code:"INVALID_ARGS",message:"recording already in progress"}};let e=t.flags?.fps;if(void 0!==e&&(!Number.isInteger(e)||e<1||e>120))return{ok:!1,error:{code:"INVALID_ARGS",message:"fps must be an integer between 1 and 120"}};let l=t.positionals?.[1]??`./recording-${Date.now()}.mp4`;if(!oM("record",d))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"record is not supported on this device"}};let c="ios"===d.platform&&"device"===d.kind||"macos"===d.platform?dl(u):void 0;if(!c&&("ios"===d.platform&&"device"===d.kind||"macos"===d.platform))return{ok:!1,error:{code:"INVALID_ARGS",message:"macos"===d.platform?"record on macOS requires an active app session; run open <app> first":"record on physical iOS devices requires an active app session; run open <app> first"}};let p=tP.expandHome(l,t.meta?.cwd),f=t.meta?.clientArtifactPaths?.outPath;if(R.mkdirSync(i.dirname(p),{recursive:!0}),"ios"===d.platform&&"device"===d.kind){let r=`agent-device-recording-${Date.now()}.mp4`,i=`tmp/${r}`,s=await du({deps:o,device:d,sessionStore:a,session:u,req:t,logPath:n,fps:e,appBundleId:c,runnerOutPath:r,recording:{platform:"ios-device-runner",outPath:p,clientOutPath:f,remotePath:i}});if("ok"in s)return s;u.recording=s.recording}else if("macos"===d.platform){let r=await du({deps:o,device:d,sessionStore:a,session:u,req:t,logPath:n,fps:e,appBundleId:c,runnerOutPath:p,recording:{platform:"macos-runner",outPath:p,clientOutPath:f}});if("ok"in r)return r;u.recording=r.recording}else if("ios"===d.platform){let{child:e,wait:t}=o.runCmdBackground("xcrun",ex(d,["io",d.id,"recordVideo",p]),{allowFailure:!0});u.recording={platform:"ios",outPath:p,clientOutPath:f,child:e,wait:t}}else{let e=`/sdcard/agent-device-recording-${Date.now()}.mp4`,{child:t,wait:r}=o.runCmdBackground("adb",["-s",d.id,"shell","screenrecord",e],{allowFailure:!0});u.recording={platform:"android",outPath:p,clientOutPath:f,remotePath:e,child:t,wait:r}}return a.set(r,u),a.recordAction(u,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{action:"start"}}),{ok:!0,data:{recording:"started",outPath:f??l}}}if(!u.recording)return{ok:!1,error:{code:"INVALID_ARGS",message:"no active recording"}};let c=u.recording;if("ios-device-runner"===c.platform||"macos-runner"===c.platform){let e=dl(u);try{await o.runIosRunnerCommand(d,{command:"recordStop",appBundleId:e},dd(t,n,u))}catch(e){L({level:"warn",phase:"record_stop_runner_failed",data:{platform:d.platform,kind:d.kind,deviceId:d.id,session:u.name,error:ds(e)}})}if(u.recording=void 0,"ios-device-runner"===c.platform){let e={stdout:"",stderr:"",exitCode:1};for(let t of e5)if(0===(e=await o.runCmd("xcrun",["devicectl","device","copy","from","--device",d.id,"--source",c.remotePath,"--destination",c.outPath,"--domain-type","appDataContainer","--domain-identifier",t],{allowFailure:!0})).exitCode)break;if(0!==e.exitCode){let t=e.stderr.trim()||e.stdout.trim()||`devicectl exited with code ${e.exitCode}`;return{ok:!1,error:{code:"COMMAND_FAILED",message:`failed to copy recording from device: ${t}`}}}}}else if("child"in c){c.child.kill("SIGINT");try{await c.wait}catch{}if("android"===c.platform&&c.remotePath)try{await o.runCmd("adb",["-s",d.id,"pull",c.remotePath,c.outPath],{allowFailure:!0}),await o.runCmd("adb",["-s",d.id,"shell","rm","-f",c.remotePath],{allowFailure:!0})}catch{}u.recording=void 0}a.recordAction(u,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{action:"stop",outPath:c.outPath}});let p=[{field:"outPath",path:c.outPath,localPath:c.clientOutPath,fileName:i.basename(c.clientOutPath??c.outPath)}];return{ok:!0,data:{recording:"stopped",outPath:c.outPath,artifacts:p}}}if("trace"===s){let e=(t.positionals?.[0]??"").toLowerCase();if(!["start","stop"].includes(e))return{ok:!1,error:{code:"INVALID_ARGS",message:"trace requires start|stop"}};let n=a.get(r);if(!n)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session"}};if("start"===e){if(n.trace)return{ok:!1,error:{code:"INVALID_ARGS",message:"trace already in progress"}};let e=t.positionals?.[1]??a.defaultTracePath(n),r=tP.expandHome(e);return R.mkdirSync(i.dirname(r),{recursive:!0}),R.appendFileSync(r,""),n.trace={outPath:r,startedAt:Date.now()},a.recordAction(n,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{action:"start",outPath:r}}),{ok:!0,data:{trace:"started",outPath:r}}}if(!n.trace)return{ok:!1,error:{code:"INVALID_ARGS",message:"no active trace"}};let o=n.trace.outPath;if(t.positionals?.[1]){let e=tP.expandHome(t.positionals[1]);R.mkdirSync(i.dirname(e),{recursive:!0}),R.existsSync(o)?R.renameSync(o,e):R.appendFileSync(e,""),o=e}return n.trace=void 0,a.recordAction(n,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{action:"stop",outPath:o}}),{ok:!0,data:{trace:"stopped",outPath:o}}}return null}let dp=[["snapshotDepth","--depth"],["snapshotScope","--scope"],["snapshotRaw","--raw"]];function df(e,t){let r=function(e){if(!e)return[];let t=[];for(let[r,a]of dp)void 0!==e[r]&&t.push(a);return t}(t);return 0===r.length?null:{ok:!1,error:{code:"INVALID_ARGS",message:`${e} @ref does not support ${r.join(", ")}.`}}}function dm(e){let{session:t,refInput:r,fallbackLabel:a,requireRect:i,invalidRefMessage:n,notFoundMessage:o}=e;if(!t.snapshot)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:"No snapshot in session. Run snapshot first."}}};let s=oV(r);if(!s)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:n}}};let l=oG(t.snapshot.nodes,s);return((!l||i&&!l.rect)&&a.length>0&&(l=oj(t.snapshot.nodes,a)),l&&(!i||l.rect))?{ok:!0,target:{ref:s,node:l,snapshotNodes:t.snapshot.nodes}}:{ok:!1,response:{ok:!1,error:{code:"COMMAND_FAILED",message:o}}}}function dh(e){let t=function(e){if(!e)return null;let t=Number(e.x),r=Number(e.y),a=Number(e.width),i=Number(e.height);return Number.isFinite(t)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(i)&&!(a<0)&&!(i<0)?{x:t,y:r,width:a,height:i}:null}(e);if(!t)return null;let r=oB(t);return Number.isFinite(r.x)&&Number.isFinite(r.y)?r:null}async function dw(e,t,r,a,i,n=oL){let o=await n(e.device,"snapshot",[],t?.out,{...a({...t??{},snapshotInteractiveOnly:i.interactiveOnly,snapshotCompact:i.interactiveOnly},e.appBundleId,e.trace?.outPath)}),s=o?.nodes??[];return e.snapshot={nodes:oU(t?.snapshotRaw?s:oW(s)),truncated:o?.truncated,createdAt:Date.now(),backend:o?.backend},r.set(e.name,e),e.snapshot}async function dg(e){let{command:t,selectorExpression:r,session:a,flags:i,sessionStore:n,contextFromFlags:o,interactiveOnly:s,requireRect:l,requireUnique:d,disambiguateAmbiguous:u,dispatch:c}=e,p=oQ(r),f=await dw(a,i,n,o,{interactiveOnly:s},c),m=await E("selector_resolve",()=>st(f.nodes,p,{platform:a.device.platform,requireRect:l,requireUnique:d,disambiguateAmbiguous:u}),{command:t});return m&&(!l||m.node.rect)?{ok:!0,chain:p,snapshot:f,resolved:m}:{ok:!1,response:{ok:!1,error:{code:"COMMAND_FAILED",message:sa(p,m?.diagnostics??[],{unique:d})}}}}async function dI(e){let{req:t,sessionName:r,sessionStore:a,contextFromFlags:i,dispatch:n}=e,o=a.get(r);if(o&&!oM("fill",o.device))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"fill is not supported on this device"}};if(t.positionals?.[0]?.startsWith("@")){if(!o)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};let e=df("fill",t.flags);if(e)return e;let r=t.positionals.length>=3?t.positionals[1]:"",s=t.positionals.length>=3?t.positionals.slice(2).join(" "):t.positionals.slice(1).join(" ");if(!s)return{ok:!1,error:{code:"INVALID_ARGS",message:"fill requires text after ref"}};let l=dm({session:o,refInput:t.positionals[0],fallbackLabel:r,requireRect:!0,invalidRefMessage:"fill requires a ref like @e2",notFoundMessage:`Ref ${t.positionals[0]} not found or has no bounds`});if(!l.ok)return l.response;let{ref:d,node:u,snapshotNodes:c}=l.target;if(!u.rect)return{ok:!1,error:{code:"COMMAND_FAILED",message:`Ref ${t.positionals[0]} not found or has no bounds`}};let p=u.type??"",f=p&&!oJ(p,o.device.platform)?`fill target ${t.positionals[0]} resolved to "${p}", attempting fill anyway.`:void 0,m=oq(u,c),h=sn(u,o.device.platform,{action:"fill"}),{x:w,y:g}=oB(u.rect),I={...await n(o.device,"fill",[String(w),String(g),s],t.flags?.out,{...i(t.flags,o.appBundleId,o.trace?.outPath)})??{ref:d,x:w,y:g}};return f&&(I.warning=f),a.recordAction(o,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{...I,refLabel:m,selectorChain:h}}),{ok:!0,data:I}}if(!o)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};let s=o1(t.positionals??[],{preferTrailingValue:!0});if(!s)return{ok:!1,error:{code:"INVALID_ARGS",message:"fill requires x y text, @ref text, or selector text"}};if(0===s.rest.length)return{ok:!1,error:{code:"INVALID_ARGS",message:"fill requires text after selector"}};let l=s.rest.join(" ").trim();if(!l)return{ok:!1,error:{code:"INVALID_ARGS",message:"fill requires text after selector"}};let d=await dg({command:t.command,selectorExpression:s.selectorExpression,session:o,flags:t.flags,sessionStore:a,contextFromFlags:i,interactiveOnly:!0,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0,dispatch:n});if(!d.ok)return d.response;let{resolved:u,snapshot:c}=d,p=u.node;if(!p.rect)return{ok:!1,error:{code:"COMMAND_FAILED",message:`Selector ${u.selector.raw} resolved to invalid bounds`}};let f=p.type??"",m=f&&!oJ(f,o.device.platform)?`fill target ${u.selector.raw} resolved to "${f}", attempting fill anyway.`:void 0,{x:h,y:w}=oB(p.rect),g=await n(o.device,"fill",[String(h),String(w),l],t.flags?.out,{...i(t.flags,o.appBundleId,o.trace?.outPath)}),I=sn(p,o.device.platform,{action:"fill"}),A={...g??{x:h,y:w,text:l},selector:u.selector.raw,selectorChain:I,refLabel:oq(p,c.nodes)};return m&&(A.warning=m),a.recordAction(o,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:A}),{ok:!0,data:A}}async function dA(e){let{req:t,sessionName:r,sessionStore:a,contextFromFlags:i,dispatch:n}=e,o=t.positionals?.[0];if("text"!==o&&"attrs"!==o)return{ok:!1,error:{code:"INVALID_ARGS",message:"get only supports text or attrs"}};let s=a.get(r);if(!s)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};if(!oM("get",s.device))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"get is not supported on this device"}};let l=t.positionals?.[1]??"";if(l.startsWith("@")){let e=df("get",t.flags);if(e)return e;let r=dm({session:s,refInput:l,fallbackLabel:t.positionals.length>2?t.positionals.slice(2).join(" ").trim():"",requireRect:!1,invalidRefMessage:"get text requires a ref like @e2",notFoundMessage:`Ref ${l} not found`});if(!r.ok)return r.response;let{ref:i,node:n}=r.target,d=sn(n,s.device.platform,{action:"get"});if("attrs"===o)return a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{ref:i,selectorChain:d}}),{ok:!0,data:{ref:i,node:n}};let u=oK(n);return a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{ref:i,text:u,refLabel:u||void 0,selectorChain:d}}),{ok:!0,data:{ref:i,text:u,node:n}}}let d=t.positionals.slice(1).join(" ").trim();if(!d)return{ok:!1,error:{code:"INVALID_ARGS",message:"get requires @ref or selector expression"}};let u=await dg({command:t.command,selectorExpression:d,session:s,flags:t.flags,sessionStore:a,contextFromFlags:i,interactiveOnly:!1,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:"text"===o,dispatch:n});if(!u.ok)return u.response;let{resolved:c}=u,p=c.node,f=sn(p,s.device.platform,{action:"get"});if("attrs"===o)return a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{selector:c.selector.raw,selectorChain:f}}),{ok:!0,data:{selector:c.selector.raw,node:p}};let m=oK(p);return a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{text:m,refLabel:m||void 0,selector:c.selector.raw,selectorChain:f}}),{ok:!0,data:{selector:c.selector.raw,text:m,node:p}}}async function dv(e){let{req:t,sessionName:r,sessionStore:a,contextFromFlags:i,dispatch:n}=e,o=(t.positionals?.[0]??"").toLowerCase();if(!["visible","hidden","exists","editable","selected","text"].includes(o))return{ok:!1,error:{code:"INVALID_ARGS",message:"is requires predicate: visible|hidden|exists|editable|selected|text"}};let s=a.get(r);if(!s)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};if(!oM("is",s.device))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"is is not supported on this device"}};let{split:l}=o2(t.positionals);if(!l)return{ok:!1,error:{code:"INVALID_ARGS",message:"is requires a selector expression"}};let d=l.rest.join(" ").trim();if("text"===o&&!d)return{ok:!1,error:{code:"INVALID_ARGS",message:"is text requires expected text value"}};if("text"!==o&&l.rest.length>0)return{ok:!1,error:{code:"INVALID_ARGS",message:`is ${o} does not accept trailing values`}};let u=oQ(l.selectorExpression);if("exists"===o){let e=sr((await dw(s,t.flags,a,i,{interactiveOnly:!1},n)).nodes,u,{platform:s.device.platform});return e?(a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{predicate:o,selector:e.selector.raw,selectorChain:u.selectors.map(e=>e.raw),pass:!0,matches:e.matches}}),{ok:!0,data:{predicate:o,pass:!0,selector:e.selector.raw,matches:e.matches}}):{ok:!1,error:{code:"COMMAND_FAILED",message:sa(u,[],{unique:!1})}}}let c=await dg({command:"is",selectorExpression:l.selectorExpression,session:s,flags:t.flags,sessionStore:a,contextFromFlags:i,interactiveOnly:!1,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:!1,dispatch:n});if(!c.ok)return c.response;let{resolved:p}=c,f=function(e){let{predicate:t,node:r,expectedText:a,platform:i}=e,n=oK(r),o=!1;switch(t){case"visible":o=o5(r);break;case"hidden":o=!o5(r);break;case"editable":o=o9(r,i);break;case"selected":o=!0===r.selected;break;case"text":o=n===(a??"")}let s="text"===t?`expected="${a??""}" actual="${n}"`:`actual=${JSON.stringify({visible:o5(r),editable:o9(r,i),selected:!0===r.selected})}`;return{pass:o,actualText:n,details:s}}({predicate:o,node:p.node,expectedText:d,platform:s.device.platform});return f.pass?(a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{predicate:o,selector:p.selector.raw,selectorChain:u.selectors.map(e=>e.raw),pass:!0,text:"text"===o?f.actualText:void 0}}),{ok:!0,data:{predicate:o,pass:!0,selector:p.selector.raw}}):{ok:!1,error:{code:"COMMAND_FAILED",message:`is ${o} failed for selector ${p.selector.raw}: ${f.details}`}}}async function dy(e){let{req:t,sessionName:r,sessionStore:a,contextFromFlags:i,dispatch:n}=e,o="click"===t.command?"click":"press",s=a.get(r);if(!s)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};if(!oM("press",s.device))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"press is not supported on this device"}};let l=n7(t.flags),d="primary"===l?{}:{button:l};if("primary"!==l){let e=oe({commandLabel:o,platform:s.device.platform,button:l,count:t.flags?.count,intervalMs:t.flags?.intervalMs,holdMs:t.flags?.holdMs,jitterPx:t.flags?.jitterPx,doubleTap:t.flags?.doubleTap});if(e)return{ok:!1,error:{code:e.code,message:e.message,details:e.details}}}let u=function(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}(t.positionals??[]);if(u){let e=await n(s.device,"press",[String(u.x),String(u.y)],t.flags?.out,{...i(t.flags,s.appBundleId,s.trace?.outPath)});return a.recordAction(s,{command:t.command,positionals:t.positionals??[String(u.x),String(u.y)],flags:t.flags??{},result:e??{x:u.x,y:u.y,...d}}),{ok:!0,data:e??{x:u.x,y:u.y,...d}}}let c=t.positionals?.[0]??"";if(c.startsWith("@")){let e=df("press",t.flags);if(e)return e;let r=t.positionals.length>1?t.positionals.slice(1).join(" ").trim():"",l=dm({session:s,refInput:c,fallbackLabel:r,requireRect:!0,invalidRefMessage:`${o} requires a ref like @e2`,notFoundMessage:`Ref ${c} not found or has no bounds`});if(!l.ok)return l.response;let{ref:u}=l.target,p=l.target.node,f=l.target.snapshotNodes,m=dh(p.rect);if(!m){let e=await dw(s,t.flags,a,i,{interactiveOnly:!0},n),o=oG(e.nodes,u),l=r.length>0?oj(e.nodes,r):null,d=dh(l?.rect),c=dh(o?.rect)?o:d?l:o??l,h=dh(c?.rect);c&&h&&(p=c,f=e.nodes,m=h)}if(!m)return{ok:!1,error:{code:"COMMAND_FAILED",message:`Ref ${c} not found or has invalid bounds`}};let h=oq(p,f),w=sn(p,s.device.platform,{action:"click"}),{x:g,y:I}=m,A=await n(s.device,"press",[String(g),String(I)],t.flags?.out,{...i(t.flags,s.appBundleId,s.trace?.outPath)});return a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{ref:u,x:g,y:I,refLabel:h,selectorChain:w,...d}}),{ok:!0,data:{...A??{},ref:u,x:g,y:I,...d}}}let p=(t.positionals??[]).join(" ").trim();if(!p)return{ok:!1,error:{code:"INVALID_ARGS",message:`${o} requires @ref, selector expression, or x y coordinates`}};let f=await dg({command:t.command,selectorExpression:p,session:s,flags:t.flags,sessionStore:a,contextFromFlags:i,interactiveOnly:!0,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0,dispatch:n});if(!f.ok)return f.response;let{resolved:m,snapshot:h}=f,w=dh(m.node.rect);if(!w)return{ok:!1,error:{code:"COMMAND_FAILED",message:`Selector ${m.selector.raw} resolved to invalid bounds`}};let{x:g,y:I}=w,A=await n(s.device,"press",[String(g),String(I)],t.flags?.out,{...i(t.flags,s.appBundleId,s.trace?.outPath)}),v=sn(m.node,s.device.platform,{action:"click"}),y=oq(m.node,h.nodes);return a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{x:g,y:I,selector:m.selector.raw,selectorChain:v,refLabel:y,...d}}),{ok:!0,data:{...A??{},selector:m.selector.raw,x:g,y:I,...d}}}function db(e,t,r){return t>=e.x&&t<=e.x+e.width&&r>=e.y&&r<=e.y+e.height}function dS(e){let t=null,r=-1;for(let a of e){let e=a.width*a.height;e>r&&(t=a,r=e)}return t}function dN(e,t,r){return Math.min(r,Math.max(t,Math.round(e)))}async function d_(e){let{req:t,sessionName:r,sessionStore:a,contextFromFlags:i,dispatch:n}=e,o=a.get(r);if(!o)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};if(!oM("scrollintoview",o.device))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"scrollintoview is not supported on this device"}};let s=t.positionals?.[0]??"";if(!s.startsWith("@"))return null;let l=df("scrollintoview",t.flags);if(l)return l;let d=dm({session:o,refInput:s,fallbackLabel:t.positionals&&t.positionals.length>1?t.positionals.slice(1).join(" ").trim():"",requireRect:!0,invalidRefMessage:"scrollintoview requires a ref like @e2",notFoundMessage:`Ref ${s} not found or has no bounds`});if(!d.ok)return d.response;let{ref:u,node:c,snapshotNodes:p}=d.target;if(!c.rect)return{ok:!1,error:{code:"COMMAND_FAILED",message:`Ref ${s} not found or has no bounds`}};let f=function(e,t){let r=oB(t),a=e.filter(e=>{var t;return!!(t=e.rect)&&Number.isFinite(t.x)&&Number.isFinite(t.y)&&Number.isFinite(t.width)&&Number.isFinite(t.height)}),i=a.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}),n=dS(i.map(e=>e.rect).filter(e=>db(e,r.x,r.y)));if(n)return n;let o=dS(i.map(e=>e.rect));if(o)return o;let s=dS(a.map(e=>e.rect).filter(e=>db(e,r.x,r.y)));return s||null}(p,c.rect);if(!f)return{ok:!1,error:{code:"COMMAND_FAILED",message:`scrollintoview could not infer viewport for ${s}`}};let m=function(e,t){var r,a;let i=Math.max(1,t.height),n=Math.max(1,t.width),o=t.y,s=t.y+i,l=t.x,d=t.x+n,u=o+.25*i,c=s-.25*i,p=Math.max(8,.1*n),f=e.y+e.height/2,m=e.x+e.width/2;if(f>=u&&f<=c)return null;let h=Math.round((r=m,a=l+p,Math.min(d-p,Math.max(a,r)))),w=Math.round(o+.86*i),g=Math.round(o+.14*i),I=Math.max(1,Math.abs(w-g));return f>c?{x:h,startY:w,endY:g,count:dN(Math.ceil((f-c)/I),1,50),direction:"down"}:{x:h,startY:g,endY:w,count:dN(Math.ceil((u-f)/I),1,50),direction:"up"}}(c.rect,f),h=oq(c,p),w=sn(c,o.device.platform,{action:"get"});if(!m)return a.recordAction(o,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{ref:u,attempts:0,alreadyVisible:!0,refLabel:h,selectorChain:w}}),{ok:!0,data:{ref:u,attempts:0,alreadyVisible:!0}};let g=await n(o.device,"swipe",[String(m.x),String(m.startY),String(m.x),String(m.endY),"16"],t.flags?.out,{...i(t.flags,o.appBundleId,o.trace?.outPath),count:m.count,pauseMs:0,pattern:"one-way"});return a.recordAction(o,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{...g??{},ref:u,attempts:m.count,direction:m.direction,refLabel:h,selectorChain:w}}),{ok:!0,data:{...g??{},ref:u,attempts:m.count,direction:m.direction}}}async function dD(e){let t={...e,dispatch:e.dispatch??oL};switch(e.req.command){case"click":case"press":return await dy(t);case"fill":return await dI(t);case"get":return await dA(t);case"is":return await dv(t);case"scrollintoview":return await d_(t);default:return null}}function dE(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 dk(e){let{req:t,leaseRegistry:r}=e,a=dE(t);switch(t.command){case"lease_allocate":return{ok:!0,data:{lease:r.allocateLease({tenantId:a.tenantId??"",runId:a.runId??"",backend:a.leaseBackend,ttlMs:a.leaseTtlMs})}};case"lease_heartbeat":return{ok:!0,data:{lease:r.heartbeatLease({leaseId:a.leaseId??"",tenantId:a.tenantId,runId:a.runId,ttlMs:a.leaseTtlMs})}};case"lease_release":return{ok:!0,data:r.releaseLease({leaseId:a.leaseId??"",tenantId:a.tenantId,runId:a.runId})};default:return null}}function dL(e,t){if(!t)return[];let r=[],a=e.device,i=t.platform;if(i&&!eX(a.platform,i)&&r.push({key:"platform",value:t.platform}),t.target&&t.target!==(a.target??"mobile")&&r.push({key:"target",value:t.target}),t.udid&&("ios"!==a.platform||t.udid!==a.id)&&r.push({key:"udid",value:t.udid}),t.serial&&("android"!==a.platform||t.serial!==a.id)&&r.push({key:"serial",value:t.serial}),t.device&&t.device.trim().toLowerCase()!==a.name.trim().toLowerCase()&&r.push({key:"device",value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),i=a.simulatorSetPath?.trim();("ios"!==a.platform||"simulator"!==a.kind||e!==i)&&r.push({key:"iosSimulatorDeviceSet",value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=ek(t.androidDeviceAllowlist);"android"===a.platform&&e.has(a.id)||r.push({key:"androidDeviceAllowlist",value:t.androidDeviceAllowlist})}return r}function dO(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 dx=["target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist"],dM=new Set(["session_list","devices","ensure-simulator","release_materialized_paths"]),dC=new Set(["session_list","devices","ensure-simulator","release_materialized_paths","lease_allocate","lease_heartbeat","lease_release"]);function dR(e,t,r,a){let i=_().requestId;return{...oC(e,t,r,a,i),requestId:i}}function dP(e){R.existsSync(e)&&R.unlinkSync(e)}function dT(e){if(!R.existsSync(e))return null;try{let t=JSON.parse(R.readFileSync(e,"utf8"));if(!Number.isInteger(t.pid)||t.pid<=0)return null;return t}catch{return null}}function d$(e){let t=dT(e);if(!t||t.pid===process.pid)try{R.existsSync(e)&&R.unlinkSync(e)}catch{}}function dF(e){if(void 0===e)return;let t=Number(e);if(Number.isInteger(t))return t}let{baseDir:dU,infoPath:dV,lockPath:dG,logPath:dB,sessionsDir:dj}=U(process.env.AGENT_DEVICE_STATE_DIR),dq=F(process.env.AGENT_DEVICE_DAEMON_SERVER_MODE);var dH=dj;if(R.existsSync(dH))for(let e of R.readdirSync(dH,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=i.join(dH,e.name,"app-log.pid");if(R.existsSync(t))try{let e=function(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}}(R.readFileSync(t,"utf8"));if(e&&function(e){let t,r=M(e.pid);if(!r||e.startTime&&r!==e.startTime)return!1;let a=n(e.pid);return!!a&&!!((t=a.toLowerCase().replaceAll("\\","/")).includes("log stream")||t.includes("logcat")||t.includes("devicectl device log stream"))&&(!e.command||a===e.command)}(e))try{process.kill(e.pid,"SIGTERM")}catch{}}catch{}finally{t$(t)}}let dW=new tP(dj),dz=new rI({maxActiveSimulatorLeases:dF(process.env.AGENT_DEVICE_MAX_SIMULATOR_LEASES),defaultLeaseTtlMs:dF(process.env.AGENT_DEVICE_LEASE_TTL_MS),minLeaseTtlMs:dF(process.env.AGENT_DEVICE_LEASE_MIN_TTL_MS),maxLeaseTtlMs:dF(process.env.AGENT_DEVICE_LEASE_MAX_TTL_MS)}),dJ=N(),dK=u.randomBytes(24).toString("hex"),dX=M(process.pid)??void 0,dZ=function(){let e=process.argv[1];if(!e)return"unknown";try{let t=R.statSync(e),r=k(),a=i.relative(r,e)||e;return`${a}:${t.size}:${Math.trunc(t.mtimeMs)}`}catch{return"unknown"}}(),dY=function(e){let{logPath:t,token:r,sessionStore:a,leaseRegistry:n,trackDownloadableArtifact:s}=e,l=e.dispatchCommand??oL;async function d(e){let u=!!(e.meta?.debug||e.flags?.verbose);return await C({session:e.session,requestId:e.meta?.requestId,command:e.command,debug:u,logPath:t},async()=>{if(e.token!==r)return{ok:!1,error:y(new w("UNAUTHORIZED","Invalid token"))};try{let r=function(e){let t=b(e.meta?.sessionIsolation??e.flags?.sessionIsolation),r=e.meta?.tenantId??e.flags?.tenant,a=o(r);if(r&&!a)throw new w("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if("tenant"!==t)return e;if(!a)throw new w("INVALID_ARGS","session isolation mode tenant requires --tenant (or meta.tenantId).");let i=e.session||"default";return i.startsWith(`${a}:`)?{...e,meta:{...e.meta,tenantId:a,sessionIsolation:t}}:{...e,session:`${a}:${i}`,meta:{...e.meta,tenantId:a,sessionIsolation:t}}}(e);L({level:"info",phase:"request_start",data:{session:r.session,command:r.command,tenant:r.meta?.tenantId,isolation:r.meta?.sessionIsolation}});let u=r.command,c=dE(r);dC.has(u)||r.meta?.sessionIsolation!=="tenant"||n.assertLeaseAdmission({tenantId:c.tenantId,runId:c.runId,leaseId:c.leaseId,backend:c.leaseBackend});let p=function(e,t){var r;let a,i=e.session||"default";if(r=e,a=r.flags?.session,"string"==typeof a&&a.trim().length>0||"default"!==i||t.has(i))return i;let n=t.toArray();return 1===n.length?n[0].name:i}(r,a),f=a.get(p),m=function(e,t){let r=e.meta?.lockPolicy;if(!r)return e;let a={...e.flags??{}},i=t?dL(t,a):function(e,t){var r,a;let i=[];for(let n of(void 0!==e.platform&&t&&(r=e.platform,a=t,r&&a&&r!==a&&("apple"===r?!eK(a):"apple"!==a||!eK(r)))&&i.push({key:"platform",value:e.platform}),dx)){let t=e[n];"string"==typeof t&&t.trim().length>0&&i.push({key:n,value:t})}return i}(a,e.meta?.lockPlatform);if(0===i.length)return!t&&e.meta?.lockPlatform&&void 0===a.platform&&(a.platform=e.meta.lockPlatform),{...e,flags:a};if("strip"===r)return t?(function(e,t){for(let r of t)delete e[r.key]}(a,i),a.platform=t.device.platform):function(e,t){for(let t of dx)delete e[t];t&&(e.platform=t)}(a,e.meta?.lockPlatform),{...e,flags:a};throw new w("INVALID_ARGS",`${e.command} cannot override session lock policy with ${i.map(dO).join(", ")}. Unset those selectors or remove the request lock policy.`)}(r,f),h=e=>(function(e,t,r){let a=_();if(!t.ok){L({level:"error",phase:"request_failed",data:{code:t.error.code,message:t.error.message}});let e=P({force:!0})??void 0;return{ok:!1,error:y(new w(t.error.code,t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath}),{diagnosticId:a.diagnosticId,logPath:e})}}return L({level:"info",phase:"request_success"}),P(),{ok:!0,data:function(e,t,r){var a,n;let o;if(!t)return t;let s=(a=e,n=t,o=Array.isArray(n.artifacts)?[...n.artifacts]:[],"screenshot"!==a.command||o.some(e=>e?.field==="path")||"string"!=typeof n.path||o.push({field:"path",path:n.path,localPath:a.meta?.clientArtifactPaths?.path,fileName:i.basename(a.meta?.clientArtifactPaths?.path??n.path)}),o.filter(e=>!!(e&&"string"==typeof e.field&&"string"==typeof e.path&&"string"==typeof e.localPath&&e.localPath.length>0)));return 0===s.length?t:{...t,artifacts:s.map(t=>{let a=t.path;return{field:t.field,artifactId:r({artifactPath:a,tenantId:e.meta?.tenantId,fileName:t.fileName}),fileName:t.fileName,localPath:t.localPath}})}}(e,t.data,r)}})(m,e,s);!f||m.meta?.lockPolicy||dM.has(u)||function(e,t){let r=dL(e,t);if(0!==r.length){var a;let t,i,n;throw new w("INVALID_ARGS",`Session "${e.name}" is bound to ${(t=(a=e).device.platform,i=a.device.name.trim(),n=a.device.id,`${t} device "${i}" (${n})`)} and cannot be used with ${r.map(dO).join(", ")}. Use a different --session name or close this session first.`)}}(f,m.flags);let g=await dk({req:m,leaseRegistry:n});if(g)return h(g);let I=await lq({req:m,sessionName:p,logPath:t,sessionStore:a,invoke:d});if(I)return h(I);let A=await dt({req:m,sessionName:p,logPath:t,sessionStore:a});if(A)return h(A);let v=await dc({req:m,sessionName:p,sessionStore:a,logPath:t});if(v)return h(v);let S=await dn({req:m,sessionName:p,logPath:t,sessionStore:a,invoke:d});if(S)return h(S);let N=await dD({req:m,sessionName:p,sessionStore:a,contextFromFlags:(e,r,a)=>dR(t,e,r,a)});if(N)return h(N);let D=a.get(p);if(!D)return h({ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}});if(!oM(u,D.device))return h({ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:`${u} is not supported on this device`}});let E=m.positionals??[],k=m.flags?.out,O="screenshot"===u&&E[0]?[tP.expandHome(E[0],m.meta?.cwd),...E.slice(1)]:E,x="screenshot"===u&&k?tP.expandHome(k,m.meta?.cwd):k,M="screenshot"===u?O:E,C="screenshot"===u&&x?{...m.flags??{},out:x}:m.flags??{},R=await l(D.device,u,O,x,{...dR(t,m.flags,D.appBundleId,D.trace?.outPath)});return a.recordAction(D,{command:u,positionals:M,flags:C,result:R??{}}),h({ok:!0,data:R??{}})}catch(r){L({level:"error",phase:"request_failed",data:{error:r instanceof Error?r.message:String(r)}});let e=_(),t=P({force:!0})??void 0;return{ok:!1,error:y(r,{diagnosticId:e.diagnosticId,logPath:t})}}})}return d}({logPath:dB,token:dK,sessionStore:dW,leaseRegistry:dz,trackDownloadableArtifact:function(e){let t=u.randomUUID(),r=setTimeout(()=>{tQ(t)},9e5);return r.unref(),tY.set(t,{artifactPath:e.artifactPath,tenantId:e.tenantId,fileName:e.fileName,deleteAfterDownload:!1!==e.deleteAfterDownload,timer:r}),t}});!async function(){let e,t;if(!function(e,t,r){R.existsSync(e)||R.mkdirSync(e,{recursive:!0});let a=JSON.stringify(r,null,2),i=()=>{try{return R.writeFileSync(t,a,{flag:"wx",mode:384}),!0}catch(e){if("EEXIST"===e.code)return!1;throw e}};if(i())return!0;let n=dT(t);if(n?.pid&&n.pid!==process.pid&&s(n.pid,n.processStartTime))return!1;try{R.unlinkSync(t)}catch{}return i()}(dU,dG,{pid:process.pid,version:dJ,startedAt:Date.now(),processStartTime:dX})){process.stderr.write("Daemon lock is held by another process; exiting.\n"),process.exit(0);return}let r=[];try{var a;let i;if("socket"===dq||"dual"===dq){let t=$.createServer(e=>{let t="",r=0,a=new Set,i=!1,n=()=>{if(!i&&0!==r){for(let e of(i=!0,a))eu(e);L({level:"warn",phase:"request_client_disconnected",data:{inFlightRequests:r}}),(async()=>{let e=Date.now()+15e3;for(;r>0&&Date.now()<e&&(await tf(),!(r<=0));)await new Promise(e=>setTimeout(e,200))})()}};e.setEncoding("utf8"),e.on("close",n),e.on("error",n),e.on("data",async i=>{let n=(t+=i).indexOf("\n");for(;-1!==n;){let i,o,s=t.slice(0,n).trim();if(t=t.slice(n+1),0===s.length){n=t.indexOf("\n");continue}r+=1;try{let e=JSON.parse(s);if(o=el(e.meta?.requestId,"socket"),e.meta={...e.meta,requestId:o},a.add(o),ed(o),ep(o))throw em();i=await dY(e)}catch(e){i={ok:!1,error:y(e)}}finally{r-=1,o&&(a.delete(o),ec(o))}e.destroyed||e.write(`${JSON.stringify(i)}
38
- `),n=t.indexOf("\n")}})});r.push(t),e=await new Promise((e,r)=>{t.once("error",r),t.listen(0,"127.0.0.1",()=>{t.off("error",r);let a=t.address();"object"==typeof a&&a?.port?e(a.port):r(new w("COMMAND_FAILED","Failed to bind socket server"))})})}if("http"===dq||"dual"===dq){let e=await rc({handleRequest:dY,token:dK});r.push(e),t=await new Promise((t,r)=>{e.once("error",r),e.listen(0,"127.0.0.1",()=>{e.off("error",r);let a=e.address();"object"==typeof a&&a?.port?t(a.port):r(new w("COMMAND_FAILED","Failed to bind HTTP server"))})})}a={socketPort:e,httpPort:t,token:dK,version:dJ,codeSignature:dZ,processStartTime:dX},R.existsSync(dU)||R.mkdirSync(dU,{recursive:!0}),R.writeFileSync(dB,""),i=a.socketPort&&a.httpPort?"dual":a.httpPort?"http":"socket",R.writeFileSync(dV,JSON.stringify({port:a.socketPort,httpPort:a.httpPort,transport:i,token:a.token,pid:process.pid,version:a.version,codeSignature:a.codeSignature,processStartTime:a.processStartTime,stateDir:dU},null,2),{mode:384}),e&&process.stdout.write(`AGENT_DEVICE_DAEMON_PORT=${e}
26
+ ${i}`.toLowerCase();return n.includes("timeout waiting for screen surfaces")||n.includes("nsposixerrordomain")&&n.includes("code=60")&&n.includes("screenshot")||n.includes("timed out")&&n.includes("screenshot")}let oe={settings:"com.apple.Preferences"},ot=null;function or(e,t,r){return m("xcrun",e$(e,t),r)}function oa(e){return e.includes("not installed")||e.includes("not found")||e.includes("no such file")}async function oi(e,t){if("macos"===e.platform)return await nC(t);let r=t.trim();if(r.includes("."))return r;let a=oe[r.toLowerCase()];if(a)return a;let i=("simulator"===e.kind?await og(e):await i3(e,"all")).filter(e=>e.name.toLowerCase()===r.toLowerCase());if(1===i.length)return i[0].bundleId;if(i.length>1)throw new I("INVALID_ARGS",`Multiple apps matched "${t}"`,{matches:i});throw new I("APP_NOT_INSTALLED",`No app found matching "${t}"`)}async function on(e,t,r){if("macos"===e.platform)return void await nP(e,t,r);let a=r?.url?.trim();if(a){if(!rU(a))throw new I("INVALID_ARGS","open <app> <url> requires a valid URL target");if("simulator"===e.kind){await nt(e),await ne(),await or(e,["openurl",e.id,a]);return}let i=rV(r?.appBundleId??await oi(e,t),a);if(!i)throw new I("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await oD(e,i,{payloadUrl:a});return}let i=t.trim();if(rU(i)){if("simulator"===e.kind){await nt(e),await ne(),await or(e,["openurl",e.id,i]);return}let t=rV(r?.appBundleId,i);if(!t)throw new I("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await oD(e,t,{payloadUrl:i});return}let n=r?.appBundleId??await oi(e,t);"simulator"===e.kind?await oN(e,n):await oD(e,n)}async function oo(e){"macos"===e.platform||"simulator"!==e.kind||"Booted"!==await na(e)&&(await nt(e),await ne())}async function os(e,t){if("macos"===e.platform)return void await nR(e,t);let r=await oi(e,t);if("simulator"===e.kind){await nt(e);let t=e$(e,["terminate",e.id,r]),a=await m("xcrun",t,{allowFailure:!0});if(0!==a.exitCode){if(a.stderr.toLowerCase().includes("found nothing to terminate"))return;throw new I("COMMAND_FAILED",`xcrun exited with code ${a.exitCode}`,{cmd:"xcrun",args:t,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode})}return}await i2(["device","process","terminate","--device",e.id,r],{action:"terminate iOS app",deviceId:e.id})}async function ol(e,t){let r=await oi(e,t);if("simulator"!==e.kind){let t=["devicectl","device","uninstall","app","--device",e.id,r],a=await m("xcrun",t,{allowFailure:!0,timeoutMs:iZ});if(0!==a.exitCode){let i=String(a.stdout??""),n=String(a.stderr??"");if(!oa(`${i}
27
+ ${n}`.toLowerCase()))throw new I("COMMAND_FAILED",`Failed to uninstall iOS app ${r}`,{cmd:"xcrun",args:t,exitCode:a.exitCode,stdout:i,stderr:n,deviceId:e.id,hint:i5(i,n)??i8})}return{bundleId:r}}await nt(e);let a=await or(e,["uninstall",e.id,r],{allowFailure:!0});if(0!==a.exitCode&&!oa(`${a.stdout}
28
+ ${a.stderr}`.toLowerCase()))throw new I("COMMAND_FAILED",`simctl uninstall failed for ${r}`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return{bundleId:r}}async function od(e,t,r){let a=await nn({kind:"path",path:t},r);try{return await oc(e,a.installablePath),{archivePath:a.archivePath,installablePath:a.installablePath,bundleId:a.bundleId,appName:a.appName,launchTarget:a.bundleId}}finally{await a.cleanup()}}async function ou(e,t,r){let{bundleId:a}=await ol(e,t);return await od(e,r,{appIdentifierHint:t}),{bundleId:a}}async function oc(e,t){"simulator"!==e.kind?await i2(["device","install","app","--device",e.id,t],{action:"install iOS app",deviceId:e.id}):(await nt(e),await or(e,["install",e.id,t]))}async function op(e){if("macos"===e.platform)return await nT();i7(e,"clipboard"),await nt(e);let t=await or(e,["pbpaste",e.id],{allowFailure:!0});if(0!==t.exitCode)throw new I("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 of(e,t){if("macos"===e.platform)return void await n$(t);i7(e,"clipboard"),await nt(e);let r=await or(e,["pbcopy",e.id],{allowFailure:!0,stdin:t});if(0!==r.exitCode)throw new I("COMMAND_FAILED","Failed to write iOS simulator clipboard",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}async function om(e,t,r){i7(e,"push"),await nt(e);let a=await P.mkdtemp(o.join(V.tmpdir(),"agent-device-ios-push-")),i=o.join(a,"payload.apns");try{await P.writeFile(i,`${JSON.stringify(r)}
29
+ `,"utf8"),await or(e,["push",e.id,t,i])}finally{await P.rm(a,{recursive:!0,force:!0})}}async function oh(e,t,r,a,i){if("macos"===e.platform){let e=t.toLowerCase();if("appearance"===e)return void await nU(r);if("permission"===e){let e=iL(r);if("deny"===e)throw new I("INVALID_ARGS","Unsupported macOS permission action: deny. macOS supports only settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>.");let t=function(e){let t=e?.trim().toLowerCase();if("accessibility"===t||"screen-recording"===t||"input-monitoring"===t)return t;throw new I("INVALID_ARGS","Unsupported macOS permission target. Use accessibility|screen-recording|input-monitoring.")}(i?.permissionTarget);return await nN(e,t)}throw new I("INVALID_ARGS",`Unsupported macOS setting: ${t}. macOS supports settings appearance <light|dark|toggle> and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>.`)}i7(e,"settings"),await nt(e);let n=t.toLowerCase();switch(n){case"wifi":{let t=ov(r);await or(e,["status_bar",e.id,"override","--wifiMode",t?"active":"failed"]);return}case"airplane":return void(ov(r)?await or(e,["status_bar",e.id,"override","--dataNetwork","hide","--wifiMode","failed","--wifiBars","0","--cellularMode","failed","--cellularBars","0","--operatorName",""]):await or(e,["status_bar",e.id,"clear"]));case"location":{let t=ov(r);if(!a)throw new I("INVALID_ARGS","location setting requires an active app in session");await or(e,["privacy",e.id,t?"grant":"revoke","location",a]);return}case"faceid":case"touchid":{let t=oA[n],a=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 I("INVALID_ARGS",`Invalid ${t} state: ${e}. Use match|nonmatch|enroll|unenroll.`)}(r,n);await o_(e,a,{settingName:n,label:t.label,modalityAliases:t.modalityAliases});return}case"appearance":{let t=await oI(e,r);await or(e,["ui",e.id,"appearance",t]);return}case"permission":{var o;if(!a)throw new I("INVALID_ARGS","permission setting requires an active app in session");let t="deny"===(o=iL(r))?"revoke":o,n=function(e,t){let r=iC(e);if("photos"!==r&&t?.trim())throw new I("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 I("INVALID_ARGS",`Invalid photos mode: ${t}. Use full|limited.`)}throw new I("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 oy(e,t,n,a);return}default:throw new I("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function ow(e,t="all"){return"macos"===e.platform?await nV(t):"simulator"===e.kind?nu(await og(e),t):await i3(e,t)}async function og(e){let t=(await or(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 m("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])=>({bundleId:e,name:t.CFBundleDisplayName??t.CFBundleName??e})):[]}function ov(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 I("INVALID_ARGS",`Invalid setting state: ${e}`)}async function oI(e,t){let r=iP(t);if("toggle"!==r)return r;let a=await or(e,["ui",e.id,"appearance"],{allowFailure:!0});if(0!==a.exitCode)throw new I("COMMAND_FAILED","Failed to read current iOS appearance",{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});let i=function(e,t){let r=/\b(light|dark|unsupported|unknown)\b/i.exec(`${e}
30
+ ${t}`);if(!r)return null;let a=r[1].toLowerCase();return"dark"===a?"dark":"light"===a?"light":null}(a.stdout,a.stderr);if(!i)throw new I("COMMAND_FAILED","Unable to determine current iOS appearance for toggle",{stdout:a.stdout,stderr:a.stderr});return"dark"===i?"light":"dark"}let oA={faceid:{label:"Face ID",modalityAliases:["face"]},touchid:{label:"Touch ID",modalityAliases:["finger","touch"]}};async function oy(e,t,r,a){let i=await oS(e);if(!i.has(r))throw new I("UNSUPPORTED_OPERATION",`iOS simctl privacy does not support service "${r}" on this runtime.`,{deviceId:e.id,appBundleId:a,hint:`Supported services: ${Array.from(i).sort().join(", ")}`});let n=["privacy",e.id,t,r,a],o="notifications"===r;if(!("reset"===t&&o))try{await or(e,n);return}catch(t){if(!(o&&ob(t)))throw t;throw new I("UNSUPPORTED_OPERATION","iOS simulator does not support setting notifications permission via simctl privacy on this runtime.",{deviceId:e.id,appBundleId:a,hint:"Use reset notifications for reprompt behavior, or toggle notifications manually in Settings."})}try{await or(e,n);return}catch(e){if(!ob(e))throw e}try{await or(e,["privacy",e.id,"reset","all",a])}catch(t){throw new I("COMMAND_FAILED","iOS simulator blocked direct notifications reset. Fallback reset-all also failed.",{deviceId:e.id,appBundleId:a,hint:"Use reinstall to force a fresh notifications prompt, or reset simulator content and settings."},t instanceof Error?t:void 0)}}function ob(e){if(!(e instanceof I)||"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 oS(e){let r=eC(e.simulatorSetPath),a=`${process.env.PATH??""}::${r??""}`;if(ot&&t===a)return ot;let i=await or(e,["privacy","help"],{allowFailure:!0}),n=function(e){let t=new Set,r=!1;for(let a of e.split("\n")){let e=a.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);i&&t.add(i[1])}return t}(`${i.stdout}
31
+ ${i.stderr}`);if(0===n.size)throw new I("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 ot=n,t=a,n}async function o_(e,t,r){let a=function(e,t,r){let a=r.length>0?r:["face"];switch(t){case"match":return a.flatMap(t=>[["biometric",e,"match",t],["biometric","match",e,t]]);case"nonmatch":return a.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 a){let r=e$(e,t),a=await m("xcrun",r,{allowFailure:!0});if(0===a.exitCode)return;i.push({args:r,stderr:a.stderr,stdout:a.stdout,exitCode:a.exitCode})}let n=i.map(e=>({args:e.args.join(" "),exitCode:e.exitCode,stderr:e.stderr.slice(0,400)}));if(i.length>0&&i.every(e=>{var t,r;let a;return t=e.stdout,r=e.stderr,(a=`${t}
32
+ ${r}`.toLowerCase()).includes("unrecognized subcommand")||a.includes("unknown subcommand")||a.includes("not supported")||a.includes("unavailable")||a.includes("biometric")&&a.includes("invalid")}))throw new I("UNSUPPORTED_OPERATION",`${r.label} simulation is not supported on this simulator runtime.`,{deviceId:e.id,action:t,setting:r.settingName,attempts:n});throw new I("COMMAND_FAILED",`Failed to simulate ${r.settingName}.`,{deviceId:e.id,action:t,setting:r.settingName,attempts:n})}async function oN(e,t){await nt(e),await ne();let r=0,a=eo.fromTimeoutMs(iY);try{await es(async({deadline:r})=>{var a;if(r?.isExpired())throw new I("COMMAND_FAILED","App launch deadline exceeded",{timeoutMs:iY});let i=(a=["launch",e.id,t],e$(e,a)),n=await m("xcrun",i,{allowFailure:!0});if(0!==n.exitCode)throw new I("COMMAND_FAILED",`xcrun exited with code ${n.exitCode}`,{cmd:"xcrun",args:i,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})},{maxAttempts:10,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>!!i6(e)&&(r+=1)<3},{deadline:a})}catch(r){if(i6(r)){var i;let a=(i=await i9(e,t)).installed?!1===i.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."}}(a)}}throw r}}async function oD(e,t,r){let a=["device","process","launch","--device",e.id,t];r?.payloadUrl&&a.push("--payload-url",r.payloadUrl),await i2(a,{action:"launch iOS app",deviceId:e.id})}function oE(e){return e?.clickButton??"primary"}function ok(e){return"primary"===e.button?null:"click"!==e.commandLabel?new I("INVALID_ARGS","--button is supported only for click"):"macos"!==e.platform?new I("UNSUPPORTED_OPERATION",`click --button ${e.button} is supported only on macOS`):"middle"===e.button?new I("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 I("INVALID_ARGS",`click --button ${e.button} does not support repeat or gesture modifier flags`):null}let oM=/^[A-Za-z0-9_.:-]{1,64}$/,ox=[[0,0],[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];function oO(e,t,r,a){if(!Number.isFinite(e)||!Number.isInteger(e)||e<r||e>a)throw new I("INVALID_ARGS",`${t} must be an integer between ${r} and ${a}`);return e}async function oL(e,t,r){for(let a=0;a<e;a+=1)await r(a),a<e-1&&t>0&&await oC(t)}async function oC(e){await new Promise(t=>setTimeout(t,e))}function oP(e,t){let r,a=t?.subject??"Payload",i=e.trim();if(!i)throw new I("INVALID_ARGS",`${a} cannot be empty`);let n=t?.expandPath?t.expandPath(i,t.cwd):i;try{if(!F.statSync(n).isFile())throw new I("INVALID_ARGS",`${a} path is not a file: ${n}`);return{kind:"file",path:n}}catch(t){if(t instanceof I)throw t;let e=t.code;if("EACCES"===e||"EPERM"===e)throw new I("INVALID_ARGS",`${a} file is not readable: ${n}`);if(e&&"ENOENT"!==e)throw new I("COMMAND_FAILED",`Unable to read ${a} file: ${n}`,{cause:String(t)})}if((r=i.trim()).startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))return{kind:"inline",text:i};throw new I("INVALID_ARGS",`${a} file not found: ${n}`)}async function oR(e){let t=oP(e,{subject:"Push payload"}),r="inline"===t.kind?t.text:await oT(t.path);try{let e=JSON.parse(r);if(!e||"object"!=typeof e||Array.isArray(e))throw new I("INVALID_ARGS","push payload must be a JSON object");return e}catch(t){if(t instanceof I)throw t;throw new I("INVALID_ARGS",`Invalid push payload JSON: ${e}`)}}async function oT(e){try{return await P.readFile(e,"utf8")}catch(r){let t=r.code;if("ENOENT"===t)throw new I("INVALID_ARGS",`Push payload file not found: ${e}`);if("EISDIR"===t)throw new I("INVALID_ARGS",`Push payload path is not a file: ${e}`);if("EACCES"===t||"EPERM"===t)throw new I("INVALID_ARGS",`Push payload file is not readable: ${e}`);throw new I("COMMAND_FAILED",`Unable to read push payload file: ${e}`,{cause:String(r)})}}let o$=ek(process.env.AGENT_DEVICE_IOS_DEVICECTL_LIST_TIMEOUT_MS,8e3,500),oF=/^(iphone|ipad|ipod|appletv)/i,oU=/^appletv/i,oV=["apple tv","appletv","tvos"];function oG(e){return(e??"").trim().toLowerCase()}function oB(e){return oG(e.hardwareProperties?.platform)}function oj(e){return e.includes("tvos")}function oq(e){return oj(oG(e))?"tv":"mobile"}function oH(e){let t=oG(e);return t.includes("ios")||t.includes("tvos")}function oW(e){let t=oG(e);return oV.some(e=>t.includes(e))}function oz(e){return oF.test(e.trim())}function oJ(e){return oU.test(e.trim())}function oX(e){return[e.name??"",e.deviceProperties?.name??"",e.deviceProperties?.deviceType??""]}function oK(e){return e.hardwareProperties?.productType??e.deviceProperties?.productType??""}function oY(e){return oj(oB(e))||oJ(oK(e))||oX(e).some(oW)?"tv":"mobile"}function oZ(e){let t=oB(e);return!!(t.includes("ios")||t.includes("tvos")||oz(oK(e)))||oX(e).some(oW)}async function oQ(e={}){let t,r,a=eC(e.simulatorSetPath),i=e.target;try{t=await m("xcrun",eT(["list","devices","-j"],{simulatorSetPath:a}))}catch{return null}try{r=JSON.parse(t.stdout)}catch{return null}let n=null,o=null,s=null;for(let[e,t]of Object.entries(r.devices)){if(!oH(e))continue;let r=oq(e);if(!i||r===i)for(let e of t){if(!e.isAvailable)continue;let t={platform:"ios",id:e.udid,name:e.name,kind:"simulator",target:r,booted:"Booted"===e.state,...a?{simulatorSetPath:a}:{}};t.booted&&(n=n??t),"mobile"===r&&(o=o??t),s=s??t}}return n??o??s}async function o0(e={}){if("darwin"!==process.platform)throw new I("UNSUPPORTED_PLATFORM","Apple tools are only available on macOS");if(!await y("xcrun"))throw new I("TOOL_MISSING","xcrun not found in PATH");let t=[],r=eC(e.simulatorSetPath),a=await m("xcrun",eT(["list","devices","-j"],{simulatorSetPath:r}));try{let e=JSON.parse(a.stdout);for(let[a,i]of Object.entries(e.devices))if(oH(a))for(let e of i)e.isAvailable&&t.push({platform:"ios",id:e.udid,name:e.name,kind:"simulator",target:oq(a),booted:"Booted"===e.state,...r?{simulatorSetPath:r}:{}})}catch(e){throw new I("COMMAND_FAILED","Failed to parse simctl devices JSON",void 0,e)}if(t.push({platform:"macos",id:"host-macos-local",name:V.hostname(),kind:"device",target:"desktop",booted:!0}),r)return t;let i=null;try{i=o.join(V.tmpdir(),`agent-device-devicectl-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);let e=await m("xcrun",["devicectl","list","devices","--json-output",i],{allowFailure:!0,timeoutMs:o$});if(0!==e.exitCode)return t;let r=await P.readFile(i,"utf8"),a=JSON.parse(r);for(let e of a.result?.devices??[])if(oZ(e)){let r=e.hardwareProperties?.udid??e.identifier??"",a=e.name??e.deviceProperties?.name??r;if(!r)continue;t.push({platform:"ios",id:r,name:a,kind:"device",target:oY(e),booted:!0})}}catch{}finally{i&&await P.rm(i,{force:!0}).catch(()=>{})}return t}async function o1(e,t,r,a){let i,n=!!(t.udid||t.serial||t.deviceName);try{i=await a.resolveDevice(e,t,r)}catch(e){if(n||!(e instanceof I)||"DEVICE_NOT_FOUND"!==e.code)throw e}if(!n&&(!t.platform||"apple"===t.platform||"ios"===t.platform)&&"desktop"!==t.target&&(!i||"device"===i.kind)){let e=await a.findBootableSimulator({simulatorSetPath:r.simulatorSetPath,target:t.target});if(e)return e}if(i)return i;throw new I("DEVICE_NOT_FOUND","No devices found",{selector:t})}async function o2(e){let t=e.platform,r=e3({simulatorSetPath:eC(e.iosSimulatorDeviceSet),platform:t,target:e.target}),a=eR(e.androidDeviceAllowlist);return await O("resolve_target_device",async()=>{let i={platform:t,target:e.target,deviceName:e.device,udid:e.udid,serial:e.serial};if(i.target&&!i.platform)throw new I("INVALID_ARGS","Device target selector requires --platform. Use --platform ios|macos|android|apple with --target mobile|tv|desktop.");if("android"===i.platform){await rT();let e=await r2({serialAllowlist:a});return await e4(e,i)}if(i.platform){let e=await o0({simulatorSetPath:r});return await o1(e,i,{simulatorSetPath:r},{resolveDevice:e4,findBootableSimulator:oQ})}let n=[];try{n.push(...await r2({serialAllowlist:a}))}catch{}try{n.push(...await o0({simulatorSetPath:r}))}catch{}return await e4(n,i,{simulatorSetPath:r})},{platform:t,target:e.target})}async function o3(e,t,r,a,i){let n=function(e,t){switch(e.platform){case"android":return{open:(t,r)=>aG(e,t,r?.activity),openDevice:()=>aH(e),close:t=>aW(e,t),tap:(t,r)=>is(e,t,r),doubleTap:async(t,r)=>{await is(e,t,r),await is(e,t,r)},swipe:(t,r,a,i,n)=>il(e,t,r,a,i,n),longPress:(t,r,a)=>ip(e,t,r,a),focus:(t,r)=>ih(e,t,r),type:t=>im(e,t),fill:(t,r,a)=>iw(e,t,r,a),scroll:(t,r)=>ig(e,t,r),scrollIntoView:t=>iv(e,t),screenshot:(t,r)=>iH(e,t),back:()=>id(e),home:()=>iu(e),appSwitcher:()=>ic(e),readClipboard:()=>ik(e),writeClipboard:t=>iM(e,t),setSetting:(t,r,a,i)=>iR(e,t,r,a,i)};case"ios":case"macos":{var r,a;let i,n,{overrides:o,runnerOpts:s}=(r=e,i={verbose:(a=t).verbose,logPath:a.logPath,traceLogPath:a.traceLogPath,requestId:a.requestId},n=()=>{if(ev(a.requestId))throw eA()},{runnerOpts:i,overrides:{tap:async(e,t)=>await tE(r,{command:"tap",x:e,y:t,appBundleId:a.appBundleId},i),doubleTap:async(e,t)=>await tE(r,{command:"tapSeries",x:e,y:t,count:1,intervalMs:0,doubleTap:!0,appBundleId:a.appBundleId},i),swipe:async(e,t,n,o,s)=>await tE(r,{command:"drag",x:e,y:t,x2:n,y2:o,durationMs:s,appBundleId:a.appBundleId},i),longPress:async(e,t,n)=>await tE(r,{command:"longPress",x:e,y:t,durationMs:n,appBundleId:a.appBundleId},i),focus:async(e,t)=>await tE(r,{command:"tap",x:e,y:t,appBundleId:a.appBundleId},i),type:async e=>{await tE(r,{command:"type",text:e,appBundleId:a.appBundleId},i)},fill:async(e,t,n)=>{let o=await tE(r,{command:"tap",x:e,y:t,appBundleId:a.appBundleId},i);return await tE(r,{command:"type",text:n,clearFirst:!0,appBundleId:a.appBundleId},i),o},scroll:async(e,t)=>{if(!["up","down","left","right"].includes(e))throw new I("INVALID_ARGS",`Unknown direction: ${e}`);let n=function(e){switch(e){case"up":return"down";case"down":return"up";case"left":return"right";case"right":return"left"}}(e);return await tE(r,{command:"swipe",direction:n,appBundleId:a.appBundleId},i)},scrollIntoView:async e=>{let t=await tE(r,{command:"findText",text:e,appBundleId:a.appBundleId},i);if(t?.found)return{attempts:1};for(let t=0;t<12;t+=1){for(let e=0;e<4;e+=1)n(),await tE(r,{command:"swipe",direction:"up",appBundleId:a.appBundleId},i),await new Promise(e=>setTimeout(e,80));n();let o=await tE(r,{command:"findText",text:e,appBundleId:a.appBundleId},i);if(o?.found)return{attempts:t+2}}throw new I("COMMAND_FAILED",`scrollintoview could not find text: ${e}`)}}});return{open:(t,r)=>on(e,t,{appBundleId:r?.appBundleId,url:r?.url}),openDevice:()=>oo(e),close:t=>os(e,t),screenshot:(t,r)=>nQ(e,t,r),back:async()=>{await tE(e,{command:"back",appBundleId:t.appBundleId},s)},home:async()=>{await tE(e,{command:"home",appBundleId:t.appBundleId},s)},appSwitcher:async()=>{await tE(e,{command:"appSwitcher",appBundleId:t.appBundleId},s)},readClipboard:()=>op(e),writeClipboard:t=>of(e,t),setSetting:(t,r,a,i)=>oh(e,t,r,a,i),...o}}default:throw new I("UNSUPPORTED_PLATFORM",`Unsupported platform: ${e.platform}`)}}(e,{requestId:i?.requestId,appBundleId:i?.appBundleId,verbose:i?.verbose,logPath:i?.logPath,traceLogPath:i?.traceLogPath});return C({level:"debug",phase:"platform_command_prepare",data:{command:t,platform:e.platform,kind:e.kind}}),await O("platform_command",async()=>{switch(t){case"open":{let t=r[0],a=r[1];if(r.length>2)throw new I("INVALID_ARGS","open accepts at most two arguments: <app|url> [url]");if(!t)return await n.openDevice(),{app:null};if(void 0!==a){if("android"===e.platform)throw new I("INVALID_ARGS","open <app> <url> is supported only on Apple platforms");if(rU(t))throw new I("INVALID_ARGS","open <app> <url> requires an app target as the first argument");if(!rU(a))throw new I("INVALID_ARGS","open <app> <url> requires a valid URL target");return await n.open(t,{activity:i?.activity,appBundleId:i?.appBundleId,url:a}),{app:t,url:a}}return await n.open(t,{activity:i?.activity,appBundleId:i?.appBundleId}),{app:t}}case"close":{let e=r[0];if(!e)return{closed:"session"};return await n.close(e),{app:e}}case"press":{let t,[a,o]=r.map(Number);if(Number.isNaN(a)||Number.isNaN(o))throw new I("INVALID_ARGS","press requires x y");let s=oE(i);if("primary"!==s){let t=ok({commandLabel:"click",platform:e.platform,button:s,count:i?.count,intervalMs:i?.intervalMs,holdMs:i?.holdMs,jitterPx:i?.jitterPx,doubleTap:i?.doubleTap});if(t)throw t;return await tE(e,{command:"mouseClick",x:a,y:o,button:s,appBundleId:i?.appBundleId},{verbose:i?.verbose,logPath:i?.logPath,traceLogPath:i?.traceLogPath,requestId:i?.requestId}),{x:a,y:o,button:s}}let l=oO(i?.count??1,"count",1,200),d=oO(i?.intervalMs??0,"interval-ms",0,1e4),u=oO(i?.holdMs??0,"hold-ms",0,1e4),c=oO(i?.jitterPx??0,"jitter-px",0,100),p=i?.doubleTap===!0;if(p&&u>0)throw new I("INVALID_ARGS","double-tap cannot be combined with hold-ms");if(p&&c>0)throw new I("INVALID_ARGS","double-tap cannot be combined with jitter-px");if(("ios"===e.platform||"macos"===e.platform)&&l>1&&0===u&&0===c){let t=await tE(e,{command:"tapSeries",x:a,y:o,count:l,intervalMs:d,doubleTap:p,appBundleId:i?.appBundleId},{verbose:i?.verbose,logPath:i?.logPath,traceLogPath:i?.traceLogPath,requestId:i?.requestId});return{x:a,y:o,count:l,intervalMs:d,holdMs:u,jitterPx:c,doubleTap:p,timingMode:"runner-series",...t}}return await oL(l,d,async e=>{let[r,i]=function(e,t){if(t<=0)return[0,0];let[r,a]=ox[e%ox.length];return[r*t,a*t]}(e,c),s=a+r,l=o+i;if(p){t??=await n.doubleTap(s,l)??void 0;return}u>0?t??=await n.longPress(s,l,u)??void 0:t??=await n.tap(s,l)??void 0}),{x:a,y:o,count:l,intervalMs:d,holdMs:u,jitterPx:c,doubleTap:p,...t}}case"swipe":{let t=Number(r[0]),a=Number(r[1]),o=Number(r[2]),s=Number(r[3]);if([t,a,o,s].some(Number.isNaN))throw new I("INVALID_ARGS","swipe requires x1 y1 x2 y2 [durationMs]");let l=oO(r[4]?Number(r[4]):250,"durationMs",16,1e4),d="ios"===e.platform?Math.min(60,Math.max(16,Math.round(l))):l,u=oO(i?.count??1,"count",1,200),c=oO(i?.pauseMs??0,"pause-ms",0,1e4),p=i?.pattern??"one-way";if("one-way"!==p&&"ping-pong"!==p)throw new I("INVALID_ARGS",`Invalid pattern: ${p}`);if(("ios"===e.platform||"macos"===e.platform)&&u>1){let r=await tE(e,{command:"dragSeries",x:t,y:a,x2:o,y2:s,durationMs:d,count:u,pauseMs:c,pattern:p,appBundleId:i?.appBundleId},{verbose:i?.verbose,logPath:i?.logPath,traceLogPath:i?.traceLogPath,requestId:i?.requestId});return{x1:t,y1:a,x2:o,y2:s,durationMs:l,effectiveDurationMs:d,timingMode:"runner-series",count:u,pauseMs:c,pattern:p,...r}}return await oL(u,c,async e=>{"ping-pong"===p&&e%2==1?await n.swipe(o,s,t,a,d):await n.swipe(t,a,o,s,d)}),{x1:t,y1:a,x2:o,y2:s,durationMs:l,effectiveDurationMs:d,timingMode:"ios"===e.platform?"safe-normalized":"direct",count:u,pauseMs:c,pattern:p}}case"longpress":{let e=Number(r[0]),t=Number(r[1]),a=r[2]?Number(r[2]):void 0;if(Number.isNaN(e)||Number.isNaN(t))throw new I("INVALID_ARGS","longpress requires x y [durationMs]");return await n.longPress(e,t,a),{x:e,y:t,durationMs:a}}case"focus":{let[e,t]=r.map(Number);if(Number.isNaN(e)||Number.isNaN(t))throw new I("INVALID_ARGS","focus requires x y");return await n.focus(e,t),{x:e,y:t}}case"type":{let e=r.join(" ");if(!e)throw new I("INVALID_ARGS","type requires text");return await n.type(e),{text:e}}case"fill":{let e=Number(r[0]),t=Number(r[1]),a=r.slice(2).join(" ");if(Number.isNaN(e)||Number.isNaN(t)||!a)throw new I("INVALID_ARGS","fill requires x y text");return await n.fill(e,t,a),{x:e,y:t,text:a}}case"scroll":{let e=r[0],t=r[1]?Number(r[1]):void 0;if(!e)throw new I("INVALID_ARGS","scroll requires direction");let a=await n.scroll(e,t);return{direction:e,amount:t,...a}}case"scrollintoview":{let e=r.join(" ").trim();if(!e)throw new I("INVALID_ARGS","scrollintoview requires text");let t=await n.scrollIntoView(e);if(t?.attempts)return{text:e,attempts:t.attempts};return{text:e}}case"pinch":{if("android"===e.platform)throw new I("UNSUPPORTED_OPERATION","Android pinch is not supported in current adb backend; requires instrumentation-based backend.");let t=Number(r[0]),a=r[1]?Number(r[1]):void 0,n=r[2]?Number(r[2]):void 0;if(Number.isNaN(t)||t<=0)throw new I("INVALID_ARGS","pinch requires scale > 0");return await tE(e,{command:"pinch",scale:t,x:a,y:n,appBundleId:i?.appBundleId},{verbose:i?.verbose,logPath:i?.logPath,traceLogPath:i?.traceLogPath,requestId:i?.requestId}),{scale:t,x:a,y:n}}case"trigger-app-event":{let{eventName:t,payload:a}=function(e){let t=e[0]?.trim(),r=e[1]?.trim();if(!t)throw new I("INVALID_ARGS","trigger-app-event requires <event> [payloadJson]");if(!oM.test(t))throw new I("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 I("INVALID_ARGS","trigger-app-event accepts at most two arguments: <event> [payloadJson]");let a=function(e,t){if(e)try{let r=JSON.parse(e);if(!r||"object"!=typeof r||Array.isArray(r))throw new I("INVALID_ARGS",`trigger-app-event payload for "${t}" must be a JSON object`);let a=JSON.stringify(r);if(Buffer.byteLength(a,"utf8")>8192)throw new I("INVALID_ARGS",`trigger-app-event payload for "${t}" exceeds 8192 bytes`);return r}catch(t){if(t instanceof I)throw t;throw new I("INVALID_ARGS",`Invalid trigger-app-event payload JSON: ${e}`)}}(r,t);return{eventName:t,payload:a}}(r),o=function(e,t,r){var a;let i,n=(i=("ios"===(a=e)?process.env.AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE:"macos"===a?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(!n)throw new I("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=n.replaceAll("{event}",encodeURIComponent(t)).replaceAll("{payload}",encodeURIComponent(o)).replaceAll("{platform}",encodeURIComponent(e));if(s.length>4096)throw new I("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,t,a);return await n.open(o,{appBundleId:i?.appBundleId}),{event:t,eventUrl:o,transport:"deep-link"}}case"screenshot":{let e=r[0]??a??`./screenshot-${Date.now()}.png`;return await P.mkdir(o.dirname(e),{recursive:!0}),await n.screenshot(e,i?.appBundleId),{path:e}}case"back":return await n.back(),{action:"back"};case"home":return await n.home(),{action:"home"};case"app-switcher":return await n.appSwitcher(),{action:"app-switcher"};case"clipboard":{let e=(r[0]??"").toLowerCase();if("read"!==e&&"write"!==e)throw new I("INVALID_ARGS","clipboard requires a subcommand: read or write");if("read"===e){if(1!==r.length)throw new I("INVALID_ARGS","clipboard read does not accept additional arguments");return{action:e,text:await n.readClipboard()}}if(r.length<2)throw new I("INVALID_ARGS",'clipboard write requires text (use "" to clear clipboard)');let t=r.slice(1).join(" ");return await n.writeClipboard(t),{action:e,textLength:Array.from(t).length}}case"keyboard":{if("android"!==e.platform)throw new I("UNSUPPORTED_OPERATION","keyboard is currently supported only on Android");let t=(r[0]??"status").toLowerCase();if("status"!==t&&"get"!==t&&"dismiss"!==t)throw new I("INVALID_ARGS","keyboard requires a subcommand: status, get, or dismiss");if(r.length>1)throw new I("INVALID_ARGS","keyboard accepts at most one subcommand argument");if("dismiss"===t){let t=await iE(e);return{platform:"android",action:"dismiss",attempts:t.attempts,wasVisible:t.wasVisible,dismissed:t.dismissed,visible:t.visible,inputType:t.inputType,type:t.type}}let a=await iD(e);return{platform:"android",action:"status",visible:a.visible,inputType:a.inputType,type:a.type}}case"settings":{let[t,a,o,s,l]=r,d="permission"===t?{permissionTarget:o,permissionMode:s}:void 0;C({level:"debug",phase:"settings_apply",data:{setting:t,state:a,target:o,mode:s,platform:e.platform}});let u=await n.setSetting(t,a,l??i?.appBundleId,d);return u&&"object"==typeof u?{setting:t,state:a,...u}:{setting:t,state:a}}case"push":{let t=r[0]?.trim(),a=r[1]?.trim();if(!t||!a)throw new I("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>");let i=await oR(a);if("ios"===e.platform)return await om(e,t,i),{platform:"ios",bundleId:t};let n=await iB(e,t,i);return{platform:"android",package:t,action:n.action,extrasCount:n.extrasCount}}case"snapshot":{if("android"!==e.platform){let t=await O("snapshot_capture",async()=>await tE(e,{command:"snapshot",appBundleId:i?.appBundleId,interactiveOnly:i?.snapshotInteractiveOnly,compact:i?.snapshotCompact,depth:i?.snapshotDepth,scope:i?.snapshotScope,raw:i?.snapshotRaw},{verbose:i?.verbose,logPath:i?.logPath,traceLogPath:i?.traceLogPath,requestId:i?.requestId}),{backend:"xctest"}),r=t.nodes??[];if(0===r.length&&"simulator"===e.kind)throw new I("COMMAND_FAILED","XCTest snapshot returned 0 nodes on iOS simulator.");return{nodes:r,truncated:t.truncated??!1,backend:"xctest"}}let t=await O("snapshot_capture",async()=>await it(e,{interactiveOnly:i?.snapshotInteractiveOnly,compact:i?.snapshotCompact,depth:i?.snapshotDepth,scope:i?.snapshotScope,raw:i?.snapshotRaw}),{backend:"android"});return{nodes:t.nodes??[],truncated:t.truncated??!1,backend:"android"}}case"read":{let[t,a]=r.map(Number);if(Number.isNaN(t)||Number.isNaN(a))throw new I("INVALID_ARGS","read requires x y");if("android"===e.platform)return{action:"read",text:await i_(e,t,a)??""};if("macos"===e.platform&&i?.surface&&"app"!==i.surface)return{action:"read",text:(await nk(t,a,{bundleId:i.appBundleId,surface:i.surface})).text};let n=await tE(e,{command:"readText",x:t,y:a,appBundleId:i?.appBundleId},{verbose:i?.verbose,logPath:i?.logPath,traceLogPath:i?.traceLogPath,requestId:i?.requestId});return{action:"read",text:"string"==typeof n.text?n.text:"string"==typeof n.message?n.message:""}}default:throw new I("INVALID_ARGS",`Unknown command: ${t}`)}},{command:t,platform:e.platform})}let o4=e=>"macos"!==e.platform,o8={alert:{apple:{simulator:!0,device:!0},android:{},supports:e=>"macos"===e.platform||"simulator"===e.kind},pinch:{apple:{simulator:!0},android:{}},"app-switcher":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:o4},apps:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},back:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},boot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:o4},click:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},clipboard:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind},keyboard:{apple:{},android:{emulator:!0,device:!0,unknown:!0}},close:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},fill:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},diff:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},find:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},focus:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},get:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},is:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},home:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:o4},logs:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},network:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},longpress:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},open:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},perf:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},install:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:o4},"install-from-source":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:o4},reinstall:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:o4},press:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},push:{apple:{simulator:!0},android:{emulator:!0,device:!0,unknown:!0},supports:o4},record:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},screenshot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},scroll:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},scrollintoview:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},swipe:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},settings:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind},snapshot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},"trigger-app-event":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},type:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}},wait:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0}}};function o5(e,t){let r=o8[e];if(!r)return!0;let a=e1(t.platform)?r.apple:r.android;return!!a&&(!r.supports||!!r.supports(t))&&!0===a[t.kind??"unknown"]}function o6(e,t,r,a,i){return{requestId:i??M().requestId,appBundleId:r,activity:t?.activity,verbose:t?.verbose,logPath:e,traceLogPath:a,snapshotInteractiveOnly:t?.snapshotInteractiveOnly,snapshotCompact:t?.snapshotCompact,snapshotDepth:t?.snapshotDepth,snapshotScope:t?.snapshotScope,snapshotRaw:t?.snapshotRaw,count:t?.count,intervalMs:t?.intervalMs,holdMs:t?.holdMs,jitterPx:t?.jitterPx,doubleTap:t?.doubleTap,clickButton:oE(t),pauseMs:t?.pauseMs,pattern:t?.pattern}}let o9=ek(process.env.AGENT_DEVICE_IOS_DEVICE_READY_TIMEOUT_MS,15e3,1e3);async function o7(e){if("ios"===e.platform){if("simulator"===e.kind){let{ensureBootedSimulator:t}=await Promise.resolve().then(()=>({ensureBootedSimulator:nt}));await t(e);return}if("device"===e.kind)return void await se(e.id)}if("android"===e.platform){let{waitForAndroidBoot:t}=await Promise.resolve().then(()=>({waitForAndroidBoot:ar}));await t(e.id)}}async function se(e){let t=o.join(V.tmpdir(),`agent-device-ready-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),r=Math.max(1,Math.ceil(o9/1e3));try{let a=await m("xcrun",["devicectl","device","info","details","--device",e,"--json-output",t,"--timeout",String(r)],{allowFailure:!0,timeoutMs:o9+3e3}),i=String(a.stdout??""),n=String(a.stderr??""),o=await st(t);if(0===a.exitCode){if(!o.parsed)throw new I("COMMAND_FAILED","iOS device readiness probe failed",{kind:"probe_inconclusive",deviceId:e,stdout:i,stderr:n,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 I("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 I("COMMAND_FAILED","iOS device is not ready for automation",{kind:"not_ready",deviceId:e,stdout:i,stderr:n,exitCode:a.exitCode,tunnelState:o?.tunnelState,hint:sr(i,n)})}catch(t){if(t instanceof I&&"COMMAND_FAILED"===t.code){if("not_ready"===("string"==typeof t.details?.kind?t.details.kind:""))throw t;let r=t.details??{},a=String(r.stdout??""),i=String(r.stderr??""),n=Number(r.timeoutMs??o9),o=`CoreDevice did not respond within ${n}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;throw new I("COMMAND_FAILED","iOS device readiness probe failed",{deviceId:e,cause:t.message,timeoutMs:n,stdout:a,stderr:i,hint:a||i?sr(a,i):o},t)}throw new I("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 P.rm(t,{force:!0}).catch(()=>{})}}async function st(e){try{let t=await P.readFile(e,"utf8"),r=JSON.parse(t),a=function(e){let t=e?.result;if(!t||"object"!=typeof t)return{};let r=t.connectionProperties?.tunnelState,a=t.device?.connectionProperties?.tunnelState,i="string"==typeof r?r:"string"==typeof a?a:void 0;return i?{tunnelState:i}:{}}(r);return{parsed:!0,tunnelState:a.tunnelState}}catch{return{parsed:!1}}}function sr(e,t){let r=i5(e,t);return r||(`${e}
33
+ ${t}`.toLowerCase().includes("timed out waiting for all destinations")?"Xcode destination did not become available in time. Keep device unlocked and retry.":i8)}function sa(e){return e.map((e,t)=>({...e,ref:`e${t+1}`}))}function si(e){let t=e.trim();return t.startsWith("@")?t.slice(1)||null:t.startsWith("e")?t:null}function sn(e,t){return e.find(e=>e.ref===t)??null}function so(e){return{x:Math.round(e.x+e.width/2),y:Math.round(e.y+e.height/2)}}function ss(e,t){let r=t.toLowerCase();return e.find(e=>{let t=(e.label??"").toLowerCase(),a=(e.value??"").toLowerCase(),i=(e.identifier??"").toLowerCase();return t.includes(r)||a.includes(r)||i.includes(r)})??null}function sl(e,t){let r=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);return r&&sd(r)?r:function(e,t){if(!e.rect)return;let r=e.rect.y+e.rect.height/2,a=null;for(let e of t){if(!e.rect)continue;let t=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);if(!t||!sd(t))continue;let i=Math.abs(e.rect.y+e.rect.height/2-r);(!a||i<a.distance)&&(a={label:t,distance:i})}return a?.label}(e,t)??(r&&sd(r)?r:void 0)}function sd(e){let t=e.trim();return!(!t||/^(true|false)$/i.test(t)||/^\d+$/.test(t))}function su(e){let t=[],r=[];for(let a of e){let e=a.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let i=sc(a.type??""),n=[a.label,a.value,a.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0),o=!!n&&sd(n);if(("group"===i||"ioscontentgroup"===i)&&!o){t.push(e);continue}let s=Math.max(0,e-t.length);r.push({...a,depth:s})}return r}function sc(e){let t=e.trim().replace(/XCUIElementType/gi,"");t.startsWith("AX")&&(t=t.slice(2));let r=Math.max((t=t.toLowerCase()).lastIndexOf("."),t.lastIndexOf("/"));return -1!==r&&(t=t.slice(r+1)),t}function sp(e,t){let r=sc(e);return!r||("android"===t?r.includes("edittext")||r.includes("autocompletetextview"):r.includes("textfield")||r.includes("securetextfield")||r.includes("searchfield")||r.includes("textview")||r.includes("textarea")||"search"===r)}function sf(e){return[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0)[0]??""}let sm=new Set(["id","role","text","label","value"]),sh=new Set(["visible","hidden","editable","selected","enabled","hittable"]),sw=new Set([...sm,...sh]);function sg(e){let t=e.trim();if(!t)throw new I("INVALID_ARGS","Selector expression cannot be empty");let r=function(e){let t=[],r="",a=null;for(let i=0;i<e.length;i+=1){let n=e[i];if(('"'===n||"'"===n)&&!sS(e,i)){a?a===n&&(a=null):a=n,r+=n;continue}if(!a&&"|"===n&&"|"===e[i+1]){let a=r.trim();if(!a)throw new I("INVALID_ARGS",`Invalid selector fallback expression: ${e}`);t.push(a),r="",i+=1;continue}r+=n}let i=r.trim();if(!i)throw new I("INVALID_ARGS",`Invalid selector fallback expression: ${e}`);return t.push(i),t}(t);if(0===r.length)throw new I("INVALID_ARGS","Selector expression cannot be empty");return{raw:t,selectors:r.map(e=>(function(e){let t=e.trim();if(!t)throw new I("INVALID_ARGS","Selector segment cannot be empty");let r=function(e){let t=[],r="",a=null;for(let i=0;i<e.length;i+=1){let n=e[i];if(('"'===n||"'"===n)&&!sS(e,i)){a?a===n&&(a=null):a=n,r+=n;continue}if(!a&&/\s/.test(n)){r.trim().length>0&&t.push(r.trim()),r="";continue}r+=n}if(a)throw new I("INVALID_ARGS",`Unclosed quote in selector: ${e}`);return r.trim().length>0&&t.push(r.trim()),t}(t);if(0===r.length)throw new I("INVALID_ARGS",`Invalid selector segment: ${e}`);return{raw:t,terms:r.map(sy)}})(e))}}function sv(e){try{return sg(e)}catch{return null}}function sI(e,t={}){if(0===e.length)return null;let r=t.preferTrailingValue??!1,a=0,i=[];for(;a<e.length&&function(e){let t=e.trim();if(!t)return!1;if("||"===t)return!0;let r=t.indexOf("=");if(-1!==r){let e=t.slice(0,r).trim().toLowerCase();return sw.has(e)}return sw.has(t.toLowerCase())}(e[a]);){a+=1;let t=e.slice(0,a).join(" ").trim();t&&sv(t)&&i.push(a)}if(0===i.length)return null;let n=i[i.length-1];if(r){for(let t=i.length-1;t>=0;t-=1)if(i[t]<e.length){n=i[t];break}}let o=e.slice(0,n).join(" ").trim();return o?{selectorExpression:o,rest:e.slice(n)}:null}function sA(e){let t=e[0]??"",r=sI(e.slice(1),{preferTrailingValue:"text"===t});return{predicate:t,split:r}}function sy(e){let t=e.trim();if(!t)throw new I("INVALID_ARGS","Empty selector term");let r=t.indexOf("=");if(-1===r){let r=t.toLowerCase();if(!sh.has(r))throw new I("INVALID_ARGS",`Invalid selector term "${e}", expected key=value`);return{key:r,value:!0}}let a=t.slice(0,r).trim().toLowerCase(),i=t.slice(r+1).trim();if(!sw.has(a))throw new I("INVALID_ARGS",`Unknown selector key: ${a}`);if(!i)throw new I("INVALID_ARGS",`Missing selector value for key: ${a}`);if(sh.has(a)){let e,t="true"===(e=sb(i).toLowerCase())||"false"!==e&&null;if(null===t)throw new I("INVALID_ARGS",`Invalid boolean value for ${a}: ${i}`);return{key:a,value:t}}return{key:a,value:sb(i)}}function sb(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/\\(["'])/g,"$1"):t}function sS(e,t){let r=0;for(let a=t-1;a>=0&&"\\"===e[a];a-=1)r+=1;return r%2==1}function s_(e,t,r){return t.terms.every(t=>(function(e,t,r){switch(t.key){case"id":return sE(e.identifier,String(t.value));case"role":var a,i;return a=e.type,i=String(t.value),function(e){return sc(e)}(a??"")===function(e){return sc(e)}(i);case"label":return sE(e.label,String(t.value));case"value":return sE(e.value,String(t.value));case"text":{let r=sk(String(t.value));return sk(sf(e))===r}case"visible":return sN(e)===!!t.value;case"hidden":return!sN(e)==!!t.value;case"editable":return sD(e,r)===!!t.value;case"selected":return!0===e.selected==!!t.value;case"enabled":return!1!==e.enabled==!!t.value;case"hittable":return!0===e.hittable==!!t.value;default:return!1}})(e,t,r))}function sN(e){return!0===e.hittable||!!e.rect&&e.rect.width>0&&e.rect.height>0}function sD(e,t){return sp(e.type??"",t)&&!1!==e.enabled}function sE(e,t){return sk(e??"")===sk(t)}function sk(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function sM(e,t,r){let a=r.requireRect??!1,i=r.requireUnique??!0,n=r.disambiguateAmbiguous??!1,o=[];for(let s=0;s<t.selectors.length;s+=1){let l=t.selectors[s],d=function(e,t,r){let a=0,i=null,n=null,o=!1;for(let s of e){if(r.requireRect&&!s.rect||!s_(s,t,r.platform))continue;if(a+=1,i||(i=s),!n){n=s;continue}let e=function(e,t){let r=e.depth??0,a=t.depth??0;if(r!==a)return r>a?1:-1;let i=sL(e),n=sL(t);return i!==n?i<n?1:-1:0}(s,n);if(e>0){n=s,o=!1;continue}0===e&&(o=!0)}return{count:a,firstNode:i,disambiguated:o?null:n}}(e,l,{platform:r.platform,requireRect:a});if(o.push({selector:l.raw,matches:d.count}),0!==d.count&&d.firstNode){if(i&&1!==d.count){if(!n)continue;let e=d.disambiguated;if(!e)continue;return{node:e,selector:l,selectorIndex:s,matches:d.count,diagnostics:o}}return{node:d.firstNode,selector:l,selectorIndex:s,matches:d.count,diagnostics:o}}}return null}function sx(e,t,r){let a=r.requireRect??!1,i=[];for(let n=0;n<t.selectors.length;n+=1){let o=t.selectors[n],s=function(e,t,r){let a=0;for(let i of e)(!r.requireRect||i.rect)&&s_(i,t,r.platform)&&(a+=1);return a}(e,o,{platform:r.platform,requireRect:a});if(i.push({selector:o.raw,matches:s}),s>0)return{selectorIndex:n,selector:o,matches:s,diagnostics:i}}return null}function sO(e,t,r){let a=r.unique??!0;if(0===t.length)return`Selector did not match: ${e.raw}`;let i=t.map(e=>`${e.selector} -> ${e.matches}`).join(", ");return a?`Selector did not resolve uniquely (${i})`:`Selector did not match (${i})`}function sL(e){return e.rect?e.rect.width*e.rect.height:1/0}function sC(e,t,r={}){let a=[],i=sc(e.type??""),n=sR(e.identifier),o=sR(e.label),s=sR(e.value),l=sR(sf(e)),d="fill"===r.action;n&&a.push(`id=${sP(n)}`),i&&o&&a.push(d?`role=${sP(i)} label=${sP(o)} editable=true`:`role=${sP(i)} label=${sP(o)}`),o&&a.push(d?`label=${sP(o)} editable=true`:`label=${sP(o)}`),s&&a.push(d?`value=${sP(s)} editable=true`:`value=${sP(s)}`),l&&l!==o&&l!==s&&a.push(d?`text=${sP(l)} editable=true`:`text=${sP(l)}`),i&&d&&!a.some(e=>e.includes("editable=true"))&&a.push(`role=${sP(i)} editable=true`);let u=tx(a);return 0===u.length&&i&&u.push(d?`role=${sP(i)} editable=true`:`role=${sP(i)}`),0===u.length&&sN(e)&&u.push("visible=true"),u}function sP(e){return JSON.stringify(e)}function sR(e){if(!e)return null;let t=e.trim();return t||null}let sT=RegExp("\\b(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b","i"),s$=/https?:\/\/[^\s"'<>\])]+/i,sF=[/\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 sU(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 sV(e,t,r){if(t){for(let e of r)if(void 0!==t[e])return sG(t[e])}for(let t of r){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=RegExp(`\\b${r}["'=: ]+(.+)$`,"i").exec(e);if(a?.[1])return a[1].trim()}}function sG(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}}function sB(e,t){return e.length<=t?e:`${e.slice(0,t)}...<truncated>`}function sj(e,t,r,a){return void 0!==e&&Number.isInteger(e)?Math.max(r,Math.min(a,e)):t}let sq="shared_prefs/ReactNativeDevPrefs.xml",sH="debug_http_host",sW="dev_server_https",sz="RCT_jsLocation",sJ="RCT_packager_scheme",sX="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.",sK='<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n</map>\n';function sY(e){return void 0!==sZ(e)}function sZ(e){if(!e)return;let t=le(e.metroHost),r=lr(e.metroPort),a="http",i=le(e.bundleUrl);if(i){var n;let e;try{e=new A(i)}catch(e){throw new I("INVALID_ARGS",`Invalid runtime bundle URL: ${i}`,{},e)}("http:"===e.protocol||"https:"===e.protocol)&&(t??=le(e.hostname),r??=lr(e.port.length>0?Number(e.port):"https:"===(n=e.protocol)?443:"http:"===n?80:void 0),a="https:"===e.protocol?"https":"http")}if(t&&r)return{host:t,port:r,scheme:a}}async function sQ(e){let{device:t,appId:r,runtime:a}=e;if(!r)return;let i=sZ(a);if(i){if("android"===t.platform)return void await s1(t,r,i);"ios"===t.platform&&"simulator"===t.kind&&await s8(t,r,i)}}async function s0(e){let{device:t,appId:r}=e;if(r){if("android"===t.platform)return void await s2(t,r);"ios"===t.platform&&"simulator"===t.kind&&await s5(t,r)}}async function s1(e,t,r){var a,i,n,o,s,l;let d,u;lt(t);let c=(a=await s3(e,t),i=sH,n=`${r.host}:${r.port}`,d=` <string name="${la(i)}">${la(n)}</string>`,s9(s7(a,i),d));o=c,s=sW,l="https"===r.scheme,u=` <boolean name="${la(s)}" value="${l?"true":"false"}" />`,c=s9(s7(o,s),u),await s4(e,t,c)}async function s2(e,t){lt(t);let r=await s3(e,t),a=s7(r,sH),i=s7(a,sW);i!==r&&await s4(e,t,i)}async function s3(e,t){let r=await m("adb",rR(e,["shell","run-as",t,"cat",sq]),{allowFailure:!0});return 0!==r.exitCode?sK:s6(r.stdout)}async function s4(e,t,r){let a=rR(e,["shell","run-as",t,"id"]),i=await m("adb",a,{allowFailure:!0});if(0!==i.exitCode){let e=li(i.stdout,i.stderr);throw new I("COMMAND_FAILED",e?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,{package:t,cmd:"adb",args:a,stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,hint:e?sX:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await m("adb",rR(e,["shell","run-as",t,"mkdir","-p","shared_prefs"])),await m("adb",rR(e,["shell","run-as",t,"tee",sq]),{stdin:r.trimEnd()})}catch(a){let e=w(a);if("TOOL_MISSING"===e.code)throw e;let r=li("string"==typeof e.details?.stdout?e.details.stdout:"","string"==typeof e.details?.stderr?e.details.stderr:"");throw new I("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?sX:"adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command."},e)}}async function s8(e,t,r){await m("xcrun",e$(e,["spawn",e.id,"defaults","write",t,sz,"-string",`${r.host}:${r.port}`])),await m("xcrun",e$(e,["spawn",e.id,"defaults","write",t,sJ,"-string",r.scheme]))}async function s5(e,t){await m("xcrun",e$(e,["spawn",e.id,"defaults","delete",t,sz]),{allowFailure:!0}),await m("xcrun",e$(e,["spawn",e.id,"defaults","delete",t,sJ]),{allowFailure:!0})}function s6(e){let t=e.trim();return t.includes("<map")&&t.includes("</map>")?`${t}
34
+ `:sK}function s9(e,t){return s6(e).replace("</map>",`${t}
35
+ </map>`)}function s7(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return s6(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 le(e){let t=e?.trim();return t&&t.length>0?t:void 0}function lt(e){if("binary"!==an(e))return;let t=ao(e);throw new I("INVALID_ARGS",t,{package:e,hint:t})}function lr(e){if(Number.isInteger(e)&&!(e<=0)&&!(e>65535))return e}function la(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function li(e,t){let r=`${e}
36
+ ${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))}function ln(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=/^\d+$/.test(t??""),a=sI(r?e.slice(0,-1):e.slice());return!a||a.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:a.selectorExpression,selectorTimeout:r?t:null}}function lo(e){return!!e&&!Number.isNaN(Number(e))}let ls=ek(process.env.AGENT_DEVICE_INSTALL_SOURCE_RETAIN_TTL_MS,9e5,5e3),ll=new Map;async function ld(e){let t=await n.mkdtemp(o.join(V.tmpdir(),"agent-device-materialized-"));try{let r=await lp(e.installablePath,o.join(t,"installable")),a=e.archivePath?await lp(e.archivePath,o.join(t,"archive")):void 0,i=f.randomUUID(),n=e.ttlMs??ls,s=Date.now()+n,l=setTimeout(()=>{lu(i)},n);return ll.set(i,{rootPath:t,installablePath:r,archivePath:a,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:s,timer:l}),{materializationId:i,installablePath:r,...a?{archivePath:a}:{},expiresAt:new Date(s).toISOString()}}catch(e){throw await n.rm(t,{recursive:!0,force:!0}),e}}async function lu(e,t){let r=ll.get(e);if(!r)throw new I("INVALID_ARGS",`Materialized paths not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new I("UNAUTHORIZED","Materialized paths belong to a different tenant");clearTimeout(r.timer),ll.delete(e),await n.rm(r.rootPath,{recursive:!0,force:!0})}async function lc(e){let t=Array.from(ll.entries()).filter(([,t])=>t.sessionName===e).map(([e])=>e);await Promise.all(t.map(async e=>{await lu(e)}))}async function lp(e,t){let r=await n.stat(e);await n.mkdir(t,{recursive:!0});let a=o.join(t,o.basename(e));return r.isDirectory()?await n.cp(e,a,{recursive:!0}):await n.copyFile(e,a),a}async function lf(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 I("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await o7(e.session.device),e.session.device}if(!r)throw new I("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let a=await o2(e.flags??{});return await o7(a),a}async function lm(e){let{req:t,sessionName:r,sessionStore:a,deps:i}=e,n=a.get(r);try{let e,o,s,l=(o=function(e){let t=e.meta?.installSource;if(!t)throw new I("INVALID_ARGS","install_from_source requires a source payload");if("url"===t.kind){if(!t.url||0===t.url.trim().length)throw new I("INVALID_ARGS","install_from_source url source requires a non-empty url");return t}if(!t.path||0===t.path.trim().length)throw new I("INVALID_ARGS","install_from_source path source requires a non-empty path");return t}(t),(s=t.meta?.uploadedArtifactId)&&"path"===o.kind?{source:{kind:"path",path:rr(s,t.meta?.tenantId)},cleanup:()=>{ra(s)}}:{source:o,cleanup:()=>{}}),d=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 I("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),u=await (i?.resolveInstallDevice??lf)({session:n,flags:t.flags});if(!o5("install",u))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"install_from_source is not supported on this device"}};let c=(i?.getRequestSignal??eI)(t.meta?.requestId);if("ios"===u.platform){let e,o=i?.installIosInstallablePath??(await Promise.resolve().then(()=>({closeIosApp:os,ensureBootedSimulator:nt,installIosApp:od,installIosInstallablePath:oc,listIosApps:ow,listSimulatorApps:og,openIosApp:on,openIosDevice:oo,parseIosDeviceAppsPayload:i4,pushIosNotification:om,readIosClipboardText:op,reinstallIosApp:ou,resolveIosApp:oi,screenshotIos:nQ,setIosSetting:oh,uninstallIosApp:ol,writeIosClipboardText:of}))).installIosInstallablePath,s=i?.prepareIosInstallArtifact??(await Promise.resolve().then(()=>({prepareIosInstallArtifact:nn,readIosBundleInfo:no}))).prepareIosInstallArtifact,p=await s(l.source,{signal:c});try{if(d.enabled&&(e=await ld({archivePath:p.archivePath,installablePath:p.installablePath,tenantId:t.meta?.tenantId,sessionName:n?r:void 0,ttlMs:d.ttlMs})),await o(u,p.installablePath),!p.bundleId)throw new I("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");let i={...e?.archivePath?{archivePath:e.archivePath}:{},...e?{installablePath:e.installablePath}:{},bundleId:p.bundleId,...p.appName?{appName:p.appName}:{},launchTarget:p.bundleId,...e?{materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}};return n&&a.recordAction(n,{command:"install_source",positionals:[],flags:t.flags??{},result:i}),{ok:!0,data:i}}catch(r){throw e&&await lu(e.materializationId,t.meta?.tenantId).catch(()=>{}),r}finally{await p.cleanup(),l.cleanup()}}let p=i?.prepareAndroidInstallArtifact??(await Promise.resolve().then(()=>({prepareAndroidInstallArtifact:aE}))).prepareAndroidInstallArtifact,f=i?.installAndroidInstallablePathAndResolvePackageName??(await Promise.resolve().then(()=>({appSwitcherAndroid:ic,backAndroid:id,closeAndroidApp:aW,dismissAndroidKeyboard:iE,ensureAdb:rT,fillAndroid:iw,focusAndroid:ih,getAndroidAppState:aU,getAndroidKeyboardState:iD,getAndroidScreenSize:iI,homeAndroid:iu,inferAndroidAppName:aF,installAndroidApp:a3,installAndroidInstallablePath:a1,installAndroidInstallablePathAndResolvePackageName:a2,isAmStartError:aj,listAndroidApps:aP,longPressAndroid:ip,openAndroidApp:aG,openAndroidDevice:aH,parseAndroidLaunchComponent:aq,pressAndroid:is,pushAndroidNotification:iB,readAndroidClipboardText:ik,readAndroidTextAtPoint:i_,reinstallAndroidApp:a4,resolveAndroidApp:aC,screenshotAndroid:iH,scrollAndroid:ig,scrollIntoViewAndroid:iv,setAndroidSetting:iR,snapshotAndroid:it,swipeAndroid:il,typeAndroid:im,writeAndroidClipboardText:iM}))).installAndroidInstallablePathAndResolvePackageName,m=await p(l.source,{signal:c});try{d.enabled&&(e=await ld({archivePath:m.archivePath,installablePath:m.installablePath,tenantId:t.meta?.tenantId,sessionName:n?r:void 0,ttlMs:d.ttlMs}));let o=await f(u,m.installablePath,m.packageName);if(!o)throw new I("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let s=(i?.inferAndroidAppName??(await Promise.resolve().then(()=>({appSwitcherAndroid:ic,backAndroid:id,closeAndroidApp:aW,dismissAndroidKeyboard:iE,ensureAdb:rT,fillAndroid:iw,focusAndroid:ih,getAndroidAppState:aU,getAndroidKeyboardState:iD,getAndroidScreenSize:iI,homeAndroid:iu,inferAndroidAppName:aF,installAndroidApp:a3,installAndroidInstallablePath:a1,installAndroidInstallablePathAndResolvePackageName:a2,isAmStartError:aj,listAndroidApps:aP,longPressAndroid:ip,openAndroidApp:aG,openAndroidDevice:aH,parseAndroidLaunchComponent:aq,pressAndroid:is,pushAndroidNotification:iB,readAndroidClipboardText:ik,readAndroidTextAtPoint:i_,reinstallAndroidApp:a4,resolveAndroidApp:aC,screenshotAndroid:iH,scrollAndroid:ig,scrollIntoViewAndroid:iv,setAndroidSetting:iR,snapshotAndroid:it,swipeAndroid:il,typeAndroid:im,writeAndroidClipboardText:iM}))).inferAndroidAppName)(o),l={...e?.archivePath?{archivePath:e.archivePath}:{},...e?{installablePath:e.installablePath}:{},packageName:o,...s?{appName:s}:{},launchTarget:o,...e?{materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}};return n&&a.recordAction(n,{command:"install_source",positionals:[],flags:t.flags??{},result:l}),{ok:!0,data:l}}catch(r){throw e&&await lu(e.materializationId,t.meta?.tenantId).catch(()=>{}),r}finally{await m.cleanup(),l.cleanup()}}catch(e){return{ok:!1,error:N(e)}}}async function lh(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new I("INVALID_ARGS","release_materialized_paths requires a materializationId");return await lu(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:N(e)}}}async function lw(e){let t,r,a,{deviceName:i,runtime:n,simulatorSetPath:o,reuseExisting:s,boot:l,ensureReady:d}=e;if("darwin"!==process.platform)throw new I("UNSUPPORTED_PLATFORM","ensure-simulator is only available on macOS");let u={simulatorSetPath:o??void 0};if(s){let e=await lg({deviceName:i,runtime:n,simctlOpts:u});e?(t=e.udid,r=e.runtime,a=!1):(t=(await lv({deviceName:i,runtime:n,simctlOpts:u})).udid,r=await lI(t,u),a=!0)}else t=(await lv({deviceName:i,runtime:n,simctlOpts:u})).udid,r=await lI(t,u),a=!0;let c=!1;if(l){let e={platform:"ios",id:t,name:i,kind:"simulator",target:"mobile",...o?{simulatorSetPath:o}:{}};await d(e),c=!0}return{udid:t,device:i,runtime:r,created:a,booted:c}}async function lg(e){let{deviceName:t,runtime:r,simctlOpts:a}=e,i=await m("xcrun",eT(["list","devices","-j"],a),{allowFailure:!0,timeoutMs:iK});if(0!==i.exitCode)return null;try{let e=JSON.parse(String(i.stdout??""));for(let[a,i]of Object.entries(e.devices??{}))if(!r||lA(a).includes(lA(r))){for(let e of i)if(e.isAvailable&&e.name.toLowerCase()===t.toLowerCase())return{udid:e.udid,runtime:a}}return null}catch{return null}}async function lv(e){let{deviceName:t,runtime:r,simctlOpts:a}=e,i=r?["create",t,t,r]:["create",t,t],n=await m("xcrun",eT(i,a),{allowFailure:!0});if(0!==n.exitCode)throw new I("COMMAND_FAILED","Failed to create iOS simulator",{deviceName:t,runtime:r,stdout:String(n.stdout??""),stderr:String(n.stderr??""),exitCode:n.exitCode,hint:"Ensure the device type and runtime identifiers are valid. Run `xcrun simctl list devicetypes` and `xcrun simctl list runtimes` to see available options."});let o=String(n.stdout??"").trim();if(!o)throw new I("COMMAND_FAILED","simctl create returned no UDID",{deviceName:t,runtime:r,stdout:String(n.stdout??""),stderr:String(n.stderr??"")});return{udid:o}}async function lI(e,t){let r=await m("xcrun",eT(["list","devices","-j"],t),{allowFailure:!0,timeoutMs:iK});if(0!==r.exitCode)return"";try{let t=JSON.parse(String(r.stdout??""));for(let[r,a]of Object.entries(t.devices??{}))if(a.some(t=>t.udid===e))return r;return""}catch{return""}}function lA(e){return e.toLowerCase().replace(/[._-]/g,"")}let ly=ek(process.env.AGENT_DEVICE_IOS_SIMULATOR_POST_CLOSE_SETTLE_MS,300,0),lb=ek(process.env.AGENT_DEVICE_IOS_SIMULATOR_POST_OPEN_SETTLE_MS,300,0);function lS(e,t,r){return t||l_(r)?null:{ok:!1,error:{code:"INVALID_ARGS",message:`${e} requires an active session or an explicit device selector (e.g. --platform ios).`}}}function l_(e){return!!(e?.platform||e?.target||e?.device||e?.udid||e?.serial)}function lN(e){return"ios"===e.platform&&"simulator"===e.kind}async function lD(e,t){lN(e)&&!(t<=0)&&await new Promise(e=>setTimeout(e,t))}async function lE(e){let t=l_(e.flags)||!e.session?await e.resolveTargetDeviceFn(e.flags??{}):await lk(e.session.device,e.resolveTargetDeviceFn);return!1!==e.ensureReady&&await e.ensureReadyFn(t),t}async function lk(e,t){if("ios"!==e.platform||"simulator"!==e.kind||"darwin"!==process.platform)return e;let r={platform:"ios",target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await t(r)}catch(e){if(!(e instanceof I)||"DEVICE_NOT_FOUND"!==e.code)throw e}return await t({platform:"ios",target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function lM(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 lx=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function lO(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function lL(e){let t=e?.trim();return t&&t.length>0?t:void 0}function lC(e,t){if(void 0!==e){if("string"!=typeof e)throw new I("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return lL(e)}}function lP(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new I("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function lR(e){if("ios"===e||"android"===e)return e}function lT(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:a,device:i}=e,n=r.getRuntimeHints(a),o=function(e){let{runtime:t,sessionName:r,platform:a}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new I("INVALID_ARGS","open runtime must be an object.");let i=Object.keys(t).find(e=>!lx.includes(e));if(i)throw new I("INVALID_ARGS",`Invalid open runtime field: ${i}. Supported fields are ${lx.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new I("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new I("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,a),metroHost:lC(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new I("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return lP(e)}}(t.metroPort),bundleUrl:lC(t.bundleUrl,"bundleUrl"),launchUrl:lC(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:lR(i.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let a=e.getRuntimeHints(t);if(!a)return;let i=r?.platform,n=lR(i);if(a.platform&&r&&!n)throw new I("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${i}.`);if(a.platform&&n&&a.platform!==n)throw new I("INVALID_ARGS",`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${i}. Clear the runtime hints or use a different session.`);return n&&a.platform!==n?{...a,platform:n}:a}(r,a,i),previousRuntime:n,replacedStoredRuntime:!1}:{runtime:o&&lO(o)>0?o:void 0,previousRuntime:n,replacedStoredRuntime:!0}}(e)}}catch(t){let e=w(t);return{ok:!1,response:{ok:!1,error:{code:e.code,message:e.message,details:e.details}}}}}async function l$(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:i,clearRuntimeHints:n}=e;!t||!i?.appBundleId||!sY(r)||sY(a)||await n({device:i.device,appId:i.appBundleId})}async function lF(e){var t,r;let{req:a,sessionName:i,sessionStore:n,clearRuntimeHints:o=s0}=e,s=(a.positionals?.[0]??"show").toLowerCase(),l=n.get(i),d=n.getRuntimeHints(i);if(!["set","show","clear"].includes(s))return{ok:!1,error:{code:"INVALID_ARGS",message:"runtime requires set, show, or clear"}};if("clear"===s){sY(d)&&l?.appBundleId&&await o({device:l.device,appId:l.appBundleId});let e=n.clearRuntimeHints(i);return{ok:!0,data:{session:i,cleared:e}}}if("show"===s)return{ok:!0,data:{session:i,configured:!!d,runtime:d}};let u=lR(a.flags?.platform??d?.platform??l?.device.platform);if(!u)return{ok:!1,error:{code:"INVALID_ARGS",message:"runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first."}};if(l&&l.device.platform!==u)return{ok:!1,error:{code:"INVALID_ARGS",message:`runtime set targets ${u}, but session "${i}" is already bound to ${l.device.platform}.`}};let c={platform:(t=a.flags,r={platform:u,metroHost:lL(t?.metroHost),metroPort:lP(t?.metroPort),bundleUrl:lL(t?.bundleUrl),launchUrl:lL(t?.launchUrl)}).platform??d?.platform,metroHost:r.metroHost??d?.metroHost,metroPort:r.metroPort??d?.metroPort,bundleUrl:r.bundleUrl??d?.bundleUrl,launchUrl:r.launchUrl??d?.launchUrl};return 0===lO(c)?{ok:!1,error:{code:"INVALID_ARGS",message:"runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."}}:(n.setRuntimeHints(i,c),{ok:!0,data:{session:i,configured:!0,runtime:c}})}async function lU(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return rU(t)?"macos"===e.platform?void 0:"device"===e.kind?rV(r,t):void 0:await lV(e,t)}async function lV(e,t){try{let{resolveIosApp:r}=await Promise.resolve().then(()=>({resolveIosApp:oi}));return await r(e,t)}catch{return}}async function lG(e,t){if(!("android"!==e.platform||!t||rU(t)))try{let{resolveAndroidApp:r}=await Promise.resolve().then(()=>({resolveAndroidApp:aC})),a=await r(e,t);return"package"===a.type?a.value:void 0}catch{return}}async function lB(e,t,r,a){return await lU(e,t,r)??await a(e,t)??("android"===e.platform&&t&&rU(t)?r:void 0)}let lj="open-command-roundtrip",lq="Not implemented for this platform in this release.";function lH(e){let{device:t,surfaceFlag:r,openTarget:a,existingSurface:i}=e;if("macos"===t.platform&&!r)return i??"app";if("macos"!==t.platform){if(r)throw new I("INVALID_ARGS","surface is only supported on macOS");return"app"}let n=r?Y(r):"app";if("app"!==n&&a)throw new I("INVALID_ARGS",`open --surface ${n} does not accept an app target`);return n}async function lW(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await nS();return{appBundleId:t.bundleId,appName:t.appName}}async function lz(e){let{device:t,closeTarget:r,stopIosRunner:a,dispatch:i,outFlag:n,context:o,settleSimulator:s}=e;"android"!==t.platform&&await a(t.id),await i(t,"close",[r],n,o),await s(t,ly)}async function lJ(e){let{runtime:t,device:r,dispatch:a,req:i,logPath:n,appBundleId:o,traceLogPath:s,openPositionals:l}=e,d=t?.launchUrl;if(!d||0===l.length||l.length>1)return;let u=l[0]?.trim();!u||rU(u)||await a(r,"open",[d],i.flags?.out,{...o6(n,i.flags,o,s)})}async function lX(e){var t,r,a;let{req:i,sessionName:n,sessionStore:o,logPath:s,device:l,dispatch:d,applyRuntimeHints:u,stopIosRunner:c,settleSimulator:p,openTarget:f,openPositionals:m,appName:h,surface:w,appBundleId:g,runtime:v,existingSession:I}=e,A=i.flags?.relaunch===!0,y=I?.trace?.outPath;if(A&&f){let e=g??f;await lz({device:l,closeTarget:e,stopIosRunner:c,dispatch:d,outFlag:i.flags?.out,context:{...o6(s,i.flags,g??I?.appBundleId,y)},settleSimulator:p})}await u({device:l,appId:g,runtime:v});let b=Date.now();await d(l,"open",m,i.flags?.out,{...o6(s,i.flags,g)}),await lJ({runtime:v,device:l,dispatch:d,req:i,logPath:s,appBundleId:g,traceLogPath:y,openPositionals:m});let S=f?{durationMs:Math.max(0,Date.now()-b),measuredAt:new Date().toISOString(),method:lj,appTarget:f,appBundleId:g}:void 0;await p(l,lb);let _=function(e){let{existingSession:t,sessionName:r,device:a,surface:i,appBundleId:n,appName:o,saveScript:s}=e;return t?{...t,device:a,surface:i,appBundleId:n,appName:o,recordSession:t.recordSession||s,snapshot:void 0}:{name:r,device:a,createdAt:Date.now(),surface:i,appBundleId:n,appName:o,recordSession:s,actions:[]}}({existingSession:I,sessionName:n,device:l,surface:w,appBundleId:g,appName:h,saveScript:!!i.flags?.saveScript});void 0!==i.runtime&&(t=o,r=n,(a=v)&&(0===lO(a)?t.clearRuntimeHints(r):t.setRuntimeHints(r,a)));let N=function(e){let{sessionName:t,appName:r,appBundleId:a,surface:i,startup:n,device:o,runtime:s}=e,l={session:t};return l.surface=i,r&&(l.appName=r),a&&(l.appBundleId=a),n&&(l.startup=n),s&&lO(s)>0&&(l.runtime=s),o&&(l.platform=o.platform,l.target=o.target??"mobile",l.device=o.name,l.id=o.id,l.kind=o.kind,"android"===o.platform&&(l.serial=o.id)),o?.platform==="ios"&&(l.device_udid=o.id,l.ios_simulator_device_set=o.simulatorSetPath??null),l}({sessionName:n,appName:h,appBundleId:g,surface:w,startup:S,device:l,runtime:v});return o.recordAction(_,{command:"open",positionals:m,flags:i.flags??{},runtime:void 0!==i.runtime?v:void 0,result:N}),o.set(n,_),{ok:!0,data:N}}async function lK(e){let t,{req:r,sessionName:a,logPath:i,sessionStore:n,dispatch:o,ensureReady:s,resolveDevice:l,applyRuntimeHints:d=sQ,clearRuntimeHints:u=s0,stopIosRunner:c=tA,settleSimulator:p=lD,resolveAndroidPackageForOpen:f=lG}=e,m=r.flags?.relaunch===!0;if(n.has(a)){let e,t=n.get(a);if(!t)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:`Session "${a}" not found.`}};let h=r.positionals?.[0],w=h??(m?t.appName:void 0);try{e=lH({device:t.device,surfaceFlag:r.flags?.surface,openTarget:w,existingSurface:t.surface})}catch(e){return{ok:!1,error:{code:e instanceof I?e.code:"INVALID_ARGS",message:String(e.message)}}}if(!t||!w&&"app"===e)return m?{ok:!1,error:{code:"INVALID_ARGS",message:"open --relaunch requires an app name or an active session app."}}:{ok:!1,error:{code:"INVALID_ARGS",message:"Session already active. Close it first or pass a new --session name."}};if(m&&rU(w))return{ok:!1,error:{code:"INVALID_ARGS",message:"open --relaunch does not support URL targets."}};if(m&&"app"!==e)return{ok:!1,error:{code:"INVALID_ARGS",message:"open --relaunch is supported only for app surfaces."}};if(m&&"android"===t.device.platform&&"binary"===an(w))return{ok:!1,error:{code:"INVALID_ARGS",message:ao(w)}};let g=await lk(t.device,l);await s(g);let v=await lW(e),A=v.appBundleId??await lB(g,w,t.appBundleId,f),y=v.appName??w,b=lT({req:r,sessionStore:n,sessionName:a,device:g});if(!b.ok)return b.response;let{runtime:S,previousRuntime:_,replacedStoredRuntime:N}=b.data;await l$({replacedStoredRuntime:N,previousRuntime:_,runtime:S,session:t,clearRuntimeHints:u});let D=h?r.positionals??[]:w?[w]:[];return await lX({req:r,sessionName:a,sessionStore:n,logPath:i,device:g,dispatch:o,applyRuntimeHints:d,stopIosRunner:c,settleSimulator:p,openTarget:w,openPositionals:D,appName:y,surface:e,appBundleId:A,runtime:S,existingSession:t})}let h=r.positionals?.[0];if(m&&!h)return{ok:!1,error:{code:"INVALID_ARGS",message:"open --relaunch requires an app argument."}};if(m&&h&&rU(h))return{ok:!1,error:{code:"INVALID_ARGS",message:"open --relaunch does not support URL targets."}};let w=await l(r.flags??{});try{t=lH({device:w,surfaceFlag:r.flags?.surface,openTarget:h})}catch(e){return{ok:!1,error:{code:e instanceof I?e.code:"INVALID_ARGS",message:String(e.message)}}}if(m&&"app"!==t)return{ok:!1,error:{code:"INVALID_ARGS",message:"open --relaunch is supported only for app surfaces."}};if(m&&"android"===w.platform&&h&&"binary"===an(h))return{ok:!1,error:{code:"INVALID_ARGS",message:ao(h)}};let g=n.toArray().find(e=>e.device.id===w.id);if(g)return{ok:!1,error:{code:"DEVICE_IN_USE",message:`Device is already in use by session "${g.name}".`,details:{session:g.name,deviceId:w.id,deviceName:w.name}}};await s(w);let v=await lW(t),A=v.appBundleId??await lB(w,h,void 0,f),y=v.appName??h,b=lT({req:r,sessionStore:n,sessionName:a,device:w});if(!b.ok)return b.response;let{runtime:S}=b.data;return await lX({req:r,sessionName:a,sessionStore:n,logPath:i,device:w,dispatch:o,applyRuntimeHints:d,stopIosRunner:c,settleSimulator:p,openTarget:h,openPositionals:r.positionals??[],appName:y,surface:t,appBundleId:A,runtime:S})}async function lY(e){let t=await m("adb",["-s",e.id,"emu","kill"],{allowFailure:!0,timeoutMs:15e3});return{success:0===t.exitCode,exitCode:t.exitCode,stdout:String(t.stdout??""),stderr:String(t.stderr??"")}}async function lZ(e){let{device:t,shutdownRequested:r,shutdownSimulator:a,shutdownAndroidEmulator:i}=e;if(r&&(lN(t)||"android"===t.platform&&"emulator"===t.kind))try{return lN(t)?await a(t):await i(t)}catch(t){let e=N(t);return{success:!1,exitCode:-1,stdout:"",stderr:e.message,error:e}}}async function lQ(e){let{req:t,sessionName:r,logPath:a,sessionStore:i,dispatch:n,stopIosRunner:o=tA,clearRuntimeHints:s=s0,settleSimulator:l=lD,shutdownSimulator:d=nr,shutdownAndroidEmulator:u=lY,appLogOps:c}=e,p=i.get(r);if(!p)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session"}};p.appLog&&await c.stop(p.appLog),t.positionals&&t.positionals.length>0&&("ios"===p.device.platform&&await o(p.device.id),await n(p.device,"close",t.positionals,t.flags?.out,{...o6(a,t.flags,p.appBundleId,p.trace?.outPath)}),await l(p.device,ly)),"ios"===p.device.platform&&await o(p.device.id),sY(i.getRuntimeHints(r))&&p.appBundleId&&await s({device:p.device,appId:p.appBundleId}).catch(()=>{}),i.recordAction(p,{command:"close",positionals:t.positionals??[],flags:t.flags??{},result:{session:r}}),t.flags?.saveScript&&(p.recordSession=!0),i.writeSessionLog(p),await lc(r).catch(()=>{}),i.delete(r);let f=await lZ({device:p.device,shutdownRequested:t.flags?.shutdown,shutdownSimulator:d,shutdownAndroidEmulator:u});return f?{ok:!0,data:{session:r,shutdown:f}}:{ok:!0,data:{session:r}}}let l0={ios:async(e,t,r)=>{let{reinstallIosApp:a}=await Promise.resolve().then(()=>({reinstallIosApp:ou}));return await a(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:a}=await Promise.resolve().then(()=>({reinstallAndroidApp:a4}));return await a(e,t,r)}},l1={ios:async(e,t,r)=>{let{installIosApp:a}=await Promise.resolve().then(()=>({installIosApp:od})),i=await a(e,r,{appIdentifierHint:t});return{bundleId:i.bundleId,appName:i.appName,launchTarget:i.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:a}=await Promise.resolve().then(()=>({installAndroidApp:a3})),i=await a(e,r);return{package:i.packageName,appName:i.appName,launchTarget:i.launchTarget}}};async function l2(e){let{req:t,command:r,sessionName:a,sessionStore:i,ensureReady:n,resolveDevice:o,deployOps:s}=e,l=i.get(a),d=t.flags??{},u=lS(r,l,d);if(u)return u;let c=t.positionals?.[0]?.trim(),p=t.positionals?.[1]?.trim();if(!c||!p)return{ok:!1,error:{code:"INVALID_ARGS",message:`${r} requires: ${r} <app> <path-to-app-binary>`}};let f=t.meta?.uploadedArtifactId;try{let e,a=f?rr(f,t.meta?.tenantId):tq.expandHome(p);if(!F.existsSync(a))return{ok:!1,error:{code:"INVALID_ARGS",message:`App binary not found: ${a}`}};let u=await lE({session:l,flags:d,ensureReadyFn:n,resolveTargetDeviceFn:o,ensureReady:!1});if(!o5(r,u))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:`${r} is not supported on this device`}};if("ios"===u.platform){let t=await s.ios(u,c,a),r=t.bundleId;e=r?{app:c,appPath:a,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:c,appPath:a,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await s.android(u,c,a),r=t.package;e=r?{app:c,appPath:a,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:c,appPath:a,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}return l&&i.recordAction(l,{command:r,positionals:t.positionals??[],flags:t.flags??{},result:e}),{ok:!0,data:e}}finally{f&&ra(f)}}let l3=["platform","target","device","udid","serial","verbose","out"];async function l4(e,t,r){let a=e.flags?.batchOnError??"stop";if("stop"!==a)return{ok:!1,error:{code:"INVALID_ARGS",message:`Unsupported batch on-error mode: ${a}.`}};let i=e.flags?.batchMaxSteps??W;if(!Number.isInteger(i)||i<1||i>1e3)return{ok:!1,error:{code:"INVALID_ARGS",message:`Invalid batch max-steps: ${String(e.flags?.batchMaxSteps)}`}};try{let a=J(e.flags?.batchSteps,i),n=Date.now(),o=[];for(let i=0;i<a.length;i+=1){let n=a[i],s=await l8(e,t,n,r,i+1);if(!s.ok)return{ok:!1,error:{code:s.error.code,message:`Batch failed at step ${s.step} (${n.command}): ${s.error.message}`,hint:s.error.hint,diagnosticId:s.error.diagnosticId,logPath:s.error.logPath,details:{...s.error.details??{},step:s.step,command:n.command,positionals:n.positionals,executed:i,total:a.length,partialResults:o}}};o.push(s.result)}return{ok:!0,data:{total:a.length,executed:a.length,totalDurationMs:Date.now()-n,results:o}}}catch(t){let e=w(t);return{ok:!1,error:{code:e.code,message:e.message,details:e.details}}}}async function l8(e,t,r,a,i){let n=Date.now(),o=function(e,t){let{batchSteps:r,batchOnError:a,batchMaxSteps:i,...n}=t??{},o=e??{};for(let e of l3)void 0===n[e]&&void 0!==o[e]&&(n[e]=o[e]);return n}(e.flags,r.flags);void 0===o.session&&(o.session=t);let s=await a({token:e.token,session:t,command:r.command,positionals:r.positionals,flags:o,runtime:r.runtime,meta:e.meta}),l=Date.now()-n;return s.ok?{ok:!0,step:i,result:{step:i,command:r.command,ok:!0,data:s.data??{},durationMs:l}}:{ok:!1,step:i,error:s.error}}let l5='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',l6='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").',l9=["platform","target","device","udid","serial","verbose","out"],l7=["path","start","stop","doctor","mark","clear"],de=`logs requires ${l7.slice(0,-1).join(", ")}, or ${l7.at(-1)}`,dt=["dump","log"],dr=`network requires ${dt.join(" or ")}`,da=["summary","headers","body","all"],di=`network include mode must be one of: ${da.join(", ")}`,dn=async({avdName:e,serial:t,headless:r})=>{let{ensureAndroidEmulatorBooted:a}=await Promise.resolve().then(()=>({ensureAndroidEmulatorBooted:ae}));return await a({avdName:e,serial:t,headless:r})};async function ds(e){let{req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:n,resolveDevice:o,dispatch:s,command:l,positionals:d,recordPositionals:u,deriveNextSession:c}=e,p=i.get(r),f=t.flags??{},m=lS(l,p,f);if(m)return m;let h=await lE({session:p,flags:f,ensureReadyFn:n,resolveTargetDeviceFn:o,ensureReady:!0});if(!o5(l,h))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:`${l} is not supported on this device`}};let w=await s(h,l,d,t.flags?.out,{...o6(a,t.flags,p?.appBundleId,p?.trace?.outPath)});if(p){let e=c?await c(p,w,h):p;i.recordAction(e,{command:l,positionals:u??d,flags:t.flags??{},result:w??{}}),e!==p&&i.set(r,e)}return{ok:!0,data:w??{}}}function dl(e){return e.appLog?e.appLog.backend:"macos"===e.device.platform?"macos":"ios"===e.device.platform?"device"===e.device.kind?"ios-device":"ios-simulator":"android"}async function dd(e){let{req:t,sessionName:r,sessionStore:a,ensureReady:i,resolveDevice:n}=e,o=a.get(r),s=t.flags??{},l=s.platform;if(!o&&"string"==typeof s?.session&&s.session.trim().length>0)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"ios"===l?`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 d=lS("appstate",o,s);if(d)return d;let u=(o?.device.platform==="ios"||o?.device.platform==="macos")&&function(e,t){if(!t)return!1;if(!l_(e))return!0;let r=e?.platform;return!(r&&!e2(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())}(s,o);if("ios"===l&&!u)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:l5}};if("macos"===l&&!u)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:l6}};if(u&&o){let e=o.appName??o.appBundleId;if(!o.appName&&!o.appBundleId){if("macos"===o.device.platform&&o.surface&&"app"!==o.surface&&"frontmost-app"!==o.surface)return{ok:!0,data:{platform:o.device.platform,appName:o.surface,appBundleId:o.appBundleId,source:"session",surface:o.surface}};let e="macos"===o.device.platform?"macOS":"iOS";return{ok:!1,error:{code:"COMMAND_FAILED",message:`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`}}}return{ok:!0,data:{platform:o.device.platform,appName:e??"unknown",appBundleId:o.appBundleId,source:"session",surface:o.surface??"app",..."ios"===o.device.platform?{device_udid:o.device.id,ios_simulator_device_set:o.device.simulatorSetPath??null}:{}}}}let c=await lE({session:o,flags:s,ensureReadyFn:i,resolveTargetDeviceFn:n,ensureReady:!0});if("ios"===c.platform)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:l5}};if("macos"===c.platform)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:l6}};let{getAndroidAppState:p}=await Promise.resolve().then(()=>({getAndroidAppState:aU})),f=await p(c);return{ok:!0,data:{platform:"android",package:f.package,activity:f.activity}}}async function du(e){let{req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:n,resolveDevice:o,dispatch:s}=e,l=i.get(r),d=t.flags??{},u=lS("clipboard",l,d);if(u)return u;let c=(t.positionals?.[0]??"").toLowerCase();if("read"!==c&&"write"!==c)return{ok:!1,error:{code:"INVALID_ARGS",message:"clipboard requires a subcommand: read or write"}};let p=await lE({session:l,flags:d,ensureReadyFn:n,resolveTargetDeviceFn:o,ensureReady:!0});if(!o5("clipboard",p))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"clipboard is not supported on this device"}};let f=await s(p,"clipboard",t.positionals??[],t.flags?.out,{...o6(a,t.flags,l?.appBundleId,l?.trace?.outPath)});return l&&i.recordAction(l,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:f??{}}),{ok:!0,data:{platform:p.platform,...f??{}}}}async function dc(e){let{req:t,sessionName:r,logPath:a,sessionStore:i,invoke:n,dispatch:o,ensureReady:s,resolveTargetDevice:l,installOps:d=l1,reinstallOps:u=l0,stopIosRunner:c,appLogOps:p={start:t8,stop:t5},ensureAndroidEmulatorBoot:f=dn,resolveAndroidPackageForOpen:m=lG,applyRuntimeHints:h=sQ,clearRuntimeHints:g=s0,settleSimulator:v,shutdownSimulator:A,shutdownAndroidEmulator:y,listAndroidDevices:b,listAppleDevices:S,listAppleApps:_}=e,D=o??o3,E=s??o7,k=l??o2,M=c??tA,x=v??lD,O=t.command;if("session_list"===O)return{ok:!0,data:{sessions:i.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("runtime"===O)return await lF({req:t,sessionName:r,sessionStore:i,clearRuntimeHints:g});if("ensure-simulator"===O)try{let e=t.flags??{},r=e.device,a=e.runtime,i=eC(e.iosSimulatorDeviceSet);if(!r)return{ok:!1,error:{code:"INVALID_ARGS",message:"ensure-simulator requires --device <name>"}};let n=!0===e.boot,o=!1!==e.reuseExisting,s=await lw({deviceName:r,runtime:a,simulatorSetPath:i,reuseExisting:o,boot:n,ensureReady:E});return{ok:!0,data:{udid:s.udid,device:s.device,runtime:s.runtime,ios_simulator_device_set:i??null,created:s.created,booted:s.booted}}}catch(t){let e=w(t);return{ok:!1,error:{code:e.code,message:e.message,details:e.details}}}if("devices"===O)try{let e=[],r=eR(t.flags?.androidDeviceAllowlist),a=t.flags?.platform,i=e3({simulatorSetPath:eC(t.flags?.iosSimulatorDeviceSet),platform:a,target:t.flags?.target});if("android"===a){let t=b??(await Promise.resolve().then(()=>({ensureAndroidEmulatorBooted:ae,ensureAndroidEmulatorHeadlessBooted:at,listAndroidDevices:r2,parseAndroidAvdList:r4,parseAndroidEmulatorAvdNameOutput:rW,parseAndroidFeatureListForTv:rZ,parseAndroidTargetFromCharacteristics:rY,resolveAndroidAvdName:r8,resolveAndroidEmulatorAvdName:rK,waitForAndroidBoot:ar}))).listAndroidDevices;e.push(...await t({serialAllowlist:r}))}else if("ios"===a||"macos"===a){let t=S??(await Promise.resolve().then(()=>({findBootableIosSimulator:oQ,isAppleProductType:oz,isAppleTvProductType:oJ,isSupportedAppleDevicectlDevice:oZ,listAppleDevices:o0,listIosDevices:o0,resolveAppleTargetFromDevicectlDevice:oY}))).listAppleDevices;e.push(...await t({simulatorSetPath:i}))}else{if("apple"!==a){let t=b??(await Promise.resolve().then(()=>({ensureAndroidEmulatorBooted:ae,ensureAndroidEmulatorHeadlessBooted:at,listAndroidDevices:r2,parseAndroidAvdList:r4,parseAndroidEmulatorAvdNameOutput:rW,parseAndroidFeatureListForTv:rZ,parseAndroidTargetFromCharacteristics:rY,resolveAndroidAvdName:r8,resolveAndroidEmulatorAvdName:rK,waitForAndroidBoot:ar}))).listAndroidDevices;try{e.push(...await t({serialAllowlist:r}))}catch{}}let t=S??(await Promise.resolve().then(()=>({findBootableIosSimulator:oQ,isAppleProductType:oz,isAppleTvProductType:oJ,isSupportedAppleDevicectlDevice:oZ,listAppleDevices:o0,listIosDevices:o0,resolveAppleTargetFromDevicectlDevice:oY}))).listAppleDevices;try{e.push(...await t({simulatorSetPath:i}))}catch{}}let n="ios"===a||"macos"===a?e.filter(e=>e.platform===a):e,o=(t.flags?.target?n.filter(e=>(e.target??"mobile")===t.flags?.target):n).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=w(t);return{ok:!1,error:{code:e.code,message:e.message,details:e.details}}}if("apps"===O){let e=i.get(r),a=t.flags??{},n=lS(O,e,a);if(n)return n;let o=await lE({session:e,flags:a,ensureReadyFn:E,resolveTargetDeviceFn:k,ensureReady:!0});if(!o5("apps",o))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"apps is not supported on this device"}};let s=t.flags?.appsFilter??"all";if(e1(o.platform)){let e=_??(await Promise.resolve().then(()=>({closeIosApp:os,ensureBootedSimulator:nt,installIosApp:od,installIosInstallablePath:oc,listIosApps:ow,listSimulatorApps:og,openIosApp:on,openIosDevice:oo,parseIosDeviceAppsPayload:i4,pushIosNotification:om,readIosClipboardText:op,reinstallIosApp:ou,resolveIosApp:oi,screenshotIos:nQ,setIosSetting:oh,uninstallIosApp:ol,writeIosClipboardText:of}))).listIosApps;return{ok:!0,data:{apps:(await e(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}}let{listAndroidApps:l}=await Promise.resolve().then(()=>({listAndroidApps:aP}));return{ok:!0,data:{apps:(await l(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}if("boot"===O){let e,a=i.get(r),n=t.flags??{},o=lS(O,a,n);if(o)return o;let s="android"===(n.platform??a?.device.platform),l=!0===n.headless;if(l&&!s)return{ok:!1,error:{code:"INVALID_ARGS",message:"boot --headless is supported only for Android emulators."}};let d=lM({flags:n,sessionDevice:a?.device}),u=s&&!!d,c=!1;try{e=await lE({session:a,flags:n,ensureReadyFn:E,resolveTargetDeviceFn:k,ensureReady:!1})}catch(r){let t=w(r);if(s&&l&&!d&&"DEVICE_NOT_FOUND"===t.code)return{ok:!1,error:{code:"INVALID_ARGS",message:"boot --headless requires --device <avd-name> (or an Android emulator session target)."}};if(!u||"DEVICE_NOT_FOUND"!==t.code||!d)throw r;e=await f({avdName:d,serial:n.serial,headless:l}),c=!0}if(n.target&&(e.target??"mobile")!==n.target)return{ok:!1,error:{code:"DEVICE_NOT_FOUND",message:`No ${e.platform} device found matching --target ${n.target}.`}};if(s&&l){if("android"!==e.platform||"emulator"!==e.kind)return{ok:!1,error:{code:"INVALID_ARGS",message:"boot --headless is supported only for Android emulators."}};if(!c){let t=lM({flags:n,sessionDevice:a?.device,resolvedDevice:e});if(!t)return{ok:!1,error:{code:"INVALID_ARGS",message:"boot --headless requires --device <avd-name> (or an Android emulator session target)."}};e=await f({avdName:t,serial:n.serial,headless:!0})}await E(e)}else("android"!==e.platform||!0!==e.booted)&&await E(e);return o5("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"boot is not supported on this device"}}}if("appstate"===O)return await dd({req:t,sessionName:r,sessionStore:i,ensureReady:E,resolveDevice:k});if("clipboard"===O)return await du({req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:E,resolveDevice:k,dispatch:D});if("keyboard"===O)return await ds({req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:E,resolveDevice:k,dispatch:D,command:"keyboard",positionals:t.positionals??[]});if("perf"===O){let e,t,a,n=i.get(r);return n?{ok:!0,data:(a=(t=(e=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===lj&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:lj,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)}(n.actions)).at(-1))?{available:!0,lastDurationMs:t.durationMs,lastMeasuredAt:t.measuredAt,method:lj,sampleCount:e.length,samples:e}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:lj},{session:n.name,platform:n.device.platform,device:n.device.name,deviceId:n.device.id,metrics:{startup:a,fps:{available:!1,reason:lq},memory:{available:!1,reason:lq},cpu:{available:!1,reason:lq}},sampling:{startup:{method:lj,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"}}})}:{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"perf requires an active session. Run open first."}}}if("install"===O||"reinstall"===O)return await l2({req:t,command:O,sessionName:r,sessionStore:i,ensureReady:E,resolveDevice:k,deployOps:"install"===O?d:u});if("install_source"===O)return await lm({req:t,sessionName:r,sessionStore:i});if("release_materialized_paths"===O)return await lh({req:t});if("push"===O){let e,n=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();if(!n||!o)return{ok:!1,error:{code:"INVALID_ARGS",message:"push requires <bundle|package> <payload.json|inline-json>"}};let s="file"===(e=oP(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>tq.expandHome(e,t)})).kind?e.path:e.text;return await ds({req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:E,resolveDevice:k,dispatch:D,command:"push",positionals:[n,s],recordPositionals:[n,o]})}if("trigger-app-event"===O)return await ds({req:t,sessionName:r,logPath:a,sessionStore:i,ensureReady:E,resolveDevice:k,dispatch:D,command:"trigger-app-event",positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,a=r?await lB(e.device,r,e.appBundleId,m)??e.appBundleId:e.appBundleId;return{...e,appBundleId:a}}});if("open"===O)return await lK({req:t,sessionName:r,logPath:a,sessionStore:i,dispatch:D,ensureReady:E,resolveDevice:k,applyRuntimeHints:h,clearRuntimeHints:g,stopIosRunner:M,settleSimulator:x,resolveAndroidPackageForOpen:m});if("replay"===O){let e=t.positionals?.[0];if(!e)return{ok:!1,error:{code:"INVALID_ARGS",message:"replay requires a path"}};try{let o=tq.expandHome(e,t.meta?.cwd),s=F.readFileSync(o,"utf8"),l=s.trimStart()[0];if("{"===l||"["===l)return{ok:!1,error:{code:"INVALID_ARGS",message:"replay accepts .ad script files. JSON replay payloads are no longer supported."}};let d=function(e){let t=[];for(let r of e.split(/\r?\n/)){let e=function(e){let t=e.trim();if(0===t.length||t.startsWith("#"))return null;let r=function(e){let t=[],r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r+=1;if(r>=e.length)break;if('"'===e[r]){let a=r+1,i=!1;for(;a<e.length;){let t=e[a];if('"'===t&&!i)break;i="\\"===t&&!i,"\\"!==t&&(i=!1),a+=1}if(a>=e.length)throw new I("INVALID_ARGS",`Invalid replay script line: ${e}`);let n=e.slice(r,a+1);t.push(JSON.parse(n)),r=a+1;continue}let a=r;for(;a<e.length&&!/\s/.test(e[a]);)a+=1;t.push(e.slice(r,a)),r=a}return t}(t);if(0===r.length)return null;let[a,...i]=r;if("context"===a)return null;let n={ts:Date.now(),command:a,positionals:[],flags:{}};if("snapshot"===a){n.positionals=[];for(let e=0;e<i.length;e+=1){let t=i[e];if("-i"===t){n.flags.snapshotInteractiveOnly=!0;continue}if("-c"===t){n.flags.snapshotCompact=!0;continue}if("--raw"===t){n.flags.snapshotRaw=!0;continue}if(("-d"===t||"--depth"===t)&&e+1<i.length){let t=Number(i[e+1]);Number.isFinite(t)&&t>=0&&(n.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if(("-s"===t||"--scope"===t)&&e+1<i.length){n.flags.snapshotScope=i[e+1],e+=1;continue}if("--backend"===t&&e+1<i.length){e+=1;continue}}return n}if("open"===a){let e=function(e){var t;let r=[],a={};for(let t of e){if("--relaunch"===t){a.relaunch=!0;continue}r.push(t)}let i=tG(r);return{positionals:i.positionals,flags:a,runtime:(t=i.flags).platform||t.metroHost||void 0!==t.metroPort||t.bundleUrl||t.launchUrl?i.flags:void 0}}(i);return n.positionals=e.positionals,Object.assign(n.flags,e.flags),n.runtime=e.runtime,n}if("runtime"===a){let e=tG(i);return n.positionals=e.positionals,Object.assign(n.flags,e.flags),n}if(tP(a)){let e=tV(a,i);if(Object.assign(n.flags,e.flags),0===e.positionals.length)return n;let t=e.positionals[0];if(t.startsWith("@"))return n.positionals=[t],e.positionals[1]&&(n.result={refLabel:e.positionals[1]}),n;let r=e.positionals[0],o=e.positionals[1];return lo(r)&&lo(o)&&e.positionals.length>=2?n.positionals=[r,o]:n.positionals=[e.positionals.join(" ")],n}if("fill"===a){if(i.length<2)return n.positionals=i,n;let e=i[0];return e.startsWith("@")?(i.length>=3?(n.positionals=[e,i.slice(2).join(" ")],n.result={refLabel:i[1]}):n.positionals=[e,i[1]],n):(n.positionals=[e,i.slice(1).join(" ")],n)}if("get"===a){if(i.length<2)return n.positionals=i,n;let e=i[0],t=i[1];return t.startsWith("@")?(n.positionals=[e,t],i[2]&&(n.result={refLabel:i[2]})):n.positionals=[e,i.slice(1).join(" ")],n}if("swipe"===a){let e=tV(a,i);return Object.assign(n.flags,e.flags),n.positionals=e.positionals,n}if("record"===a){let e=[];for(let t=0;t<i.length;t+=1){let r=i[t];if("--hide-touches"===r){n.flags.hideTouches=!0;continue}if("--fps"===r&&t+1<i.length){let e=Number(i[t+1]);Number.isFinite(e)&&(n.flags.fps=Math.floor(e)),t+=1;continue}e.push(r)}return n.positionals=e,n}return n.positionals=i,n}(r);e&&t.push(e)}return t}(s),u=t.flags?.replayUpdate===!0,c=0;for(let e=0;e<d.length;e+=1){let s=d[e];if(!s||"replay"===s.command)continue;let l=await n({token:t.token,session:r,command:s.command,positionals:s.positionals??[],flags:df(t.flags,s.flags),runtime:s.runtime,meta:t.meta});if(l.ok)continue;if(!u)return dp(l,s,e,o);let p=await dm({action:s,sessionName:r,logPath:a,sessionStore:i,dispatch:D});if(!p)return dp(l,s,e,o);if(d[e]=p,!(l=await n({token:t.token,session:r,command:p.command,positionals:p.positionals??[],flags:df(t.flags,p.flags),runtime:p.runtime,meta:t.meta})).ok)return dp(l,p,e,o);c+=1}if(u&&c>0){let e=i.get(r);!function(e,t,r){let a=[];if(r){let e=r.device.name.replace(/"/g,'\\"'),t=r.device.kind?` kind=${r.device.kind}`:"",i=r.device.target?` target=${r.device.target}`:"";a.push(`context platform=${r.device.platform}${i} device="${e}"${t} theme=unknown`)}for(let e of t)a.push(function(e){let t=[e.command];if("snapshot"===e.command)return e.flags?.snapshotInteractiveOnly&&t.push("-i"),e.flags?.snapshotCompact&&t.push("-c"),"number"==typeof e.flags?.snapshotDepth&&t.push("-d",String(e.flags.snapshotDepth)),e.flags?.snapshotScope&&t.push("-s",tR(e.flags.snapshotScope)),e.flags?.snapshotRaw&&t.push("--raw"),t.join(" ");if("open"===e.command)return tj(t,e),t.join(" ");if("runtime"===e.command){for(let r of e.positionals??[])t.push(tT(r));return tF(t,e.flags),t.join(" ")}if("record"===e.command)return tU(t,e),t.join(" ");for(let r of e.positionals??[])t.push(tR(r));return t$(t,e),t.join(" ")}(e));let i=`${a.join("\n")}
37
+ `,n=`${e}.tmp-${process.pid}-${Date.now()}`;F.writeFileSync(n,i),F.renameSync(n,e)}(o,d,e)}return{ok:!0,data:{replayed:d.length,healed:c,session:r}}}catch(t){let e=w(t);return{ok:!1,error:{code:e.code,message:e.message}}}}if("logs"===O){let e=i.get(r);if(!e)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"logs requires an active session"}};if(!o5("logs",e.device))return{ok:!1,error:N(new I("UNSUPPORTED_OPERATION","logs is not supported on this device"))};let a=(t.positionals?.[0]??"path").toLowerCase(),n=!!t.flags?.restart;if(!l7.includes(a))return{ok:!1,error:{code:"INVALID_ARGS",message:de}};if(n&&"clear"!==a)return{ok:!1,error:{code:"INVALID_ARGS",message:"logs --restart is only supported with logs clear"}};if("path"===a){let t=i.resolveAppLogPath(r),a=function(e){if(!F.existsSync(e))return{exists:!1,sizeBytes:0};let t=F.statSync(e);return{exists:!0,sizeBytes:t.size,modifiedAt:t.mtime.toISOString()}}(t),n=dl(e);return{ok:!0,data:{path:t,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:n,sizeBytes:a.sizeBytes,modifiedAt:a.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>'}}}if("doctor"===a){let t=i.resolveAppLogPath(r),a=await t6(e.device,e.appBundleId);return{ok:!0,data:{path:t,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:a.checks,notes:a.notes}}}if("mark"===a){let e,a=t.positionals?.slice(1).join(" ")??"",n=i.resolveAppLogPath(r);return t4(n),e=`[agent-device][mark][${new Date().toISOString()}] ${a.trim()||"marker"}
38
+ `,F.appendFileSync(n,e,"utf8"),{ok:!0,data:{path:n,marked:!0}}}if("clear"===a){if(e.appLog&&!n)return{ok:!1,error:{code:"INVALID_ARGS",message:"logs clear requires logs to be stopped first; run logs stop"}};if(n&&!e.appBundleId)return{ok:!1,error:{code:"INVALID_ARGS",message:"logs clear --restart requires an app session; run open <app> first"}};let t=i.resolveAppLogPath(r);if(n){e.appLog&&await p.stop(e.appLog);let a=t9(t),n=i.resolveAppLogPidPath(r);try{let o=await p.start(e.device,e.appBundleId,t,n),s={...e,appLog:{platform:e.device.platform,backend:o.backend,outPath:t,startedAt:o.startedAt,getState:o.getState,stop:o.stop,wait:o.wait}};return i.set(r,s),{ok:!0,data:{...a,restarted:!0}}}catch(a){let t=N(a);return i.set(r,{...e,appLog:void 0}),{ok:!1,error:t}}}return{ok:!0,data:t9(t)}}if("start"===a){if(e.appLog)return{ok:!1,error:{code:"INVALID_ARGS",message:"app log already streaming; run logs stop first"}};if(!e.appBundleId)return{ok:!1,error:{code:"INVALID_ARGS",message:"logs start requires an app session; run open <app> first"}};let t=i.resolveAppLogPath(r),a=i.resolveAppLogPidPath(r);try{let n=await p.start(e.device,e.appBundleId,t,a),o={...e,appLog:{platform:e.device.platform,backend:n.backend,outPath:t,startedAt:n.startedAt,getState:n.getState,stop:n.stop,wait:n.wait}};return i.set(r,o),{ok:!0,data:{path:t,started:!0}}}catch(e){return{ok:!1,error:N(e)}}}if("stop"===a){if(!e.appLog)return{ok:!1,error:{code:"INVALID_ARGS",message:"no app log stream active"}};let t=e.appLog.outPath;return await p.stop(e.appLog),i.set(r,{...e,appLog:void 0}),{ok:!0,data:{path:t,stopped:!0}}}}if("network"===O){let e=i.get(r);if(!e)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"network requires an active session"}};if(!o5("network",e.device))return{ok:!1,error:N(new I("UNSUPPORTED_OPERATION","network is not supported on this device"))};let a=(t.positionals?.[0]??"dump").toLowerCase();if(!dt.includes(a))return{ok:!1,error:{code:"INVALID_ARGS",message:dr}};let n=t.positionals?.[1],o=n?Number.parseInt(n,10):25;if(!Number.isInteger(o)||o<1||o>200)return{ok:!1,error:{code:"INVALID_ARGS",message:"network dump limit must be an integer in range 1..200"}};let s=(t.positionals?.[2]??"summary").toLowerCase();if(!da.includes(s))return{ok:!1,error:{code:"INVALID_ARGS",message:di}};let l=function(e,t){let r=sj(t?.maxEntries,25,1,200),a=t?.include??"summary",i=sj(t?.maxPayloadChars,2048,64,16384),n=sj(t?.maxScanLines,4e3,100,2e4);if(!F.existsSync(e))return{path:e,exists:!1,scannedLines:0,matchedLines:0,entries:[],include:a,limits:{maxEntries:r,maxPayloadChars:i,maxScanLines:n}};let o=F.readFileSync(e,"utf8").split("\n"),s=Math.max(0,o.length-n),l=o.slice(s),d=[];for(let e=l.length-1;e>=0&&d.length<r;e-=1){let t=l[e]?.trim();if(!t)continue;let r=function(e,t,r,a){let i=function(e){let t=e.indexOf("{");if(t<0)return null;let r=e.lastIndexOf("}");if(r<=t)return null;let a=e.slice(t,r+1);try{let e=JSON.parse(a);return e&&"object"==typeof e?e:null}catch{return null}}(e),n=sU(i,["method","httpMethod"]),o=sU(i,["url","requestUrl"]),s=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}(i,["status","statusCode","responseCode"]),l=sT.exec(e),d=/\bmethod["'=: ]+([A-Z]+)\b/i.exec(e),u=(n??d?.[1]??l?.[1])?.toUpperCase(),c=s$.exec(e),p=o??c?.[0];if(!p)return null;let f={method:u,url:p,status:s??function(e){for(let t of sF){let r=t.exec(e);if(!r)continue;let a=Number.parseInt(r[1]??"",10);if(Number.isInteger(a))return a}return null}(e)??void 0,timestamp:function(e){let t=/\b\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z)?\b/.exec(e);return t?.[0]}(e),raw:sB(e,a),line:t};if("headers"===r||"all"===r){let t=function(e,t){if(t){let e=t.headers??t.requestHeaders??t.responseHeaders;if(void 0!==e)return sG(e)}let r=/\bheaders?["'=: ]+(\{.*\})/i.exec(e);return r?.[1]?.trim()}(e,i);t&&(f.headers=sB(t,a))}if("body"===r||"all"===r){let t=sV(e,i,["requestBody","body","payload","request"]),r=sV(e,i,["responseBody","response"]);t&&(f.requestBody=sB(t,a)),r&&(f.responseBody=sB(r,a))}return f}(t,s+e+1,a,i);r&&d.push(r)}return{path:e,exists:!0,scannedLines:l.length,matchedLines:d.length,entries:d,include:a,limits:{maxEntries:r,maxPayloadChars:i,maxScanLines:n}}}(i.resolveAppLogPath(r),{maxEntries:o,include:s,maxPayloadChars:2048,maxScanLines:4e3}),d=dl(e),u=[];return e.appLog||u.push("Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests."),0===l.entries.length&&u.push("No HTTP(s) entries were found in recent session app logs."),{ok:!0,data:{...l,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:d,notes:u}}}return"batch"===O?await l4(t,r,n):"close"===O?await lQ({req:t,sessionName:r,logPath:a,sessionStore:i,dispatch:D,stopIosRunner:M,clearRuntimeHints:g,settleSimulator:x,shutdownSimulator:A??nr,shutdownAndroidEmulator:y,appLogOps:{stop:p.stop}}):null}function dp(e,t,r,a){if(e.ok)return e;let i=r+1,n=function(e){let t;return t=(e.positionals??[]).map(e=>tR(e)),[e.command,...t].join(" ")}(t),o={...e.error.details??{},replayPath:a,step:i,action:t.command,positionals:t.positionals??[]};return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${i} (${n}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:o}}}function df(e,t){let r={...t??{}},a=e??{};for(let e of l9)void 0===r[e]&&void 0!==a[e]&&(r[e]=a[e]);return r}async function dm(e){let{action:t,sessionName:r,logPath:a,sessionStore:i,dispatch:n}=e;if(!(tP(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let o=i.get(r);if(!o)return null;let s=tP(t.command)||"fill"===t.command,l=tP(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",d=await dh(o,t,a,s,n,i);for(let e of 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),tP(e.command)){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&t.push(e.positionals.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}=sA(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=ln(e.positionals??[]);r&&t.push(r)}let a="string"==typeof e.result?.refLabel?e.result.refLabel.trim():"";if(a.length>0){let r=JSON.stringify(a);"fill"===e.command?(t.push(`id=${r} editable=true`),t.push(`label=${r} editable=true`),t.push(`text=${r} editable=true`),t.push(`value=${r} editable=true`)):(t.push(`id=${r}`),t.push(`label=${r}`),t.push(`text=${r}`),t.push(`value=${r}`))}return tx(t).filter(e=>e.trim().length>0)}(t)){let r=sv(e);if(!r)continue;let a=sM(d.nodes,r,{platform:o.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!a)continue;let i=sC(a.node,o.device.platform,{action:tP(t.command)?"click":"fill"===t.command?"fill":"get"}).join(" || ");if(tP(t.command))return{...t,positionals:[i]};if("fill"===t.command){let e=tM(t);if(!e)continue;return{...t,positionals:[i,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,i]}}if("is"===t.command){let{predicate:e,split:r}=sA(t.positionals);if(!e)continue;let a=r?.rest.join(" ").trim()??"",n=[e,i];return"text"===e&&a.length>0&&n.push(a),{...t,positionals:n}}if("wait"===t.command){let{selectorTimeout:e}=ln(t.positionals??[]),r=[i];return e&&r.push(e),{...t,positionals:r}}}let u=function(e,t,r){if("get"!==e.command||e.positionals?.[0]!=="text")return null;let a=e.positionals?.[1];if(!a)return null;let i=sv(a);if(!i)return null;let n=new Set,o=!1;for(let e of i.selectors)for(let t of e.terms)"role"===t.key&&"string"==typeof t.value&&n.add(sc(t.value)),("text"===t.key||"label"===t.key||"value"===t.key)&&"string"==typeof t.value&&/^\d+$/.test(t.value.trim())&&(o=!0);if(!o)return null;let s=t.nodes.filter(e=>{let t=sf(e).trim();return!!/^\d+$/.test(t)&&(0===n.size||n.has(sc(e.type??"")))});if(0===s.length||1!==tx(s.map(e=>sf(e).trim())).length)return null;let l=s[0];if(!l)return null;let d=sC(l,r.device.platform,{action:"get"});return 0===d.length?null:{...e,positionals:["text",d.join(" || ")]}}(t,d,o);return u||null}async function dh(e,t,r,a,i,n){let o=await i(e.device,"snapshot",[],t.flags?.out,{...o6(r,{...t.flags??{},snapshotInteractiveOnly:a,snapshotCompact:a},e.appBundleId,e.trace?.outPath)}),s=o?.nodes??[],l={nodes:sa(t.flags?.snapshotRaw?s:su(s)),truncated:o?.truncated,createdAt:Date.now(),backend:o?.backend};return e.snapshot=l,n.set(e.name,e),l}function dw(e,t){let r=z(e.type??"Element"),a=Q(e,r),i=!1===e.enabled?"disabled":"enabled",n=!0===e.selected?"selected":"unselected",o=!0===e.hittable?"hittable":"not-hittable";return[String(t??e.depth??0),r,a,i,n,o].join("|")}function dg(e,t){return t.flatten?e.map(e=>({text:H(e,0,!1),comparable:dw(e,0)})):ee(e).map(e=>({text:e.text,comparable:dw(e.node,e.depth)}))}function dv(e,t){return e.get(t)??0}async function dI(e){var t,r;let a;return{snapshot:(t=await dA(e),r=e.flags?.snapshotRaw,a=t?.nodes??[],{nodes:sa(r?a:su(a)),truncated:t?.truncated,createdAt:Date.now(),backend:t?.backend})}}async function dA(e){var t,r,a,i;let n,{dispatchSnapshotCommand:o,device:s,session:l,flags:d,outPath:u,logPath:c,snapshotScope:p}=e;return"macos"===s.platform&&l?.surface&&"app"!==l.surface?(t=await nE(l.surface),r={snapshotDepth:d?.snapshotDepth,snapshotInteractiveOnly:d?.snapshotInteractiveOnly,snapshotScope:p},n=t.nodes??[],r.snapshotScope&&(n=function(e,t){let r=ss(sa(e),t);if(!r)return[];let a=e.findIndex(e=>e.index===r.index);if(-1===a)return[];let i=e[a]?.depth??0,n=[];for(let t=a;t<e.length;t+=1){let r=e[t];if(!r)continue;let o=r.depth??0;if(t>a&&o<=i)break;n.push(r)}return dy(n,i)}(n,r.snapshotScope)),r.snapshotInteractiveOnly&&(n=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 a of e){if(!function(e){if(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")}(a))continue;let e=a;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:dy(e.filter(e=>r.has(e.index)))}(n)),"number"==typeof r.snapshotDepth&&(a=n,i=r.snapshotDepth,n=dy(a.filter(e=>(e.depth??0)<=i))),{...t,nodes:n}):await o(s,"snapshot",[],u,{...o6(c,{...d,snapshotScope:p},l?.appBundleId,l?.trace?.outPath)})}function dy(e,t=0){let r=new Map;for(let[t,a]of e.entries())r.set(a.index,t);return e.map((e,a)=>({...e,index:a,depth:Math.max(0,(e.depth??0)-t),parentIndex:"number"==typeof e.parentIndex?r.get(e.parentIndex):void 0}))}function db(e,t){if(!e||!e.trim().startsWith("@"))return{ok:!0,scope:e};if(!t?.snapshot)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:"Ref scope requires an existing snapshot in session."}}};let r=si(e.trim());if(!r)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:`Invalid ref scope: ${e}`}}};let a=sn(t.snapshot.nodes,r),i=a?sl(a,t.snapshot.nodes):void 0;return i?{ok:!0,scope:i}:{ok:!1,response:{ok:!1,error:{code:"COMMAND_FAILED",message:`Ref ${e} not found or has no label`}}}}async function dS(e,t,r){let a=e.get(t),i=a?.device??await o2(r??{});return a||await o7(i),{session:a,device:i}}async function d_(e,t,r){let a=!e&&"ios"===t.platform;try{return await r()}finally{a&&await tA(t.id)}}function dN(e,t,r,a){t&&e.recordAction(t,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:a})}function dD(e){let{session:t,sessionName:r,device:a,snapshot:i,appBundleId:n}=e;return t?{...t,snapshot:i}:{name:r,device:a,createdAt:Date.now(),appBundleId:n,snapshot:i,actions:[]}}function dE(e){if(!e)return null;let t=Number(e);return Number.isFinite(t)?t:null}async function dk(e){let{parsed:t,req:r,sessionName:a,logPath:i,sessionStore:n,session:o,device:s}=e,l=e.dispatchSnapshotCommand??o3,d=e.runnerCommand??tE;if("sleep"===t.kind)return await new Promise(e=>setTimeout(e,t.durationMs)),dN(n,o,r,{waitedMs:t.durationMs}),{ok:!0,data:{waitedMs:t.durationMs}};if(!o5("wait",s))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"wait is not supported on this device"}};if("selector"===t.kind)return await dM({dispatchSnapshotCommand:l,device:s,logPath:i,parsed:t,req:r,session:o,sessionName:a,sessionStore:n});let u=function(e,t){if("ref"===e.kind){if(!t?.snapshot)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:"Ref wait requires an existing snapshot in session."}}};let r=si(e.rawRef);if(!r)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:`Invalid ref: ${e.rawRef}`}}};let a=sn(t.snapshot.nodes,r),i=a?sl(a,t.snapshot.nodes):void 0;return i?{ok:!0,text:i,timeoutMs:e.timeoutMs}:{ok:!1,response:{ok:!1,error:{code:"COMMAND_FAILED",message:`Ref ${e.rawRef} not found or has no label`}}}}return e.text?{ok:!0,text:e.text,timeoutMs:e.timeoutMs}:{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:"wait requires text"}}}}(t,o);return u.ok?await dx({dispatchSnapshotCommand:l,device:s,logPath:i,req:r,runnerCommand:d,session:o,sessionStore:n,text:u.text,timeoutMs:u.timeoutMs}):u.response}async function dM(e){let{dispatchSnapshotCommand:t,device:r,logPath:a,parsed:i,req:n,session:o,sessionName:s,sessionStore:l}=e,d=i.timeoutMs??1e4,u=Date.now();for(;Date.now()-u<d;){let e=sx((await dO({dispatchSnapshotCommand:t,device:r,logPath:a,req:n,session:o,sessionName:s,sessionStore:l})).nodes,i.selector,{platform:r.platform});if(e)return dL(l,o,n,{selector:e.selector.raw,waitedMs:Date.now()-u});await new Promise(e=>setTimeout(e,300))}return{ok:!1,error:{code:"COMMAND_FAILED",message:`wait timed out for selector: ${i.selectorExpression}`}}}async function dx(e){let{device:t,logPath:r,req:a,runnerCommand:i,session:n,sessionStore:o,text:s,timeoutMs:l}=e,d=l??1e4,u=Date.now();for(;Date.now()-u<d;){if("macos"===t.platform&&n?.surface&&"app"!==n.surface){if(ss((await dO({dispatchSnapshotCommand:e.dispatchSnapshotCommand,device:t,logPath:r,req:a,session:n,sessionName:n?.name??a.session??"default",sessionStore:o})).nodes,s))return dL(o,n,a,{text:s,waitedMs:Date.now()-u})}else if(e1(t.platform)){let e=await i(t,{command:"findText",text:s,appBundleId:n?.appBundleId},{verbose:a.flags?.verbose,logPath:r,traceLogPath:n?.trace?.outPath,requestId:a.meta?.requestId});if(e?.found)return dN(o,n,a,{text:s,waitedMs:Date.now()-u}),{ok:!0,data:{text:s,waitedMs:Date.now()-u}}}else if("android"===t.platform&&ss(sa((await it(t,{scope:s})).nodes??[]),s))return dN(o,n,a,{text:s,waitedMs:Date.now()-u}),{ok:!0,data:{text:s,waitedMs:Date.now()-u}};await new Promise(e=>setTimeout(e,300))}return{ok:!1,error:{code:"COMMAND_FAILED",message:`wait timed out for text: ${s}`}}}async function dO(e){let{dispatchSnapshotCommand:t,device:r,logPath:a,req:i,session:n,sessionName:o,sessionStore:s}=e,{snapshot:l}=await dI({dispatchSnapshotCommand:t,device:r,session:n,flags:{...i.flags,snapshotInteractiveOnly:!1,snapshotCompact:!1},outPath:i.flags?.out,logPath:a});return n&&(n.snapshot=l,s.set(o,n)),l}function dL(e,t,r,a){return dN(e,t,r,a),{ok:!0,data:a}}async function dC(e){let{req:t,logPath:r,sessionStore:a,session:i,device:n}=e,o=e.runnerCommand??tE,s=(t.positionals?.[0]??"get").toLowerCase(),l=i?"frontmost-app"===i.surface?{surface:"frontmost-app"}:{bundleId:i.appBundleId,surface:i.surface}:{};if(!o5("alert",n))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"alert is not supported on this device"}};if("macos"===n.platform){let e=async()=>await nD("wait"===s?"get":s,l);if("wait"===s){let r=dE(t.positionals?.[1])??1e4,n=Date.now();for(;Date.now()-n<r;){try{let r=await e();return dN(a,i,t,r),{ok:!0,data:r}}catch{}await new Promise(e=>setTimeout(e,300))}return{ok:!1,error:{code:"COMMAND_FAILED",message:"alert wait timed out"}}}let r="accept"===s||"dismiss"===s?s:"get";if("accept"===r||"dismiss"===r){let e,n=Date.now();for(;Date.now()-n<2e3;){try{let e=await nD(r,l);return dN(a,i,t,e),{ok:!0,data:e}}catch(r){e=r;let t=String(r?.message??"").toLowerCase();if(!t.includes("alert not found")&&!t.includes("no alert"))break}await new Promise(e=>setTimeout(e,300))}throw e}let n=await nD("get",l);return dN(a,i,t,n),{ok:!0,data:n}}if("wait"===s){let e=dE(t.positionals?.[1])??1e4,s=Date.now();for(;Date.now()-s<e;){try{let e=await o(n,{command:"alert",action:"get",appBundleId:i?.appBundleId},{verbose:t.flags?.verbose,logPath:r,traceLogPath:i?.trace?.outPath,requestId:t.meta?.requestId});return dN(a,i,t,e),{ok:!0,data:e}}catch{}await new Promise(e=>setTimeout(e,300))}return{ok:!1,error:{code:"COMMAND_FAILED",message:"alert wait timed out"}}}let d="accept"===s||"dismiss"===s?s:"get",u={verbose:t.flags?.verbose,logPath:r,traceLogPath:i?.trace?.outPath,requestId:t.meta?.requestId};if("accept"===d||"dismiss"===d){let e,r=Date.now();for(;Date.now()-r<2e3;){try{let e=await o(n,{command:"alert",action:d,appBundleId:i?.appBundleId},u);return dN(a,i,t,e),{ok:!0,data:e}}catch(r){e=r;let t=String(r?.message??"").toLowerCase();if(!t.includes("alert not found")&&!t.includes("no alert"))break}await new Promise(e=>setTimeout(e,300))}throw e}let c=await o(n,{command:"alert",action:d,appBundleId:i?.appBundleId},u);return dN(a,i,t,c),{ok:!0,data:c}}async function dP(e){let{req:t,logPath:r,sessionStore:a,session:i,device:n,parsed:o}=e,{setting:s,state:l,permissionTarget:d}=o;if(!o5("settings",n))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"settings is not supported on this device"}};let u=i?.appBundleId,c="permission"===s?[s,l,d??"",t.positionals?.[3]??"",u??""]:[s,l,u??""],p=await o3(n,"settings",c,t.flags?.out,{...o6(r,t.flags,u,i?.trace?.outPath)});return dN(a,i,t,p??{setting:s,state:l}),{ok:!0,data:p??{setting:s,state:l}}}async function dR(e){let{req:t,sessionName:r,logPath:a,sessionStore:i}=e,n=e.dispatchSnapshotCommand??o3,o=e.runnerCommand??tE,s=e.sessionlessRunnerCleanup??d_,l=t.command;if("snapshot"===l){let{session:e,device:o}=await dS(i,r,t.flags);if(!o5("snapshot",o))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"snapshot is not supported on this device"}};let l=db(t.flags?.snapshotScope,e);return l.ok?await s(e,o,async()=>{let s=await dI({dispatchSnapshotCommand:n,device:o,session:e,flags:t.flags,outPath:t.flags?.out,logPath:a,snapshotScope:l.scope}),d=dD({session:e,sessionName:r,device:o,snapshot:s.snapshot,appBundleId:e?.appBundleId});return dN(i,d,t,{nodes:s.snapshot.nodes.length,truncated:s.snapshot.truncated??!1}),i.set(r,d),{ok:!0,data:{nodes:s.snapshot.nodes,truncated:s.snapshot.truncated??!1,appName:d.appBundleId?d.appName??d.appBundleId:void 0,appBundleId:d.appBundleId}}}):l.response}if("diff"===l){if(t.positionals?.[0]!=="snapshot")return{ok:!1,error:{code:"INVALID_ARGS",message:"diff currently supports only: diff snapshot"}};let{session:e,device:o}=await dS(i,r,t.flags);if(!o5("diff",o))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"diff is not supported on this device"}};let l=db(t.flags?.snapshotScope,e);if(!l.ok)return l.response;let d=t.flags?.snapshotInteractiveOnly===!0;return await s(e,o,async()=>{let s=(await dI({dispatchSnapshotCommand:n,device:o,session:e,flags:t.flags,outPath:t.flags?.out,logPath:a,snapshotScope:l.scope})).snapshot;if(!e?.snapshot){let a=function(e,t={}){return dg(e,t).length}(s.nodes,{flatten:d}),n=dD({session:e,sessionName:r,device:o,snapshot:s,appBundleId:e?.appBundleId});return dN(i,n,t,{mode:"snapshot",baselineInitialized:!0,summary:{additions:0,removals:0,unchanged:a}}),i.set(r,n),{ok:!0,data:{mode:"snapshot",baselineInitialized:!0,summary:{additions:0,removals:0,unchanged:a},lines:[]}}}let u=function(e,t,r={}){let a=function(e,t){let r=e.length,a=t.length,i=r+a,n=new Map,o=[];n.set(1,0);for(let s=0;s<=i;s+=1){o.push(new Map(n));for(let i=-s;i<=s;i+=2){let l=i===-s||i!==s&&dv(n,i-1)<dv(n,i+1)?dv(n,i+1):dv(n,i-1)+1,d=l-i;for(;l<r&&d<a&&e[l].comparable===t[d].comparable;)l+=1,d+=1;if(n.set(i,l),l>=r&&d>=a)return function(e,t,r,a,i){let n=[],o=a,s=i;for(let a=e.length-1;a>=0;a-=1){let i=e[a],l=o-s,d=l===-a||l!==a&&dv(i,l-1)<dv(i,l+1)?l+1:l-1,u=dv(i,d),c=u-d;for(;o>u&&s>c;)n.push({kind:"unchanged",text:r[s-1].text}),o-=1,s-=1;if(0===a)break;o===u?(n.push({kind:"added",text:r[c].text}),s=c):(n.push({kind:"removed",text:t[u].text}),o=u)}return n.reverse(),n}(o,e,t,r,a)}}return[]}(dg(e,r),dg(t,r)),i={additions:0,removals:0,unchanged:0};for(let e of a)"added"===e.kind&&(i.additions+=1),"removed"===e.kind&&(i.removals+=1),"unchanged"===e.kind&&(i.unchanged+=1);return{summary:i,lines:a}}(e.snapshot.nodes,s.nodes,{flatten:d}),c={...e,snapshot:s};return dN(i,c,t,{mode:"snapshot",baselineInitialized:!1,summary:u.summary}),i.set(r,c),{ok:!0,data:{mode:"snapshot",baselineInitialized:!1,summary:u.summary,lines:u.lines}}})}if("wait"===l){let{session:e,device:l}=await dS(i,r,t.flags),d=function(e){if(0===e.length)return null;let t=dE(e[0]);if(null!==t)return{kind:"sleep",durationMs:t};if("text"===e[0]){let t=dE(e[e.length-1]);return{kind:"text",text:(null!==t?e.slice(1,-1).join(" "):e.slice(1).join(" ")).trim(),timeoutMs:t}}if(e[0].startsWith("@")){let t=dE(e[e.length-1]);return{kind:"ref",rawRef:e[0],timeoutMs:t}}let r=dE(e[e.length-1]),a=sI(null!==r?e.slice(0,-1):e.slice());if(a&&0===a.rest.length){let e=sv(a.selectorExpression);if(e)return{kind:"selector",selector:e,selectorExpression:a.selectorExpression,timeoutMs:r}}return{kind:"text",text:(null!==r?e.slice(0,-1).join(" "):e.join(" ")).trim(),timeoutMs:r}}(t.positionals??[]);if(!d)return{ok:!1,error:{code:"INVALID_ARGS",message:"wait requires a duration or text"}};let u=()=>dk({parsed:d,req:t,sessionName:r,logPath:a,sessionStore:i,session:e,device:l,dispatchSnapshotCommand:n,runnerCommand:o});return"sleep"===d.kind?await u():await s(e,l,u)}if("alert"===l){let{session:e,device:n}=await dS(i,r,t.flags);return await s(e,n,async()=>await dC({req:t,logPath:a,sessionStore:i,session:e,device:n,runnerCommand:o}))}if("settings"===l){let e,n,o,l=(e=t.positionals?.[0]?.toLowerCase(),n=t.positionals?.[1]?.toLowerCase(),o=t.positionals?.[2]?.toLowerCase(),e&&n&&("permission"!==e||o)?{ok:!0,parsed:{setting:e,state:n,permissionTarget:o}}:{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:K}}});if(!l.ok)return l.response;let{session:d,device:u}=await dS(i,r,t.flags);return await s(d,u,async()=>await dP({req:t,logPath:a,sessionStore:i,session:d,device:u,parsed:l.parsed}))}return null}function dT(e,t,r,a={}){let i=dF(r);if(!i)return{matches:[],score:0};let n=0,o=[];for(let r of e){if(a.requireRect&&!r.rect)continue;let e=function(e,t,r){switch(t){case"role":return function(e,t){let r=function(e){let t=e.trim();return t?t=(t.split(".").pop()??t).replace(/XCUIElementType/gi,"").toLowerCase():""}(e??"");return r?r===t?2:+!!r.includes(t):0}(e.type,r);case"label":return d$(e.label,r);case"value":return d$(e.value,r);case"id":return d$(e.identifier,r);default:return Math.max(d$(e.label,r),d$(e.value,r),d$(e.identifier,r))}}(r,t,i);if(!(e<=0)){if(e>n){n=e,o.length=0,o.push(r);continue}e===n&&o.push(r)}}return{matches:o,score:n}}function d$(e,t){let r=dF(e??"");return r?r===t?2:+!!r.includes(t):0}function dF(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function dU(e){let{session:t,refInput:r,fallbackLabel:a,requireRect:i,invalidRefMessage:n,notFoundMessage:o}=e;if(!t.snapshot)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:"No snapshot in session. Run snapshot first."}}};let s=si(r);if(!s)return{ok:!1,response:{ok:!1,error:{code:"INVALID_ARGS",message:n}}};let l=sn(t.snapshot.nodes,s);return((!l||i&&!l.rect)&&a.length>0&&(l=ss(t.snapshot.nodes,a)),l&&(!i||l.rect))?{ok:!0,target:{ref:s,node:l,snapshotNodes:t.snapshot.nodes}}:{ok:!1,response:{ok:!1,error:{code:"COMMAND_FAILED",message:o}}}}async function dV(e){let{device:t,node:r,flags:a,appBundleId:i,traceOutPath:n,surface:o,contextFromFlags:s,dispatch:l}=e,d=X(r),u=function(e){let t=function(e){if(!e)return null;let t=Number(e.x),r=Number(e.y),a=Number(e.width),i=Number(e.height);return Number.isFinite(t)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(i)&&!(a<0)&&!(i<0)?{x:t,y:r,width:a,height:i}:null}(e);if(!t)return null;let r=so(t);return Number.isFinite(r.x)&&Number.isFinite(r.y)?r:null}(r.rect);if(!u)return d;try{let e=await l(t,"read",[String(u.x),String(u.y)],void 0,{...s(a,i,n),surface:o}),c=e&&"object"==typeof e?e:void 0,p="string"==typeof c?.text?c.text:"";if(p.trim())return p;return C({level:"warn",phase:"interaction_read_fallback",data:{reason:"empty_backend_text",nodeRef:r.ref,surface:o,platform:t.platform}}),d}catch(e){return C({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)}}),d}}async function dG(e){let{req:t,sessionName:r,logPath:a,sessionStore:i,invoke:n}=e,o=e.dispatch??o3,s=t.command;if("find"!==s)return null;let l=t.positionals??[];if(0===l.length)return{ok:!1,error:{code:"INVALID_ARGS",message:"find requires a locator or text"}};let{locator:d,query:u,action:c,value:p,timeoutMs:f}=function(e){let t="any",r=0;["text","label","value","role","id"].includes(e[0])&&(t=e[0],r=1);let a=e[r]??"",i=e.slice(r+1);if(0===i.length)return{locator:t,query:a,action:"click"};let n=i[0].toLowerCase();if("get"===n){let e=i[1]?.toLowerCase();if("text"===e)return{locator:t,query:a,action:"get_text"};if("attrs"===e)return{locator:t,query:a,action:"get_attrs"};throw new I("INVALID_ARGS","find get only supports text or attrs")}if("wait"===n)return{locator:t,query:a,action:"wait",timeoutMs:dE(i[1])??void 0};if("exists"===n)return{locator:t,query:a,action:"exists"};if("click"===n)return{locator:t,query:a,action:"click"};if("focus"===n)return{locator:t,query:a,action:"focus"};if("fill"===n)return{locator:t,query:a,action:"fill",value:i.slice(1).join(" ")};if("type"===n)return{locator:t,query:a,action:"type",value:i.slice(1).join(" ")};throw new I("INVALID_ARGS",`Unsupported find action: ${i[0]}`)}(l);if(!u)return{ok:!1,error:{code:"INVALID_ARGS",message:"find requires a value"}};let m=i.get(r);if(!m&&"exists"!==c&&"wait"!==c&&"get_text"!==c&&"get_attrs"!==c)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};let h=m?.device??await o2(t.flags??{});m||await o7(h);let w="role"!==d?u:void 0,g="click"===c||"focus"===c||"fill"===c||"type"===c,v=0,A=null,y=async()=>{let e=Date.now();if(A&&e-v<750)return{nodes:A};let{snapshot:n}=await dI({dispatchSnapshotCommand:o,device:h,session:m,flags:{...t.flags,snapshotInteractiveOnly:g,snapshotCompact:g},outPath:t.flags?.out,logPath:a,snapshotScope:w}),s=n.nodes;return v=e,A=s,m&&(m.snapshot=n,i.set(r,m)),{nodes:s,truncated:n.truncated,backend:n.backend}};if("wait"===c){let e=f??1e4,r=Date.now();for(;Date.now()-r<e;){let{nodes:e}=await y();if(dT(e,d,u,{requireRect:!1}).matches[0])return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{found:!0,waitedMs:Date.now()-r}}),{ok:!0,data:{found:!0,waitedMs:Date.now()-r}};await new Promise(e=>setTimeout(e,300))}return{ok:!1,error:{code:"COMMAND_FAILED",message:"find wait timed out"}}}let{nodes:b}=await y(),S=dT(b,d,u,{requireRect:g});if(g&&S.matches.length>1){let e=S.matches.slice(0,8).map(e=>{let t=sf(e)||e.label||e.identifier||e.type||"";return`@${e.ref}${t?`(${t})`:""}`});return{ok:!1,error:{code:"AMBIGUOUS_MATCH",message:`find matched ${S.matches.length} elements for ${d} "${u}". Use a more specific locator or selector.`,details:{locator:d,query:u,matches:S.matches.length,candidates:e}}}}let _=S.matches[0]??null;if(!_)return{ok:!1,error:{code:"COMMAND_FAILED",message:"find did not match any element"}};let N="click"===c||"focus"===c||"fill"===c||"type"===c?function(e,t){if(t.hittable)return t;let r=t,a=new Set;for(;void 0!==r.parentIndex&&!a.has(r.ref);){a.add(r.ref);let t=e[r.parentIndex];if(!t)break;if(t.hittable)return t;r=t}return null}(b,_)??_:_,D=`@${N.ref}`,E={...t.flags??{},noRecord:!0};if("exists"===c)return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{found:!0}}),{ok:!0,data:{found:!0}};if("get_text"===c){let e=await dV({device:h,node:_,flags:t.flags,appBundleId:m?.appBundleId,traceOutPath:m?.trace?.outPath,surface:m?.surface,contextFromFlags:(e,t,r)=>o6(a,e,t,r),dispatch:o});return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:D,action:"get text",text:e}}),{ok:!0,data:{ref:D,text:e,node:_}}}if("get_attrs"===c)return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:D,action:"get attrs"}}),{ok:!0,data:{ref:D,node:_}};if("click"===c){let e=await n({token:t.token,session:r,command:"click",positionals:[D],flags:E});if(!e.ok)return e;let a=N.rect?so(N.rect):null,o={ref:D,locator:d,query:u};return a&&(o.x=a.x,o.y=a.y),m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:D,action:"click",locator:d,query:u}}),{ok:!0,data:o}}if("fill"===c){if(!p)return{ok:!1,error:{code:"INVALID_ARGS",message:"find fill requires text"}};let e=await n({token:t.token,session:r,command:"fill",positionals:[D,p],flags:E});return e.ok&&m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:D,action:"fill"}}),e}if("focus"===c){let e=_.rect?so(_.rect):null;if(!e)return{ok:!1,error:{code:"COMMAND_FAILED",message:"matched element has no bounds"}};let r=await o(h,"focus",[String(e.x),String(e.y)],t.flags?.out,{...o6(a,t.flags,m?.appBundleId,m?.trace?.outPath)});return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:D,action:"focus"}}),{ok:!0,data:r??{ref:D}}}if("type"===c){if(!p)return{ok:!1,error:{code:"INVALID_ARGS",message:"find type requires text"}};let e=_.rect?so(_.rect):null;if(!e)return{ok:!1,error:{code:"COMMAND_FAILED",message:"matched element has no bounds"}};await o(h,"focus",[String(e.x),String(e.y)],t.flags?.out,{...o6(a,t.flags,m?.appBundleId,m?.trace?.outPath)});let r=await o(h,"type",[p],t.flags?.out,{...o6(a,t.flags,m?.appBundleId,m?.trace?.outPath)});return m&&i.recordAction(m,{command:s,positionals:t.positionals??[],flags:t.flags??{},result:{ref:D,action:"type"}}),{ok:!0,data:r??{ref:D}}}return null}let dB=`
39
+ import Foundation
40
+ import AVFoundation
41
+
42
+ let url = URL(fileURLWithPath: CommandLine.arguments[1])
43
+ let asset = AVURLAsset(url: url)
44
+ let semaphore = DispatchSemaphore(value: 0)
45
+ var exitCode: Int32 = 1
46
+
47
+ Task {
48
+ defer { semaphore.signal() }
49
+ do {
50
+ let playable = try await asset.load(.isPlayable)
51
+ let duration = try await asset.load(.duration)
52
+ if playable && duration.isValid && !duration.isIndefinite && CMTimeGetSeconds(duration) > 0 {
53
+ exitCode = 0
54
+ }
55
+ } catch {
56
+ exitCode = 1
57
+ }
58
+ }
59
+
60
+ semaphore.wait()
61
+ exit(exitCode)
62
+ `.trim();async function dj(e,t={}){let r,a=t.pollMs??150,i=t.attempts??12,n=0;for(let t=0;t<i;t+=1){let t=0;try{t=F.statSync(e).size}catch{t=0}if(t>0&&t===r){if((n+=1)>=2)return}else n=0;r=t,await new Promise(e=>setTimeout(e,a))}}async function dq(e){try{var t,r;let a,i=await m("swift",["-",e],{stdin:dB,allowFailure:!0,timeoutMs:1e4});if(0===i.exitCode)return!0;if(t=i.stderr,r=i.stdout,a=`${t}
63
+ ${r}`,/\b(no such module ['"]AVFoundation['"]|unable to find utility ["']swift["']|xcrun: error: unable to find utility ["']swift["'])\b/i.test(a))return dW(e);return!1}catch(t){if(t instanceof I&&"TOOL_MISSING"===t.code)return dW(e);throw t}}async function dH(e,t={}){let r=t.pollMs??150,a=t.attempts??12;for(let t=0;t<a;t+=1){if(await dq(e))return;await new Promise(e=>setTimeout(e,r))}}function dW(e){try{let t=F.statSync(e);if(!t.isFile()||t.size<=0)return!1}catch{return!1}let t=function(e){try{let t=F.openSync(e,"r");try{let e=F.fstatSync(t).size,r=0,a=[];for(;r+8<=e&&a.length<16;){let e=Buffer.alloc(8);if(8>F.readSync(t,e,0,8,r))break;let i=e.readUInt32BE(0),n=e.toString("latin1",4,8);if(a.push(n),1===i){let e=Buffer.alloc(8);if(8>F.readSync(t,e,0,8,r+8))break;i=Number(e.readBigUInt64BE(0))}if(!Number.isFinite(i)||i<=0)break;r+=i}return a}finally{F.closeSync(t)}}catch{return[]}}(e);return t.includes("ftyp")&&t.includes("moov")}function dz(e){let t=o.parse(e);return o.join(t.dir,`${t.name}.gesture-telemetry.json`)}function dJ(e){return[...e].sort((e,t)=>e.tMs-t.tMs)}function dX(e){var t,r;let a=dz(e.videoPath),i={version:1,generatedAt:new Date().toISOString(),events:(t=e.events,(r=e.trimStartMs??0)>0?dJ(t.flatMap(e=>{let t=e.tMs-r,a="durationMs"in e?e.durationMs:void 0;return("number"==typeof a?t+a:t)<=0?[]:[{...e,tMs:Math.max(0,t)}]})):dJ(t))};return F.writeFileSync(a,JSON.stringify(i,null,2)),a}function dK(e){let{recording:t,trimStartMs:r,writeTelemetry:a=dX}=e,i=a({videoPath:t.outPath,events:t.gestureEvents,trimStartMs:r});return t.telemetryPath=i,i}function dY(e){let t=o.dirname(b(import.meta.url)),r=[b(new URL(`./${e}`,import.meta.url)),o.resolve(t,`../../ios-runner/AgentDeviceRunner/RecordingScripts/${e}`),o.resolve(t,`../../../ios-runner/AgentDeviceRunner/RecordingScripts/${e}`),o.resolve(process.cwd(),`ios-runner/AgentDeviceRunner/RecordingScripts/${e}`)];for(let e of r)if(F.existsSync(e))return e;throw new I("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})}function dZ(e=process.platform){if("darwin"!==e)return"touch overlay burn-in is only available on macOS hosts; returning raw video plus gesture telemetry"}async function dQ(e){let{videoPath:t,scriptPath:r,scriptArgs:a,commandDescription:i}=e;await dj(t),await dH(t);let n=F.mkdtempSync(o.join(V.tmpdir(),"agent-device-record-overlay-")),s=o.join(n,`input${o.extname(t)||".mp4"}`),l=o.join(n,o.basename(t)),d=o.join(n,"home"),u=o.join(n,"module-cache");F.copyFileSync(t,s),F.mkdirSync(d,{recursive:!0}),F.mkdirSync(u,{recursive:!0});try{await m("xcrun",["swift",r,"--input",s,"--output",l,...a],{timeoutMs:12e4,env:{...process.env,HOME:d,CLANG_MODULE_CACHE_PATH:u}}),await dH(l),F.copyFileSync(l,t)}catch(a){let e=a instanceof I?a:new I("COMMAND_FAILED",String(a),void 0,a instanceof Error?a:void 0);throw new I("COMMAND_FAILED",i,{videoPath:t,script:r,stderr:e.details?.stderr,stdout:e.details?.stdout,exitCode:e.details?.exitCode,processExitError:e.details?.processExitError},e)}finally{F.rmSync(n,{recursive:!0,force:!0})}}async function d0(e){let{videoPath:t,trimStartMs:r}=e;r>0&&await dQ({videoPath:t,scriptPath:a??=dY("recording-trim.swift"),scriptArgs:["--trim-start-ms",String(r)],commandDescription:"Failed to trim the start of the iOS recording"})}async function d1(e){let{videoPath:t,telemetryPath:a,targetLabel:i="recording"}=e;await dQ({videoPath:t,scriptPath:r??=dY("recording-overlay.swift"),scriptArgs:["--events",a],commandDescription:`Failed to add touch overlays to the ${i}`})}function d2(e){return e instanceof Error?e.message:String(e)}function d3(e,t){return e.stderr.trim()||e.stdout.trim()||`${t} exited with code ${e.exitCode}`}async function d4(e,t,r){let a=await e.runCmd("adb",["-s",t,"shell","ps","-o","pid=","-p",r],{allowFailure:!0});return 0===a.exitCode&&a.stdout.split(/\s+/).map(e=>e.trim()).includes(r)}async function d8(e,t,r){for(let a=0;a<40;a+=1){if(!await d4(e,t,r))return!0;await new Promise(e=>setTimeout(e,250))}return!await d4(e,t,r)}async function d5(e,t,r){let a,i=0;for(let n=0;n<20;n+=1){let n=await e.runCmd("adb",["-s",t,"shell","stat","-c","%s",r],{allowFailure:!0}),o=0===n.exitCode?n.stdout.trim():"";if(o.length>0&&o===a){if((i+=1)>=4)return}else i=0;a=o,await new Promise(e=>setTimeout(e,250))}}async function d6(e,t,r,a){for(let i=0;i<8;i+=1){let n=await e.runCmd("adb",["-s",t,"shell","stat","-c","%s",r],{allowFailure:!0}),o=0===n.exitCode?Number(n.stdout.trim()):NaN;if(Number.isFinite(o)&&o>0)return!0;if(!await d4(e,t,a))break;if(i+1>=2)return!0;await new Promise(e=>setTimeout(e,250))}return!1}async function d9(e){let t,{deps:r,deviceId:a,remotePath:i,outPath:n}=e;for(let e=0;e<2;e+=1){try{F.rmSync(n,{force:!0})}catch{}let o=await r.runCmd("adb",["-s",a,"pull",i,n],{allowFailure:!0});if(0!==o.exitCode)t=d3(o,"adb pull");else{await r.waitForStableFile(n,{pollMs:250,attempts:20});let t=await r.isPlayableVideo(n);if(C({level:"debug",phase:"record_stop_android_pull_validation",data:{deviceId:a,remotePath:i,outPath:n,attempt:e+1,fileSize:(()=>{try{return F.statSync(n).size}catch{return 0}})(),playable:t}}),t)return;C({level:"warn",phase:"record_stop_android_invalid_video_retry",data:{deviceId:a,remotePath:i,outPath:n,attempt:e+1}})}e<1&&await new Promise(e=>setTimeout(e,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 d7(e,t,r){await e.runCmd("adb",["-s",t,"shell","rm","-f",r],{allowFailure:!0})}async function ue(e,t,r){let a=await e.runCmd("adb",["-s",t,"shell","kill","-9",r],{allowFailure:!0});return C({level:"warn",phase:"record_stop_android_force_signal",data:{deviceId:t,remotePid:r,exitCode:a.exitCode,stdout:a.stdout.trim(),stderr:a.stderr.trim()}}),!(0!==a.exitCode&&await d4(e,t,r))&&await d8(e,t,r)}async function ut(e){var t;let r,{deps:a,device:i,recordingBase:n}=e,o="failed to start recording: Android screenrecord did not begin producing frames";for(let e of(t=Date.now(),r=`agent-device-recording-${t}.mp4`,[`/sdcard/${r}`,`/data/local/tmp/${r}`])){let t=await a.runCmd("adb",["-s",i.id,"shell",`screenrecord ${e} >/dev/null 2>&1 & echo $!`],{allowFailure:!0});if(0!==t.exitCode){o=`failed to start recording: ${d3(t,"adb shell screenrecord")}`;continue}let r=t.stdout.split(/\r?\n/).map(e=>e.trim()).filter(e=>/^\d+$/.test(e)).at(-1);if(!r){o="failed to start recording: adb did not return a valid Android screenrecord pid",await d7(a,i.id,e);continue}if(C({level:"debug",phase:"record_start_android_started",data:{deviceId:i.id,remotePath:e,remotePid:r}}),await d6(a,i.id,e,r))return{platform:"android",remotePath:e,remotePid:r,...n,startedAt:Date.now()};o="failed to start recording: Android screenrecord did not begin producing frames",await ue(a,i.id,r),await d7(a,i.id,e)}return{ok:!1,error:{code:"COMMAND_FAILED",message:o}}}async function ur(e){let t,r,{deps:a,device:i,recording:n}=e;C({level:"debug",phase:"record_stop_android_enter",data:{deviceId:i.id,remotePath:n.remotePath,remotePid:n.remotePid}});let o=await a.runCmd("adb",["-s",i.id,"shell","kill","-2",n.remotePid],{allowFailure:!0});if(C({level:"debug",phase:"record_stop_android_signal",data:{deviceId:i.id,remotePath:n.remotePath,remotePid:n.remotePid,exitCode:o.exitCode,stdout:o.stdout.trim(),stderr:o.stderr.trim()}}),0!==o.exitCode?await d4(a,i.id,n.remotePid)&&!await ue(a,i.id,n.remotePid)&&(t=`failed to stop recording: ${d3(o,"adb shell kill")}`):await d8(a,i.id,n.remotePid)||await ue(a,i.id,n.remotePid)||(t=`failed to stop recording: Android screenrecord pid ${n.remotePid} did not exit`),!t){await d5(a,i.id,n.remotePath);let e=await d9({deps:a,deviceId:i.id,remotePath:n.remotePath,outPath:n.outPath});if(e)return await s(),{ok:!1,error:{code:"COMMAND_FAILED",message:e}};if(dK({recording:n,writeTelemetry:a.writeRecordingTelemetry}),n.showTouches&&n.telemetryPath){let e=dZ();if(e)n.overlayWarning=e;else try{await a.overlayRecordingTouches({videoPath:n.outPath,telemetryPath:n.telemetryPath,targetLabel:"Android recording"})}catch(e){n.overlayWarning=`failed to overlay recording touches: ${d2(e)}`}}}if(await s(),t)return{ok:!1,error:{code:"COMMAND_FAILED",message:t}};if(r)return{ok:!1,error:{code:"COMMAND_FAILED",message:r}};return null;async function s(){let e=await a.runCmd("adb",["-s",i.id,"shell","rm","-f",n.remotePath],{allowFailure:!0});C({level:"debug",phase:"record_stop_android_cleanup",data:{deviceId:i.id,remotePath:n.remotePath,exitCode:e.exitCode,stdout:e.stdout.trim(),stderr:e.stderr.trim()}}),0===e.exitCode||t||(r=`failed to clean up remote recording: ${d3(e,"adb shell rm")}`)}}function ua(e){let t=e.appBundleId?.trim();return t&&t.length>0?t:void 0}function ui(e,t,r){return{verbose:e.flags?.verbose,logPath:t,traceLogPath:r.trace?.outPath}}async function un(e){let{req:t,activeSession:r,device:a,logPath:i,deps:n}=e,o=ua(r);if(o)try{await n.runIosRunnerCommand(a,{command:"snapshot",appBundleId:o,interactiveOnly:!0,compact:!0,depth:1},ui(t,i,r))}catch(e){C({level:"warn",phase:"record_start_simulator_runner_warm_failed",data:{deviceId:a.id,session:r.name,appBundleId:o,error:d2(e)}})}}async function uo(e){let t,r,{req:a,activeSession:i,sessionStore:n,device:o,logPath:s,deps:l,fpsFlag:d,recordingBase:u,appBundleId:c}=e,p=`agent-device-recording-${Date.now()}.mp4`,f=`tmp/${p}`,m=ui(a,s,i),h=async()=>l.runIosRunnerCommand(o,{command:"recordStart",outPath:p,fps:d,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(a){var w,g;if(!d2(a).toLowerCase().includes("recording already in progress"))return{ok:!1,error:{code:"COMMAND_FAILED",message:`failed to start recording: ${d2(a)}`}};C({level:"warn",phase:"record_start_runner_desynced",data:{platform:o.platform,kind:o.kind,deviceId:o.id,session:i.name,error:d2(a)}});let e=(w=o.id,g=i.name,n.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{ok:!1,error:{code:"COMMAND_FAILED",message:`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{ok:!1,error:{code:"COMMAND_FAILED",message:`failed to start recording: ${d2(e)}`}}}}return{platform:"ios-device-runner",remotePath:f,runnerStartedAtUptimeMs:t,targetAppReadyUptimeMs:r,...u}}async function us(e){let{req:t,activeSession:r,device:a,logPath:i,deps:n,fpsFlag:o,recordingBase:s,appBundleId:l}=e;try{await n.runIosRunnerCommand(a,{command:"recordStart",outPath:s.outPath,fps:o,appBundleId:l},ui(t,i,r))}catch(e){return{ok:!1,error:{code:"COMMAND_FAILED",message:`failed to start recording: ${d2(e)}`}}}return{platform:"macos-runner",...s}}async function ul(e){let{req:t,activeSession:r,device:a,logPath:i,deps:n,recording:o}=e,s=ua(r);try{await n.runIosRunnerCommand(a,{command:"recordStop",appBundleId:s},ui(t,i,r))}catch(e){C({level:"warn",phase:"record_stop_runner_failed",data:{platform:a.platform,kind:a.kind,deviceId:a.id,session:r.name,error:d2(e)}})}let l={stdout:"",stderr:"",exitCode:1};for(let e of ta)if(0===(l=await n.runCmd("xcrun",["devicectl","device","copy","from","--device",a.id,"--source",o.remotePath,"--destination",o.outPath,"--domain-type","appDataContainer","--domain-identifier",e],{allowFailure:!0})).exitCode)break;if(0!==l.exitCode){let e=l.stderr.trim()||l.stdout.trim()||`devicectl exited with code ${l.exitCode}`;return{ok:!1,error:{code:"COMMAND_FAILED",message:`failed to copy recording from device: ${e}`}}}let d="number"!=typeof o.runnerStartedAtUptimeMs||"number"!=typeof o.targetAppReadyUptimeMs?0:Math.max(0,o.targetAppReadyUptimeMs-o.runnerStartedAtUptimeMs);d>0&&await n.trimRecordingStart({videoPath:o.outPath,trimStartMs:d});let u=dK({recording:o,trimStartMs:d,writeTelemetry:n.writeRecordingTelemetry});if(o.showTouches){let e=dZ();if(e)o.overlayWarning=e;else try{await n.overlayRecordingTouches({videoPath:o.outPath,telemetryPath:u,targetLabel:"iOS recording"})}catch(e){o.overlayWarning=`failed to overlay recording touches: ${d2(e)}`}}return null}async function ud(e){let{req:t,activeSession:r,device:a,logPath:i,deps:n,recording:o}=e,s=ua(r);try{await n.runIosRunnerCommand(a,{command:"recordStop",appBundleId:s},ui(t,i,r))}catch(e){C({level:"warn",phase:"record_stop_runner_failed",data:{platform:a.platform,kind:a.kind,deviceId:a.id,session:r.name,error:d2(e)}})}let l=dK({recording:o,writeTelemetry:n.writeRecordingTelemetry});if(o.showTouches){let e=dZ();if(e)o.overlayWarning=e;else try{await n.overlayRecordingTouches({videoPath:o.outPath,telemetryPath:l,targetLabel:"macOS recording"})}catch(e){o.overlayWarning=`failed to overlay recording touches: ${d2(e)}`}}return null}async function uu(e){for(let t=0;t<2;t+=1){try{if(F.statSync(e).size>0)return Date.now()}catch{}if(t+1>=2)break;await new Promise(e=>setTimeout(e,250))}return Date.now()}async function uc(e){let t,{req:r,sessionName:a,sessionStore:i,activeSession:n,device:s,logPath:l,deps:d}=e;if(n.recording)return{ok:!1,error:{code:"INVALID_ARGS",message:"recording already in progress"}};let u=r.flags?.fps;if(void 0!==u&&(!Number.isInteger(u)||u<1||u>120))return{ok:!1,error:{code:"INVALID_ARGS",message:"fps must be an integer between 1 and 120"}};if(!o5("record",s))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"record is not supported on this device"}};let c=r.positionals?.[1]??`./recording-${Date.now()}.mp4`,p=tq.expandHome(c,r.meta?.cwd),f={outPath:p,clientOutPath:r.meta?.clientArtifactPaths?.outPath,startedAt:Date.now(),showTouches:r.flags?.hideTouches!==!0,gestureEvents:[]};if(F.mkdirSync(o.dirname(p),{recursive:!0}),F.rmSync(p,{force:!0}),"ios"===s.platform&&"device"===s.kind){let e=ua(n);if(!e)return{ok:!1,error:{code:"INVALID_ARGS",message:"record on physical iOS devices requires an active app session; run open <app> first"}};t=await uo({req:r,activeSession:n,sessionStore:i,device:s,logPath:l,deps:d,fpsFlag:u,recordingBase:f,appBundleId:e})}else if("macos"===s.platform){let e=ua(n);if(!e)return{ok:!1,error:{code:"INVALID_ARGS",message:"record on macOS requires an active app session; run open <app> first"}};t=await us({req:r,activeSession:n,device:s,logPath:l,deps:d,fpsFlag:u,recordingBase:f,appBundleId:e})}else if("ios"===s.platform){let e,a;await un({req:r,activeSession:n,device:s,logPath:l,deps:d});let{child:i,wait:o}=d.runCmdBackground("xcrun",e$(s,["io",s.id,"recordVideo",p]),{allowFailure:!0}),u=await uu(p);try{let t=Date.now(),i=await d.runIosRunnerCommand(s,{command:"uptime",appBundleId:ua(n)},{verbose:r.flags?.verbose,logPath:l,traceLogPath:n.trace?.outPath}),o=Date.now();e=Math.round((t+o)/2),a="number"==typeof i.currentUptimeMs?i.currentUptimeMs:void 0}catch{}t={platform:"ios",child:i,wait:o,...f,startedAt:u,gestureClockOriginAtMs:void 0===a?void 0:e,gestureClockOriginUptimeMs:a}}else t=await ut({deps:d,device:s,recordingBase:f});return"ok"in t?t:(n.recording=t,i.set(a,n),i.recordAction(n,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:{action:"start",showTouches:t.showTouches}}),{ok:!0,data:{recording:"started",outPath:t.clientOutPath??c,showTouches:t.showTouches}})}async function up(e){let{deps:t,device:r,recording:a}=e;if("android"===a.platform)return await ur({deps:t,device:r,recording:a});a.child.kill("SIGINT");let i=await a.wait;if(0!==i.exitCode)return{ok:!1,error:{code:"COMMAND_FAILED",message:`failed to stop recording: ${d3(i,"simctl recordVideo")}`}};let n=dK({recording:a,writeTelemetry:t.writeRecordingTelemetry});if(a.showTouches){let e=dZ();if(e)a.overlayWarning=e;else try{await t.overlayRecordingTouches({videoPath:a.outPath,telemetryPath:n,targetLabel:"iOS recording"})}catch(e){a.overlayWarning=`failed to overlay recording touches: ${d2(e)}`}}return null}async function uf(e){var t;let r,{req:a,activeSession:i,device:n,logPath:s,deps:l}=e;if(!i.recording)return{ok:!1,error:{code:"INVALID_ARGS",message:"no active recording"}};let d=i.recording,u=d.invalidatedReason;i.recording=void 0;let c="ios-device-runner"===d.platform?await ul({req:a,activeSession:i,device:n,logPath:s,deps:l,recording:d}):"macos-runner"===d.platform?await ud({req:a,activeSession:i,device:n,logPath:s,deps:l,recording:d}):await up({deps:l,device:n,recording:d});return c||(u?{ok:!1,error:{code:"COMMAND_FAILED",message:u}}:(r=[{field:"outPath",path:(t=d).outPath,localPath:t.clientOutPath,fileName:o.basename(t.clientOutPath??t.outPath)}],t.telemetryPath&&r.push({field:"telemetryPath",path:t.telemetryPath,localPath:function(e){if(e.clientOutPath)return dz(e.clientOutPath)}(t),fileName:o.basename(t.telemetryPath)}),{ok:!0,data:{recording:"stopped",outPath:t.outPath,telemetryPath:t.telemetryPath,artifacts:r,showTouches:t.showTouches,overlayWarning:t.overlayWarning}}))}async function um(e){let{req:t,sessionName:r,sessionStore:a,logPath:i}=e,n={runCmd:m,runCmdBackground:c,runIosRunnerCommand:tE,waitForStableFile:dj,isPlayableVideo:dq,writeRecordingTelemetry:dX,trimRecordingStart:d0,overlayRecordingTouches:d1,...e.deps},o=a.get(r),s=o?.device??await o2(t.flags??{});o||await o7(s);let l=o??{name:r,device:s,createdAt:Date.now(),actions:[]},d=(t.positionals?.[0]??"").toLowerCase();if(!["start","stop"].includes(d))return{ok:!1,error:{code:"INVALID_ARGS",message:"record requires start|stop"}};if("start"===d)return uc({req:t,sessionName:r,sessionStore:a,activeSession:l,device:s,logPath:i,deps:n});let u=await uf({req:t,activeSession:l,device:s,logPath:i,deps:n});return u.ok&&a.recordAction(l,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{action:"stop",outPath:u.data?.outPath,showTouches:u.data?.showTouches}}),u}async function uh(e){let{req:t,sessionName:r,sessionStore:a,logPath:i}=e,n=t.command;if("record"===n)return um({req:t,sessionName:r,sessionStore:a,logPath:i,deps:e.deps});if("trace"===n){let e=(t.positionals?.[0]??"").toLowerCase();if(!["start","stop"].includes(e))return{ok:!1,error:{code:"INVALID_ARGS",message:"trace requires start|stop"}};let i=a.get(r);if(!i)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session"}};if("start"===e){if(i.trace)return{ok:!1,error:{code:"INVALID_ARGS",message:"trace already in progress"}};let e=t.positionals?.[1]??a.defaultTracePath(i),r=tq.expandHome(e);return F.mkdirSync(o.dirname(r),{recursive:!0}),F.appendFileSync(r,""),i.trace={outPath:r,startedAt:Date.now()},a.recordAction(i,{command:n,positionals:t.positionals??[],flags:t.flags??{},result:{action:"start",outPath:r}}),{ok:!0,data:{trace:"started",outPath:r}}}if(!i.trace)return{ok:!1,error:{code:"INVALID_ARGS",message:"no active trace"}};let s=i.trace.outPath;if(t.positionals?.[1]){let e=tq.expandHome(t.positionals[1]);F.mkdirSync(o.dirname(e),{recursive:!0}),F.existsSync(s)?F.renameSync(s,e):F.appendFileSync(e,""),s=e}return i.trace=void 0,a.recordAction(i,{command:n,positionals:t.positionals??[],flags:t.flags??{},result:{action:"stop",outPath:s}}),{ok:!0,data:{trace:"stopped",outPath:s}}}return null}let uw=new WeakMap;function ug(e){if(!e)return;let t=uw.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)&&uv(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(uv);if(0===r.length)return;let a=Math.max(...r.map(e=>e.x+e.width)),i=Math.max(...r.map(e=>e.y+e.height));if(!(a<=0)&&!(i<=0))return{x:0,y:0,width:a,height:i}}(e);if(t)return{referenceWidth:t.width,referenceHeight:t.height}}(e.nodes??[]);if(r)return uw.set(e,r),r}function uv(e){return!!e&&e.width>0&&e.height>0}function uI(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 uA={referenceWidth:1e3,referenceHeight:1e3};function uy(e,t,r,a,i={},n=Date.now(),o=Date.now()){var s,l,d;let u,c,p=e.recording;if(!p)return;let f={...i,...a??{}},m=uN(f.effectiveDurationMs)??uN(f.durationMs),h={recordingStartedAt:p.startedAt,gestureClockOriginAtMs:p.gestureClockOriginAtMs,gestureClockOriginUptimeMs:p.gestureClockOriginUptimeMs,runnerStartedAtUptimeMs:"ios-device-runner"===p.platform?p.runnerStartedAtUptimeMs:void 0,gestureStartUptimeMs:uN(f.gestureStartUptimeMs),gestureEndUptimeMs:uN(f.gestureEndUptimeMs),fallbackStartedAtMs:n,fallbackFinishedAtMs:o},w="number"==typeof(s={gestureStartUptimeMs:uN(f.gestureStartUptimeMs),gestureEndUptimeMs:uN(f.gestureEndUptimeMs),reportedDurationMs:m,fallbackStartedAtMs:n,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),g="ios"===e.device.platform&&void 0===uN(f.gestureStartUptimeMs)&&function(e,t){switch(e){case"click":case"fill":case"focus":return!0;case"press":{let e=uD(uN(t.count),1)??1,r=!0===t.doubleTap,a=uD(uN(t.holdMs),1);return 1===e&&!r&&void 0===a}default:return!1}}(t,f)?function(e){let t=Math.max(0,e.gestureDurationMs);if(t<600)return uI(e);let r=Math.min(Math.max(.15*t,120),260);return Math.max(0,e.fallbackFinishedAtMs-r-e.recordingStartedAt)}({...h,gestureDurationMs:w}):uI(h),v=(l=e.snapshot,u=uN((d=f).referenceWidth),c=uN(d.referenceHeight),void 0!==u&&u>0&&void 0!==c&&c>0?{referenceWidth:u,referenceHeight:c}:ug(l)),I=function(e,t,r,a,i,n){switch(e){case"click":case"press":return function(e,t,r,a){let i=uk(t,e);if(!i)return[];let{x:n,y:o}=i,s=uD(uN(t.count),1)??1,l=uD(uN(t.intervalMs),0)??0,d=!0===t.doubleTap,u=uD(uN(t.holdMs),1),c=[];for(let e=0;e<s;e+=1){let t=r+e*l;if(void 0!==u&&u>0){c.push(uS(t,n,o,u,a));continue}c.push(ub(t,n,o,a)),d&&c.push(ub(t+90,n,o,a))}return c}(t,r,a,n);case"fill":case"focus":return function(e,t,r,a){let i=uk(t,e);if(!i)return[];let{x:n,y:o}=i;return[ub(r,n,o,a)]}(t,r,a,n);case"longpress":return function(e,t,r,a,i){let n=uk(t,e);if(!n)return[];let{x:o,y:s}=n;return[uS(r,o,s,ux(a,[uN(t.durationMs),uN(e[2])],800),i)]}(t,r,a,i,n);case"scroll":return function(e,t,r,a,i){let n=uM(t,e),o=u_(t.contentDirection)??u_(t.direction);if(!n||!o)return[];let{x1:s,y1:l,x2:d,y2:u}=n,c=ux(a,[],250),p=uN(t.amount)??uN(e[1]);return[{kind:"scroll",tMs:r,x:s,y:l,x2:d,y2:u,...i,durationMs:c,contentDirection:o,...void 0!==p?{amount:p}:{}}]}(t,r,a,i,n);case"swipe":return function(e,t,r,a,i){let n=uM(t,e);if(!n)return[];let{x1:o,y1:s,x2:l,y2:d}=n,u=ux(a,[uN(t.effectiveDurationMs),uN(t.durationMs),uN(e[4])],250),c=uD(uN(t.count),1)??1,p=uD(uN(t.pauseMs),0)??0,f="ping-pong"===t.pattern?"ping-pong":"one-way",m=[];for(let e=0;e<c;e+=1){let t="ping-pong"===f&&e%2==1,a=t?l:o,n=t?d:s,c=t?o:l,h=t?s:d,w=r+e*(u+p);if("back-swipe"===function(e,t,r,a,i){if(!i||Math.abs(r-e)<=1.25*Math.abs(a-t))return"swipe";let n=.08*i.referenceWidth;return e<=n&&r>e||e>=i.referenceWidth-n&&r<e?"back-swipe":"swipe"}(a,n,c,h,i)){m.push({kind:"back-swipe",tMs:w,x:a,y:n,x2:c,y2:h,...i,durationMs:u,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"}(a,c,i)});continue}m.push({kind:"swipe",tMs:w,x:a,y:n,x2:c,y2:h,...i,durationMs:u})}return m}(t,r,a,i,n);case"pinch":return function(e,t,r,a,i){let n=uk(t,e,1),o=uN(t.scale)??uN(e[0]);if(!n||void 0===o||o<=0)return[];let{x:s,y:l}=n;return[{kind:"pinch",tMs:r,x:s,y:l,...i,scale:o,durationMs:ux(a,[],280)}]}(t,r,a,i,n);default:return[]}}(t,r,f,g,w,v);0!==I.length&&(p.gestureEvents.push(...I),C({level:"debug",phase:"record_touch_visualization_event",data:{session:e.name,command:t,count:I.length,tMs:g,gestureDurationMs:w,kinds:I.map(e=>e.kind)}}))}function ub(e,t,r,a){return{kind:"tap",tMs:e,x:t,y:r,...a}}function uS(e,t,r,a,i){return{kind:"longpress",tMs:e,x:t,y:r,...i,durationMs:a}}function u_(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 uN(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 uD(e,t){if(void 0===e)return;let r=Math.floor(e);return r>=t?r:void 0}function uE(e,t,r){return Math.max(t,Math.min(r,e))}function uk(e,t,r=0){let a=uN(e.x)??uN(t[r]),i=uN(e.y)??uN(t[r+1]);if(void 0!==a&&void 0!==i)return{x:a,y:i}}function uM(e,t){let r=uN(e.x1)??uN(t[0]),a=uN(e.y1)??uN(t[1]),i=uN(e.x2)??uN(t[2]),n=uN(e.y2)??uN(t[3]);if(void 0!==r&&void 0!==a&&void 0!==i&&void 0!==n)return{x1:r,y1:a,x2:i,y2:n}}function ux(e,t,r){return uD(e,1)??t.map(e=>uD(e,1)).find(e=>void 0!==e)??r}function uO(e){let{data:t,fallbackX:r,fallbackY:a,referenceFrame:i,extra:n}=e;return{x:r,y:a,...i??{},...n??{},...t??{}}}async function uL(e){let{session:t,sessionStore:r,requestCommand:a,requestPositionals:i,flags:n,contextFromFlags:o,dispatch:s,interactionCommand:l,interactionPositionals:d,outPath:u,buildPayloads:c}=e,p=await uC({session:t,flags:n,contextFromFlags:o,dispatch:s,command:l,positionals:d,outPath:u}),{result:f,responseData:m=f}=await c(p.data);return function(e){let{session:t,sessionStore:r,command:a,positionals:i,flags:n,result:o,responseData:s,actionStartedAt:l,actionFinishedAt:d}=e;return r.recordAction(t,{command:a,positionals:i,flags:n??{},result:o}),uy(t,a,i,o,n??{},l,d),{ok:!0,data:s}}({session:t,sessionStore:r,command:a,positionals:i,flags:n,result:f,responseData:m,actionStartedAt:p.actionStartedAt,actionFinishedAt:p.actionFinishedAt})}async function uC(e){let{session:t,flags:r,contextFromFlags:a,dispatch:i,command:n,positionals:o,outPath:s}=e,l=Date.now(),d={...a(r,t.appBundleId,t.trace?.outPath)},u=await i(t.device,n,o,s,d);return{data:u&&"object"==typeof u?u:void 0,actionStartedAt:l,actionFinishedAt:Date.now()}}async function uP(e){let{req:t,sessionName:r,sessionStore:a,contextFromFlags:i,captureSnapshotForSession:n,resolveRefTarget:o,refSnapshotFlagGuardResponse:s}=e,l=e.dispatch??o3,d=e.readAndroidScreenSize??iI,u=t.command;if("press"===u||"click"===u){let e="click"===u?"click":"press",c=a.get(r);if(!c)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};let p=uR(c,e);if(p)return p;if(!o5("press",c.device))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"press is not supported on this device"}};let f=oE(t.flags),m="primary"===f?{}:{button:f};if("primary"!==f){let r=ok({commandLabel:e,platform:c.device.platform,button:f,count:t.flags?.count,intervalMs:t.flags?.intervalMs,holdMs:t.flags?.holdMs,jitterPx:t.flags?.jitterPx,doubleTap:t.flags?.doubleTap});if(r)return{ok:!1,error:{code:r.code,message:r.message,details:r.details}}}let h=function(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}(t.positionals??[]);if(h)return uL({session:c,sessionStore:a,requestCommand:u,requestPositionals:t.positionals??[String(h.x),String(h.y)],flags:t.flags,contextFromFlags:i,dispatch:l,interactionCommand:"press",interactionPositionals:[String(h.x),String(h.y)],outPath:t.flags?.out,buildPayloads:async e=>{let r=await u$({session:c,flags:t.flags,sessionStore:a,contextFromFlags:i,captureSnapshotForSession:n,dispatch:l,readAndroidScreenSize:d}),o=uO({data:e,fallbackX:h.x,fallbackY:h.y,referenceFrame:r,extra:m});return{result:o,responseData:o}}});let w="click",g=t.positionals?.[0]??"";if(g.startsWith("@")){let r=s("press",t.flags);if(r)return r;let d=t.positionals.length>1?t.positionals.slice(1).join(" ").trim():"",p=await uF({session:c,refInput:g,fallbackLabel:d,invalidRefMessage:`${e} requires a ref like @e2`,missingBoundsMessage:`Ref ${g} not found or has no bounds`,invalidBoundsMessage:`Ref ${g} not found or has invalid bounds`,reqFlags:t.flags,sessionStore:a,contextFromFlags:i,captureSnapshotForSession:n,dispatch:l,resolveRefTarget:o});if(!p.ok)return p.response;let{ref:f,node:h,snapshotNodes:v,point:I}=p.target,A=sl(h,v),y=sC(h,c.device.platform,{action:w}),{x:b,y:S}=I;return uL({session:c,sessionStore:a,requestCommand:u,requestPositionals:t.positionals??[],flags:t.flags,contextFromFlags:i,dispatch:l,interactionCommand:"press",interactionPositionals:[String(b),String(S)],outPath:t.flags?.out,buildPayloads:e=>{let t=uO({data:e,fallbackX:b,fallbackY:S,referenceFrame:uU(v),extra:{ref:f,refLabel:A,selectorChain:y,...m}});return{result:t,responseData:t}}})}let v=(t.positionals??[]).join(" ").trim();if(!v)return{ok:!1,error:{code:"INVALID_ARGS",message:`${e} requires @ref, selector expression, or x y coordinates`}};let I=sg(v),A=await n(c,t.flags,a,i,{interactiveOnly:!0},l),y=await O("selector_resolve",()=>sM(A.nodes,I,{platform:c.device.platform,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0}),{command:u});if(!y||!y.node.rect)return{ok:!1,error:{code:"COMMAND_FAILED",message:sO(I,y?.diagnostics??[],{unique:!0})}};let b=uV(y.node.rect);if(!b)return{ok:!1,error:{code:"COMMAND_FAILED",message:`Selector ${y.selector.raw} resolved to invalid bounds`}};let{x:S,y:_}=b,N=sC(y.node,c.device.platform,{action:w}),D=sl(y.node,A.nodes);return uL({session:c,sessionStore:a,requestCommand:u,requestPositionals:t.positionals??[],flags:t.flags,contextFromFlags:i,dispatch:l,interactionCommand:"press",interactionPositionals:[String(S),String(_)],outPath:t.flags?.out,buildPayloads:e=>{let t=uO({data:e,fallbackX:S,fallbackY:_,referenceFrame:uU(A.nodes),extra:{selector:y.selector.raw,selectorChain:N,refLabel:D,...m}});return{result:t,responseData:t}}})}if("fill"===u){let e=a.get(r);if(e){let t=uR(e,u);if(t)return t}if(e&&!o5("fill",e.device))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"fill is not supported on this device"}};if(t.positionals?.[0]?.startsWith("@")){if(!e)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};let r=s("fill",t.flags);if(r)return r;let d=t.positionals.length>=3?t.positionals[1]:"",c=t.positionals.length>=3?t.positionals.slice(2).join(" "):t.positionals.slice(1).join(" ");if(!c)return{ok:!1,error:{code:"INVALID_ARGS",message:"fill requires text after ref"}};let p=await uF({session:e,refInput:t.positionals[0],fallbackLabel:d,invalidRefMessage:"fill requires a ref like @e2",missingBoundsMessage:`Ref ${t.positionals[0]} not found or has no bounds`,invalidBoundsMessage:`Ref ${t.positionals[0]} not found or has invalid bounds`,reqFlags:t.flags,sessionStore:a,contextFromFlags:i,captureSnapshotForSession:n,dispatch:l,resolveRefTarget:o});if(!p.ok)return p.response;let{ref:f,node:m,snapshotNodes:h,point:w}=p.target,g=m.type??"",v=g&&!sp(g,e.device.platform)?`fill target ${t.positionals[0]} resolved to "${g}", attempting fill anyway.`:void 0,I=sl(m,h),A=sC(m,e.device.platform,{action:"fill"}),{x:y,y:b}=w;return uL({session:e,sessionStore:a,requestCommand:u,requestPositionals:t.positionals??[],flags:t.flags,contextFromFlags:i,dispatch:l,interactionCommand:"fill",interactionPositionals:[String(y),String(b),c],outPath:t.flags?.out,buildPayloads:e=>{let t=uO({data:e,fallbackX:y,fallbackY:b,referenceFrame:uU(h),extra:{ref:f,refLabel:I,selectorChain:A}}),r={...e??{ref:f,x:y,y:b}};return v&&(t.warning=v,r.warning=v),{result:t,responseData:r}}})}if(!e)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};let d=sI(t.positionals??[],{preferTrailingValue:!0});if(d){if(0===d.rest.length)return{ok:!1,error:{code:"INVALID_ARGS",message:"fill requires text after selector"}};let r=d.rest.join(" ").trim();if(!r)return{ok:!1,error:{code:"INVALID_ARGS",message:"fill requires text after selector"}};let o=sg(d.selectorExpression),s=await n(e,t.flags,a,i,{interactiveOnly:!0},l),c=await O("selector_resolve",()=>sM(s.nodes,o,{platform:e.device.platform,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0}),{command:u});if(!c||!c.node.rect)return{ok:!1,error:{code:"COMMAND_FAILED",message:sO(o,c?.diagnostics??[],{unique:!0})}};let p=c.node,f=p.type??"",m=f&&!sp(f,e.device.platform)?`fill target ${c.selector.raw} resolved to "${f}", attempting fill anyway.`:void 0,{x:h,y:w}=so(c.node.rect),g=sC(p,e.device.platform,{action:"fill"});return uL({session:e,sessionStore:a,requestCommand:u,requestPositionals:t.positionals??[],flags:t.flags,contextFromFlags:i,dispatch:l,interactionCommand:"fill",interactionPositionals:[String(h),String(w),r],outPath:t.flags?.out,buildPayloads:e=>{let t=uO({data:e,fallbackX:h,fallbackY:w,referenceFrame:uU(s.nodes),extra:{text:r,selector:c.selector.raw,selectorChain:g,refLabel:sl(p,s.nodes)}});return m&&(t.warning=m),{result:t,responseData:t}}})}return{ok:!1,error:{code:"INVALID_ARGS",message:"fill requires x y text, @ref text, or selector text"}}}return null}function uR(e,t){return"macos"!==e.device.platform||"desktop"!==e.surface&&"menubar"!==e.surface?null:{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:`${t} is not supported on macOS ${e.surface} sessions yet. Open an app session to act, or use the ${e.surface} surface to inspect.`}}}async function uT(e){let{session:t,flags:r,sessionStore:a,contextFromFlags:i,captureSnapshotForSession:n,dispatch:o,readAndroidScreenSize:s}=e;if(!t.recording)return;if(t.recording.touchReferenceFrame)return t.recording.touchReferenceFrame;if("android"===t.device.platform){let e=await s(t.device),r={referenceWidth:e.width,referenceHeight:e.height};return t.recording&&(t.recording.touchReferenceFrame=r),r}let l=ug(t.snapshot);if(l)return t.recording&&(t.recording.touchReferenceFrame=l),l;if(!t.recording)return;let d=ug(await n(t,r,a,i,{interactiveOnly:!0},o));return d&&t.recording&&(t.recording.touchReferenceFrame=d),d}async function u$(e){try{return await uT(e)}catch(t){C({level:"warn",phase:"touch_reference_frame_resolve_failed",data:{platform:e.session.device.platform,error:t instanceof Error?t.message:String(t)}});return}}async function uF(e){let{session:t,refInput:r,fallbackLabel:a,invalidRefMessage:i,missingBoundsMessage:n,invalidBoundsMessage:o,reqFlags:s,sessionStore:l,contextFromFlags:d,captureSnapshotForSession:u,dispatch:c,resolveRefTarget:p}=e,f=p({session:t,refInput:r,fallbackLabel:a,requireRect:!0,invalidRefMessage:i,notFoundMessage:n});if(!f.ok)return{ok:!1,response:f.response};let{ref:m}=f.target,h=f.target.node,w=f.target.snapshotNodes,g=uV(h.rect);if(!g){let e=await u(t,s,l,d,{interactiveOnly:!0},c),r=sn(e.nodes,m),i=a.length>0?ss(e.nodes,a):null,n=uV(i?.rect),o=uV(r?.rect)?r:n?i:r??i,p=uV(o?.rect);o&&p&&(h=o,w=e.nodes,g=p)}return g?{ok:!0,target:{ref:m,node:h,snapshotNodes:w,point:g}}:{ok:!1,response:{ok:!1,error:{code:"COMMAND_FAILED",message:o}}}}function uU(e){return ug({nodes:e,createdAt:0})}function uV(e){let t=function(e){if(!e)return null;let t=Number(e.x),r=Number(e.y),a=Number(e.width),i=Number(e.height);return Number.isFinite(t)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(i)&&!(a<0)&&!(i<0)?{x:t,y:r,width:a,height:i}:null}(e);if(!t)return null;let r=so(t);return Number.isFinite(r.x)&&Number.isFinite(r.y)?r:null}let uG=[["snapshotDepth","--depth"],["snapshotScope","--scope"],["snapshotRaw","--raw"]];function uB(e,t){let r=function(e){if(!e)return[];let t=[];for(let[r,a]of uG)void 0!==e[r]&&t.push(a);return t}(t);return 0===r.length?null:{ok:!1,error:{code:"INVALID_ARGS",message:`${e} @ref does not support ${r.join(", ")}.`}}}async function uj(e,t,r,a,i,n=o3){let o={...t??{},snapshotInteractiveOnly:i.interactiveOnly,snapshotCompact:i.interactiveOnly},s=a(o,e.appBundleId,e.trace?.outPath),{snapshot:l}=await dI({dispatchSnapshotCommand:n,device:e.device,session:e,flags:o,outPath:o.out,logPath:s.logPath??""});return e.snapshot=l,r.set(e.name,e),e.snapshot}async function uq(e){let{command:t,selectorExpression:r,session:a,flags:i,sessionStore:n,contextFromFlags:o,interactiveOnly:s,requireRect:l,requireUnique:d,disambiguateAmbiguous:u,dispatch:c}=e,p=sg(r),f=await uj(a,i,n,o,{interactiveOnly:s},c),m=await O("selector_resolve",()=>sM(f.nodes,p,{platform:a.device.platform,requireRect:l,requireUnique:d,disambiguateAmbiguous:u}),{command:t});return m&&(!l||m.node.rect)?{ok:!0,chain:p,snapshot:f,resolved:m}:{ok:!1,response:{ok:!1,error:{code:"COMMAND_FAILED",message:sO(p,m?.diagnostics??[],{unique:d})}}}}async function uH(e){let{req:t,sessionName:r,sessionStore:a,contextFromFlags:i,dispatch:n}=e,o=t.positionals?.[0];if("text"!==o&&"attrs"!==o)return{ok:!1,error:{code:"INVALID_ARGS",message:"get only supports text or attrs"}};let s=a.get(r);if(!s)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};if(!o5("get",s.device))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"get is not supported on this device"}};let l=t.positionals?.[1]??"";if(l.startsWith("@")){let e=uB("get",t.flags);if(e)return e;let r=dU({session:s,refInput:l,fallbackLabel:t.positionals.length>2?t.positionals.slice(2).join(" ").trim():"",requireRect:!1,invalidRefMessage:"get text requires a ref like @e2",notFoundMessage:`Ref ${l} not found`});if(!r.ok)return r.response;let{ref:d,node:u}=r.target,c=sC(u,s.device.platform,{action:"get"});if("attrs"===o)return a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{ref:d,selectorChain:c}}),{ok:!0,data:{ref:d,node:u}};let p=await dV({device:s.device,node:u,flags:t.flags,appBundleId:s.appBundleId,traceOutPath:s.trace?.outPath,surface:s.surface,contextFromFlags:i,dispatch:n});return a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{ref:d,text:p,refLabel:uW(p),selectorChain:c}}),{ok:!0,data:{ref:d,text:p,node:u}}}let d=t.positionals.slice(1).join(" ").trim();if(!d)return{ok:!1,error:{code:"INVALID_ARGS",message:"get requires @ref or selector expression"}};let u=await uq({command:t.command,selectorExpression:d,session:s,flags:t.flags,sessionStore:a,contextFromFlags:i,interactiveOnly:!1,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:"text"===o,dispatch:n});if(!u.ok)return u.response;let{resolved:c}=u,p=c.node,f=sC(p,s.device.platform,{action:"get"});if("attrs"===o)return a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{selector:c.selector.raw,selectorChain:f}}),{ok:!0,data:{selector:c.selector.raw,node:p}};let m=await dV({device:s.device,node:p,flags:t.flags,appBundleId:s.appBundleId,traceOutPath:s.trace?.outPath,surface:s.surface,contextFromFlags:i,dispatch:n});return a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{text:m,refLabel:uW(m),selector:c.selector.raw,selectorChain:f}}),{ok:!0,data:{selector:c.selector.raw,text:m,node:p}}}function uW(e){let t=e.trim();if(!(!t||t.length>80||/[\r\n]/.test(t)))return t}async function uz(e){let{req:t,sessionName:r,sessionStore:a,contextFromFlags:i,dispatch:n}=e,o=(t.positionals?.[0]??"").toLowerCase();if(!["visible","hidden","exists","editable","selected","text"].includes(o))return{ok:!1,error:{code:"INVALID_ARGS",message:"is requires predicate: visible|hidden|exists|editable|selected|text"}};let s=a.get(r);if(!s)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};if(!o5("is",s.device))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"is is not supported on this device"}};let{split:l}=sA(t.positionals);if(!l)return{ok:!1,error:{code:"INVALID_ARGS",message:"is requires a selector expression"}};let d=l.rest.join(" ").trim();if("text"===o&&!d)return{ok:!1,error:{code:"INVALID_ARGS",message:"is text requires expected text value"}};if("text"!==o&&l.rest.length>0)return{ok:!1,error:{code:"INVALID_ARGS",message:`is ${o} does not accept trailing values`}};let u=sg(l.selectorExpression);if("exists"===o){let e=sx((await uj(s,t.flags,a,i,{interactiveOnly:!1},n)).nodes,u,{platform:s.device.platform});return e?(a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{predicate:o,selector:e.selector.raw,selectorChain:u.selectors.map(e=>e.raw),pass:!0,matches:e.matches}}),{ok:!0,data:{predicate:o,pass:!0,selector:e.selector.raw,matches:e.matches}}):{ok:!1,error:{code:"COMMAND_FAILED",message:sO(u,[],{unique:!1})}}}let c=await uq({command:"is",selectorExpression:l.selectorExpression,session:s,flags:t.flags,sessionStore:a,contextFromFlags:i,interactiveOnly:!1,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:!1,dispatch:n});if(!c.ok)return c.response;let{resolved:p}=c,f=function(e){let{predicate:t,node:r,expectedText:a,platform:i}=e,n=sf(r),o=!1;switch(t){case"visible":o=sN(r);break;case"hidden":o=!sN(r);break;case"editable":o=sD(r,i);break;case"selected":o=!0===r.selected;break;case"text":o=n===(a??"")}let s="text"===t?`expected="${a??""}" actual="${n}"`:`actual=${JSON.stringify({visible:sN(r),editable:sD(r,i),selected:!0===r.selected})}`;return{pass:o,actualText:n,details:s}}({predicate:o,node:p.node,expectedText:d,platform:s.device.platform});return f.pass?(a.recordAction(s,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{predicate:o,selector:p.selector.raw,selectorChain:u.selectors.map(e=>e.raw),pass:!0,text:"text"===o?f.actualText:void 0}}),{ok:!0,data:{predicate:o,pass:!0,selector:p.selector.raw}}):{ok:!1,error:{code:"COMMAND_FAILED",message:`is ${o} failed for selector ${p.selector.raw}: ${f.details}`}}}function uJ(e,t,r){return t>=e.x&&t<=e.x+e.width&&r>=e.y&&r<=e.y+e.height}function uX(e){let t=null,r=-1;for(let a of e){let e=a.width*a.height;e>r&&(t=a,r=e)}return t}function uK(e,t,r){return Math.min(r,Math.max(t,Math.round(e)))}async function uY(e){let{req:t,sessionName:r,sessionStore:a,contextFromFlags:i,dispatch:n}=e,o=a.get(r);if(!o)return{ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}};if(!o5("scrollintoview",o.device))return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:"scrollintoview is not supported on this device"}};let s=t.positionals?.[0]??"";if(!s.startsWith("@"))return null;let l=uB("scrollintoview",t.flags);if(l)return l;let d=dU({session:o,refInput:s,fallbackLabel:t.positionals&&t.positionals.length>1?t.positionals.slice(1).join(" ").trim():"",requireRect:!0,invalidRefMessage:"scrollintoview requires a ref like @e2",notFoundMessage:`Ref ${s} not found or has no bounds`});if(!d.ok)return d.response;let{ref:u,node:c,snapshotNodes:p}=d.target;if(!c.rect)return{ok:!1,error:{code:"COMMAND_FAILED",message:`Ref ${s} not found or has no bounds`}};let f=function(e,t){let r=so(t),a=e.filter(e=>{var t;return!!(t=e.rect)&&Number.isFinite(t.x)&&Number.isFinite(t.y)&&Number.isFinite(t.width)&&Number.isFinite(t.height)}),i=a.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}),n=uX(i.map(e=>e.rect).filter(e=>uJ(e,r.x,r.y)));if(n)return n;let o=uX(i.map(e=>e.rect));if(o)return o;let s=uX(a.map(e=>e.rect).filter(e=>uJ(e,r.x,r.y)));return s||null}(p,c.rect);if(!f)return{ok:!1,error:{code:"COMMAND_FAILED",message:`scrollintoview could not infer viewport for ${s}`}};let m=function(e,t){var r,a;let i=Math.max(1,t.height),n=Math.max(1,t.width),o=t.y,s=t.y+i,l=t.x,d=t.x+n,u=o+.25*i,c=s-.25*i,p=Math.max(8,.1*n),f=e.y+e.height/2,m=e.x+e.width/2;if(f>=u&&f<=c)return null;let h=Math.round((r=m,a=l+p,Math.min(d-p,Math.max(a,r)))),w=Math.round(o+.86*i),g=Math.round(o+.14*i),v=Math.max(1,Math.abs(w-g));return f>c?{x:h,startY:w,endY:g,count:uK(Math.ceil((f-c)/v),1,50),direction:"down"}:{x:h,startY:g,endY:w,count:uK(Math.ceil((u-f)/v),1,50),direction:"up"}}(c.rect,f),h=sl(c,p),w=sC(c,o.device.platform,{action:"get"});if(!m)return a.recordAction(o,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{ref:u,attempts:0,alreadyVisible:!0,refLabel:h,selectorChain:w}}),{ok:!0,data:{ref:u,attempts:0,alreadyVisible:!0}};let g=await n(o.device,"swipe",[String(m.x),String(m.startY),String(m.x),String(m.endY),"16"],t.flags?.out,{...i(t.flags,o.appBundleId,o.trace?.outPath),count:m.count,pauseMs:0,pattern:"one-way"});return a.recordAction(o,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{...g??{},ref:u,attempts:m.count,direction:m.direction,refLabel:h,selectorChain:w}}),{ok:!0,data:{...g??{},ref:u,attempts:m.count,direction:m.direction}}}async function uZ(e){let t=e.dispatch??o3,r=e.readAndroidScreenSize??iI,a={...e,dispatch:t},i=await uP({...a,readAndroidScreenSize:r,captureSnapshotForSession:uj,resolveRefTarget:dU,refSnapshotFlagGuardResponse:uB});if(i)return i;switch(e.req.command){case"get":return await uH(a);case"is":return await uz(a);case"scrollintoview":return await uY(a);default:return null}}function uQ(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 u0(e){let{req:t,leaseRegistry:r}=e,a=uQ(t);switch(t.command){case"lease_allocate":return{ok:!0,data:{lease:r.allocateLease({tenantId:a.tenantId??"",runId:a.runId??"",backend:a.leaseBackend,ttlMs:a.leaseTtlMs})}};case"lease_heartbeat":return{ok:!0,data:{lease:r.heartbeatLease({leaseId:a.leaseId??"",tenantId:a.tenantId,runId:a.runId,ttlMs:a.leaseTtlMs})}};case"lease_release":return{ok:!0,data:r.releaseLease({leaseId:a.leaseId??"",tenantId:a.tenantId,runId:a.runId})};default:return null}}function u1(e,t){if(!t)return[];let r=[],a=e.device,i=t.platform;if(i&&!e2(a.platform,i)&&r.push({key:"platform",value:t.platform}),t.target&&t.target!==(a.target??"mobile")&&r.push({key:"target",value:t.target}),t.udid&&("ios"!==a.platform||t.udid!==a.id)&&r.push({key:"udid",value:t.udid}),t.serial&&("android"!==a.platform||t.serial!==a.id)&&r.push({key:"serial",value:t.serial}),t.device&&t.device.trim().toLowerCase()!==a.name.trim().toLowerCase()&&r.push({key:"device",value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),i=a.simulatorSetPath?.trim();("ios"!==a.platform||"simulator"!==a.kind||e!==i)&&r.push({key:"iosSimulatorDeviceSet",value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=eP(t.androidDeviceAllowlist);"android"===a.platform&&e.has(a.id)||r.push({key:"androidDeviceAllowlist",value:t.androidDeviceAllowlist})}return r}function u2(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 u3=["target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist"],u4=/\bis(?:n't| not)\s+responding\b/i,u8=/^close app$/i;async function u5(e){let{session:t,snapshotAndroidUi:r=it,reopenAndroidApp:a=aG,readAndroidAppState:i=aU,execCommand:n=m}=e;if("android"!==t.device.platform||!t.recording)return"absent";try{let e=await u6(t,r),o=function(e){if(ct(e))return e.find(e=>{let t=ce(e);return t.length>0&&u8.test(t)&&e.rect})}(e);if(!o?.rect)return"absent";let{x:s,y:l}=so(o.rect),d=await n("adb",rR(t.device,["shell","input","tap",String(Math.round(s)),String(Math.round(l))]),{allowFailure:!0});if(0!==d.exitCode)return C({level:"warn",phase:"android_blocking_dialog_tap_failed",data:{session:t.name,deviceId:t.device.id,exitCode:d.exitCode,stdout:d.stdout.trim(),stderr:d.stderr.trim()}}),"failed";if(!await u9(t,r))return C({level:"warn",phase:"android_blocking_dialog_still_present",data:{session:t.name,deviceId:t.device.id}}),"failed";if(t.appBundleId&&(await a(t.device,t.appBundleId),!await u7(t,t.appBundleId,i)))return C({level:"warn",phase:"android_blocking_dialog_relaunch_unfocused",data:{session:t.name,deviceId:t.device.id,appBundleId:t.appBundleId}}),"failed";return C({level:"warn",phase:"android_blocking_dialog_recovered",data:{session:t.name,deviceId:t.device.id,appBundleId:t.appBundleId,x:s,y:l}}),"recovered"}catch(e){return C({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 u6(e,t){return sa(su((await t(e.device,{interactiveOnly:!1,compact:!1})).nodes))}async function u9(e,t){for(let r=0;r<12;r+=1){if(!ct(await u6(e,t)))return!0;await cr(500)}return!ct(await u6(e,t))}async function u7(e,t,r){for(let a=0;a<12;a+=1){if((await r(e.device)).package===t)return!0;await cr(500)}return(await r(e.device)).package===t}function ce(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).join(" ").trim()}function ct(e){return e.some(e=>{let t=ce(e);return t.length>0&&u4.test(t)})}function cr(e){return new Promise(t=>setTimeout(t,e))}let ca=new Set(["session_list","devices","ensure-simulator","release_materialized_paths"]),ci=new Set(["session_list","devices","ensure-simulator","release_materialized_paths","lease_allocate","lease_heartbeat","lease_release"]);function cn(e,t,r,a){let i=M().requestId;return{...o6(e,t,r,a,i),requestId:i}}function co(e){F.existsSync(e)&&F.unlinkSync(e)}function cs(e){if(!F.existsSync(e))return null;try{let t=JSON.parse(F.readFileSync(e,"utf8"));if(!Number.isInteger(t.pid)||t.pid<=0)return null;return t}catch{return null}}function cl(e){let t=cs(e);if(!t||t.pid===process.pid)try{F.existsSync(e)&&F.unlinkSync(e)}catch{}}function cd(e){if(void 0===e)return;let t=Number(e);if(Number.isInteger(t))return t}let{baseDir:cu,infoPath:cc,lockPath:cp,logPath:cf,sessionsDir:cm}=j(process.env.AGENT_DEVICE_STATE_DIR),ch=B(process.env.AGENT_DEVICE_DAEMON_SERVER_MODE);var cw=cm;if(F.existsSync(cw))for(let e of F.readdirSync(cw,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=o.join(cw,e.name,"app-log.pid");if(F.existsSync(t))try{let e=function(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}}(F.readFileSync(t,"utf8"));if(e&&function(e){let t,r=T(e.pid);if(!r||e.startTime&&r!==e.startTime)return!1;let a=s(e.pid);return!!a&&!!((t=a.toLowerCase().replaceAll("\\","/")).includes("log stream")||t.includes("logcat")||t.includes("devicectl device log stream"))&&(!e.command||a===e.command)}(e))try{process.kill(e.pid,"SIGTERM")}catch{}}catch{}finally{tW(t)}}let cg=new tq(cm),cv=new rM({maxActiveSimulatorLeases:cd(process.env.AGENT_DEVICE_MAX_SIMULATOR_LEASES),defaultLeaseTtlMs:cd(process.env.AGENT_DEVICE_LEASE_TTL_MS),minLeaseTtlMs:cd(process.env.AGENT_DEVICE_LEASE_MIN_TTL_MS),maxLeaseTtlMs:cd(process.env.AGENT_DEVICE_LEASE_MAX_TTL_MS)}),cI=k(),cA=f.randomBytes(24).toString("hex"),cy=T(process.pid)??void 0,cb=function(){let e=process.argv[1];if(!e)return"unknown";try{let t=F.statSync(e),r=L(),a=o.relative(r,e)||e;return`${a}:${t.size}:${Math.trunc(t.mtimeMs)}`}catch{return"unknown"}}(),cS=function(e){let{logPath:t,token:r,sessionStore:a,leaseRegistry:i,trackDownloadableArtifact:n}=e,s=e.dispatchCommand??o3,d=e.snapshotAndroidUi??it,u=e.reopenAndroidApp??aG,c=e.readAndroidAppState??aU,p=e.execCommand??m;async function f(e){let m=!!(e.meta?.debug||e.flags?.verbose);return await $({session:e.session,requestId:e.meta?.requestId,command:e.command,debug:m,logPath:t},async()=>{if(e.token!==r)return{ok:!1,error:N(new I("UNAUTHORIZED","Invalid token"))};try{let r=function(e){let t=D(e.meta?.sessionIsolation??e.flags?.sessionIsolation),r=e.meta?.tenantId??e.flags?.tenant,a=l(r);if(r&&!a)throw new I("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if("tenant"!==t)return e;if(!a)throw new I("INVALID_ARGS","session isolation mode tenant requires --tenant (or meta.tenantId).");let i=e.session||"default";return i.startsWith(`${a}:`)?{...e,meta:{...e.meta,tenantId:a,sessionIsolation:t}}:{...e,session:`${a}:${i}`,meta:{...e.meta,tenantId:a,sessionIsolation:t}}}(e);C({level:"info",phase:"request_start",data:{session:r.session,command:r.command,tenant:r.meta?.tenantId,isolation:r.meta?.sessionIsolation}});let m=r.command,h=uQ(r);ci.has(m)||r.meta?.sessionIsolation!=="tenant"||i.assertLeaseAdmission({tenantId:h.tenantId,runId:h.runId,leaseId:h.leaseId,backend:h.leaseBackend});let w=function(e,t){var r;let a,i=e.session||"default";if(r=e,a=r.flags?.session,"string"==typeof a&&a.trim().length>0||"default"!==i||t.has(i))return i;let n=t.toArray();return 1===n.length?n[0].name:i}(r,a),g=a.get(w);g&&(!function(e){var t,r;let a,i=e.recording;if(!i||"ios"!==e.device.platform)return;let n=(t=e.device.id,(a=tm.get(t))?{sessionId:a.sessionId,alive:!!(r=a.child.pid)&&R(r)}:null);if(!i.runnerSessionId){n?.alive&&(i.runnerSessionId=n.sessionId);return}if(!n?.alive){i.invalidatedReason??="iOS runner session exited during recording";return}n.sessionId!==i.runnerSessionId&&(i.invalidatedReason??="iOS runner session restarted during recording")}(g),a.set(w,g));let v=function(e,t){let r=e.meta?.lockPolicy;if(!r)return e;let a={...e.flags??{}},i=t?u1(t,a):function(e,t){var r,a;let i=[];for(let n of(void 0!==e.platform&&t&&(r=e.platform,a=t,r&&a&&r!==a&&("apple"===r?!e1(a):"apple"!==a||!e1(r)))&&i.push({key:"platform",value:e.platform}),u3)){let t=e[n];"string"==typeof t&&t.trim().length>0&&i.push({key:n,value:t})}return i}(a,e.meta?.lockPlatform);if(0===i.length)return!t&&e.meta?.lockPlatform&&void 0===a.platform&&(a.platform=e.meta.lockPlatform),{...e,flags:a};if("strip"===r)return t?(function(e,t){for(let r of t)delete e[r.key]}(a,i),a.platform=t.device.platform):function(e,t){for(let t of u3)delete e[t];t&&(e.platform=t)}(a,e.meta?.lockPlatform),{...e,flags:a};throw new I("INVALID_ARGS",`${e.command} cannot override session lock policy with ${i.map(u2).join(", ")}. Unset those selectors or remove the request lock policy.`)}(r,g),A=e=>(function(e,t,r){let a=M();if(!t.ok){C({level:"error",phase:"request_failed",data:{code:t.error.code,message:t.error.message}});let e=U({force:!0})??void 0;return{ok:!1,error:N(new I(t.error.code,t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath}),{diagnosticId:a.diagnosticId,logPath:e})}}return C({level:"info",phase:"request_success"}),U(),{ok:!0,data:function(e,t,r){var a,i;let n;if(!t)return t;let s=(a=e,i=t,n=Array.isArray(i.artifacts)?[...i.artifacts]:[],"screenshot"!==a.command||n.some(e=>e?.field==="path")||"string"!=typeof i.path||n.push({field:"path",path:i.path,localPath:a.meta?.clientArtifactPaths?.path,fileName:o.basename(a.meta?.clientArtifactPaths?.path??i.path)}),n.filter(e=>!!(e&&"string"==typeof e.field&&"string"==typeof e.path&&"string"==typeof e.localPath&&e.localPath.length>0)));return 0===s.length?t:{...t,artifacts:s.map(t=>{let a=t.path;return{field:t.field,artifactId:r({artifactPath:a,tenantId:e.meta?.tenantId,fileName:t.fileName}),fileName:t.fileName,localPath:t.localPath}})}}(e,t.data,r)}})(v,e,n);if(g?.recording?.invalidatedReason&&"record"!==m&&"close"!==m)return A({ok:!1,error:{code:"COMMAND_FAILED",message:g.recording.invalidatedReason}});!g||v.meta?.lockPolicy||ca.has(m)||function(e,t){let r=u1(e,t);if(0!==r.length){var a;let t,i,n;throw new I("INVALID_ARGS",`Session "${e.name}" is bound to ${(t=(a=e).device.platform,i=a.device.name.trim(),n=a.device.id,`${t} device "${i}" (${n})`)} and cannot be used with ${r.map(u2).join(", ")}. Use a different --session name or close this session first.`)}}(g,v.flags);let y=await u0({req:v,leaseRegistry:i});if(y)return A(y);let b=await dc({req:v,sessionName:w,logPath:t,sessionStore:a,invoke:f});if(b)return A(b);let S=await dR({req:v,sessionName:w,logPath:t,sessionStore:a});if(S)return A(S);let _=await uh({req:v,sessionName:w,sessionStore:a,logPath:t});if(_)return A(_);let E=await dG({req:v,sessionName:w,logPath:t,sessionStore:a,invoke:f});if(E)return A(E);let k=await uZ({req:v,sessionName:w,sessionStore:a,contextFromFlags:(e,r,a)=>cn(t,e,r,a)});if(k)return A(k);let x=a.get(w);if(!x)return A({ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}});if(!o5(m,x.device))return A({ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:`${m} is not supported on this device`}});if("android"===x.device.platform&&x.recording&&"record"!==m){let e=await u5({session:x,snapshotAndroidUi:d,reopenAndroidApp:u,readAndroidAppState:c,execCommand:p});if("failed"===e)return A({ok:!1,error:{code:"COMMAND_FAILED",message:"Android system dialog blocked the recording session"}})}let O=v.positionals??[],L=v.flags?.out,P="screenshot"===m&&O[0]?[tq.expandHome(O[0],v.meta?.cwd),...O.slice(1)]:O,T="screenshot"===m&&L?tq.expandHome(L,v.meta?.cwd):L,$="screenshot"===m?P:O,F="screenshot"===m&&T?{...v.flags??{},out:T}:v.flags??{},V=Date.now(),G={...cn(t,v.flags,x.appBundleId,x.trace?.outPath)},B=await s(x.device,m,P,T,{...G}),j=Date.now(),q=function(e,t,r,a){var i;if("scroll"!==t)return a;let n=ug(e.snapshot),o={...a??{}},s=u_(o.direction)??u_(r[0]);if(!s)return a;let l=uN(o.amount)??uN(r[1]),d=(i=l,void 0===i||!Number.isFinite(i)||i<=0?.4:i<=1?uE(i,.2,.7):uE(i/100,.2,.7)),u=uN(o.referenceWidth),c=uN(o.referenceHeight),p=void 0!==u&&u>0&&void 0!==c&&c>0?{referenceWidth:u,referenceHeight:c}:n??uA,{start:f,end:m}=function(e,t,r){let a=Math.round(t.referenceWidth/2),i=Math.round(t.referenceHeight/2),n=Math.round(t.referenceWidth*r/2),o=Math.round(t.referenceHeight*r/2);switch(e){case"up":return{start:{x:a,y:i-o},end:{x:a,y:i+o}};case"down":return{start:{x:a,y:i+o},end:{x:a,y:i-o}};case"left":return{start:{x:a-n,y:i},end:{x:a+n,y:i}};case"right":return{start:{x:a+n,y:i},end:{x:a-n,y:i}}}}(s,p,d);return{...o,x1:f.x,y1:f.y,x2:m.x,y2:m.y,contentDirection:s,amount:l,referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight,durationMs:250}}(x,m,P,B);return uy(x,m,P,q,v.flags??{},V,j),a.recordAction(x,{command:m,positionals:$,flags:F,result:B??{}}),A({ok:!0,data:B??{}})}catch(r){C({level:"error",phase:"request_failed",data:{error:r instanceof Error?r.message:String(r)}});let e=M(),t=U({force:!0})??void 0;return{ok:!1,error:N(r,{diagnosticId:e.diagnosticId,logPath:t})}}})}return f}({logPath:cf,token:cA,sessionStore:cg,leaseRegistry:cv,trackDownloadableArtifact:function(e){let t=f.randomUUID(),r=setTimeout(()=>{re(t)},9e5);return r.unref(),t7.set(t,{artifactPath:e.artifactPath,tenantId:e.tenantId,fileName:e.fileName,deleteAfterDownload:!1!==e.deleteAfterDownload,timer:r}),t}});!async function(){let e,t;if(!function(e,t,r){F.existsSync(e)||F.mkdirSync(e,{recursive:!0});let a=JSON.stringify(r,null,2),i=()=>{try{return F.writeFileSync(t,a,{flag:"wx",mode:384}),!0}catch(e){if("EEXIST"===e.code)return!1;throw e}};if(i())return!0;let n=cs(t);if(n?.pid&&n.pid!==process.pid&&p(n.pid,n.processStartTime))return!1;try{F.unlinkSync(t)}catch{}return i()}(cu,cp,{pid:process.pid,version:cI,startedAt:Date.now(),processStartTime:cy})){process.stderr.write("Daemon lock is held by another process; exiting.\n"),process.exit(0);return}let r=[];try{var a;let i;if("socket"===ch||"dual"===ch){let t=G.createServer(e=>{let t="",r=0,a=new Set,i=!1,n=()=>{if(!i&&0!==r){for(let e of(i=!0,a))ew(e);C({level:"warn",phase:"request_client_disconnected",data:{inFlightRequests:r}}),(async()=>{let e=Date.now()+15e3;for(;r>0&&Date.now()<e&&(await ty(),!(r<=0));)await new Promise(e=>setTimeout(e,200))})()}};e.setEncoding("utf8"),e.on("close",n),e.on("error",n),e.on("data",async i=>{let n=(t+=i).indexOf("\n");for(;-1!==n;){let i,o,s=t.slice(0,n).trim();if(t=t.slice(n+1),0===s.length){n=t.indexOf("\n");continue}r+=1;try{let e=JSON.parse(s);if(o=em(e.meta?.requestId,"socket"),e.meta={...e.meta,requestId:o},a.add(o),eh(o),ev(o))throw eA();i=await cS(e)}catch(e){i={ok:!1,error:N(e)}}finally{r-=1,o&&(a.delete(o),eg(o))}e.destroyed||e.write(`${JSON.stringify(i)}
64
+ `),n=t.indexOf("\n")}})});r.push(t),e=await new Promise((e,r)=>{t.once("error",r),t.listen(0,"127.0.0.1",()=>{t.off("error",r);let a=t.address();"object"==typeof a&&a?.port?e(a.port):r(new I("COMMAND_FAILED","Failed to bind socket server"))})})}if("http"===ch||"dual"===ch){let e=await rb({handleRequest:cS,token:cA});r.push(e),t=await new Promise((t,r)=>{e.once("error",r),e.listen(0,"127.0.0.1",()=>{e.off("error",r);let a=e.address();"object"==typeof a&&a?.port?t(a.port):r(new I("COMMAND_FAILED","Failed to bind HTTP server"))})})}a={socketPort:e,httpPort:t,token:cA,version:cI,codeSignature:cb,processStartTime:cy},F.existsSync(cu)||F.mkdirSync(cu,{recursive:!0}),F.writeFileSync(cf,""),i=a.socketPort&&a.httpPort?"dual":a.httpPort?"http":"socket",F.writeFileSync(cc,JSON.stringify({port:a.socketPort,httpPort:a.httpPort,transport:i,token:a.token,pid:process.pid,version:a.version,codeSignature:a.codeSignature,processStartTime:a.processStartTime,stateDir:cu},null,2),{mode:384}),e&&process.stdout.write(`AGENT_DEVICE_DAEMON_PORT=${e}
39
65
  `),t&&process.stdout.write(`AGENT_DEVICE_DAEMON_HTTP_PORT=${t}
40
- `)}catch(t){let e=f(t);for(let t of(process.stderr.write(`Daemon error: ${e.message}
41
- `),r))try{t.close(()=>{})}catch{}dP(dV),d$(dG),process.exit(1);return}let i=!1,n=async()=>{await Promise.all(r.map(async e=>{await new Promise(t=>{try{e.close(()=>t())}catch{t()}})}))},o=async()=>{if(!i){for(let e of(i=!0,await n(),dW.toArray()))dW.writeSessionLog(e);await tm(),dP(dV),d$(dG),process.exit(0)}};process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),process.on("SIGHUP",()=>{o()}),process.on("uncaughtException",e=>{let t=e instanceof w?e:f(e);process.stderr.write(`Daemon error: ${t.message}
66
+ `)}catch(t){let e=w(t);for(let t of(process.stderr.write(`Daemon error: ${e.message}
67
+ `),r))try{t.close(()=>{})}catch{}co(cc),cl(cp),process.exit(1);return}let i=!1,n=async()=>{await Promise.all(r.map(async e=>{await new Promise(t=>{try{e.close(()=>t())}catch{t()}})}))},o=async()=>{if(!i){for(let e of(i=!0,await n(),cg.toArray()))cg.writeSessionLog(e);await tb(),co(cc),cl(cp),process.exit(0)}};process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),process.on("SIGHUP",()=>{o()}),process.on("uncaughtException",e=>{let t=e instanceof I?e:w(e);process.stderr.write(`Daemon error: ${t.message}
42
68
  `),o()})}();