agent-device 0.16.5 → 0.16.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.16.5.apk → agent-device-android-multitouch-helper-0.16.7.apk} +0 -0
  2. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.16.7.apk.sha256 +1 -0
  3. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.16.5.manifest.json → agent-device-android-multitouch-helper-0.16.7.manifest.json} +4 -4
  4. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.7.apk +0 -0
  5. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.7.apk.sha256 +1 -0
  6. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.16.5.manifest.json → agent-device-android-snapshot-helper-0.16.7.manifest.json} +6 -6
  7. package/dist/src/1010.js +1 -0
  8. package/dist/src/1231.js +1 -1
  9. package/dist/src/1352.js +1 -0
  10. package/dist/src/1998.js +1 -0
  11. package/dist/src/208.js +1 -1
  12. package/dist/src/221.js +6 -6
  13. package/dist/src/2415.js +31 -0
  14. package/dist/src/2805.js +1 -0
  15. package/dist/src/5186.js +1 -0
  16. package/dist/src/5310.js +1 -0
  17. package/dist/src/5792.js +1 -0
  18. package/dist/src/6085.js +1 -0
  19. package/dist/src/6629.js +1 -0
  20. package/dist/src/8114.js +4 -0
  21. package/dist/src/8133.js +1 -0
  22. package/dist/src/8502.js +1 -0
  23. package/dist/src/8699.js +1 -0
  24. package/dist/src/8806.js +7 -0
  25. package/dist/src/940.js +1 -1
  26. package/dist/src/9404.js +1 -0
  27. package/dist/src/9471.js +1 -0
  28. package/dist/src/9533.js +1 -0
  29. package/dist/src/9542.js +3 -3
  30. package/dist/src/9671.js +1 -0
  31. package/dist/src/android-adb.js +1 -1
  32. package/dist/src/android-snapshot-helper.d.ts +2 -1
  33. package/dist/src/android-snapshot-helper.js +1 -1
  34. package/dist/src/android.js +5 -0
  35. package/dist/src/apple.js +1 -0
  36. package/dist/src/apps.js +13 -0
  37. package/dist/src/args.js +449 -0
  38. package/dist/src/batch.js +1 -1
  39. package/dist/src/cli.js +36 -492
  40. package/dist/src/command-metadata.js +1 -0
  41. package/dist/src/command-surface.js +1 -0
  42. package/dist/src/contracts.d.ts +1 -0
  43. package/dist/src/devices.js +1 -0
  44. package/dist/src/devices~1.js +1 -0
  45. package/dist/src/devices~2.js +1 -0
  46. package/dist/src/find.js +1 -0
  47. package/dist/src/finders.d.ts +1 -0
  48. package/dist/src/generic.js +9 -0
  49. package/dist/src/index.d.ts +12 -0
  50. package/dist/src/input-actions.js +1 -0
  51. package/dist/src/input-actions~1.js +1 -0
  52. package/dist/src/interaction.js +1 -0
  53. package/dist/src/internal/bin.js +5 -2
  54. package/dist/src/internal/daemon.js +1 -100
  55. package/dist/src/lease.js +1 -0
  56. package/dist/src/linux.js +1 -0
  57. package/dist/src/notifications.js +1 -0
  58. package/dist/src/react-native.js +1 -0
  59. package/dist/src/record-trace.js +26 -0
  60. package/dist/src/recording-provider.js +1 -0
  61. package/dist/src/selector-runtime.js +1 -0
  62. package/dist/src/selectors.d.ts +1 -0
  63. package/dist/src/server.js +1 -1
  64. package/dist/src/session.js +29 -0
  65. package/dist/src/snapshot.js +2 -0
  66. package/package.json +4 -1
  67. package/server.json +2 -2
  68. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.16.5.apk.sha256 +0 -1
  69. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.5.apk +0 -0
  70. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.5.apk.sha256 +0 -1
  71. package/dist/src/1769.js +0 -7
  72. package/dist/src/6277.js +0 -4
  73. package/dist/src/7519.js +0 -1
  74. package/dist/src/89.js +0 -1
@@ -0,0 +1,13 @@
1
+ let e;import{promises as t}from"node:fs";import i from"node:os";import a from"node:path";import{fileURLToPath as r}from"node:url";import{AppError as n}from"./9152.js";import{runXcrun as o,IOS_RUNNER_CONTAINER_BUNDLE_IDS as l,resolveIosDevicectlHint as s,LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE as d,runIosRunnerCommand as u,resolveAppleToolProvider as c,runSimctlForDevice as p,IOS_DEVICECTL_DEFAULT_HINT as f,requireSimulatorDevice as w,buildSimctlArgsForDevice as m,runMacOsPermissionAction as h,parseXmlDocumentSync as y,runIosDevicectl as A,filterAppleAppsByBundlePrefix as I,runAppleToolCommand as g,listIosDeviceApps as v,quitMacOsApp as _,visitXmlPlistEntries as C,ensureBootedSimulator as b,readApplePlistJson as N,LAUNCH_CONSOLE_IOS_SIMULATOR_ONLY_MESSAGE as S,getSimulatorState as L}from"./2415.js";import{runCmd as D}from"./9818.js";import{materializeInstallablePath as M,isTrustedInstallSourceUrl as O}from"./989.js";import{parseAppearanceAction as P,summarizeCommandAttemptFailures as x,parseSettingState as F,parsePermissionTarget as R,parsePermissionAction as $}from"./6629.js";import{createAppResolutionCache as E,isDeepLinkTarget as k,resolveIosSimulatorDeviceSetPath as T,resolveIosDeviceDeepLinkBundleId as U,retryWithPolicy as B,Deadline as G}from"./8806.js";import{emitDiagnostic as V}from"./7599.js";import{requireLocationCoordinates as j}from"./1998.js";import{getUnsupportedMacOsSettingMessage as W}from"./1352.js";function K(e){if(!(e instanceof n)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{};if(4!==t.exitCode)return!1;let i=String(t.stderr??"").toLowerCase();return i.includes("fbsopenapplicationserviceerrordomain")&&i.includes("the request to open")}async function H(e,t){let i=await o(m(e,["get_app_container",e.id,t]),{allowFailure:!0});if(0!==i.exitCode)return{installed:!1};let a=i.stdout.trim();if(!a)return{installed:!1};let r=await g("plutil",["-extract","CFBundleExecutable","raw","-o","-",`${a}/Info.plist`],{allowFailure:!0});if(0!==r.exitCode||!r.stdout.trim())return{installed:!0};let n=r.stdout.trim(),l=`${a}/${n}`,s=await g("otool",["-l",l],{allowFailure:!0});if(0!==s.exitCode)return{installed:!0};let d=s.stdout.toLowerCase();return{installed:!0,simulatorCompatible:d.includes("iossimulator")||d.includes("platform 7")}}async function z(e,i){try{let t=await N(e),a=t?.[i];if("string"==typeof a&&a.length>0)return a}catch{}try{let t=await g("plutil",["-extract",i,"raw","-o","-",e],{allowFailure:!0});if(0===t.exitCode){let e=String(t.stdout??"").trim();if(e.length>0)return e}}catch{}try{var a,r;let n;return a=await t.readFile(e,"utf8"),r=i,C(y(a),(e,t)=>{void 0===n&&e===r&&"string"===t.name&&(n=t.text??void 0)}),n}catch{return}}async function q(e,t){let i;if("url"===e.kind&&!O(e.url))throw new n("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 a=await M({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||O(e.url),signal:t?.signal});try{let e=i=await Z(a.installablePath,t),r=await J(e.installPath);return{archivePath:a.archivePath??(a.installablePath.toLowerCase().endsWith(".ipa")?a.installablePath:void 0),installablePath:e.installPath,bundleId:r.bundleId,appName:r.appName,cleanup:async()=>{await e.cleanup(),await a.cleanup()}}}catch(e){try{await i?.cleanup()}finally{await a.cleanup()}throw e}}async function J(e){let t=a.join(e,"Info.plist"),[i,r,n]=await Promise.all([z(t,"CFBundleIdentifier"),z(t,"CFBundleDisplayName"),z(t,"CFBundleName")]);return{bundleId:i,appName:r??n}}async function Z(e,r){if(!e.toLowerCase().endsWith(".ipa"))return{installPath:e,cleanup:async()=>{}};let o=await t.mkdtemp(a.join(i.tmpdir(),"agent-device-ios-ipa-")),l=async()=>{await t.rm(o,{recursive:!0,force:!0})};try{await D("unzip",["-q",e,"-d",o]);let i=a.join(o,"Payload"),s=(await t.readdir(i,{withFileTypes:!0}).catch(()=>{throw new n("INVALID_ARGS","Invalid IPA: missing Payload directory")})).filter(e=>e.isDirectory()&&e.name.toLowerCase().endsWith(".app")).map(e=>({installPath:a.join(i,e.name),bundleName:e.name.replace(/\.app$/i,"")})),d=s[0];if(void 0!==d&&1===s.length)return{installPath:d.installPath,cleanup:l};if(0===s.length)throw new n("INVALID_ARGS","Invalid IPA: expected at least one .app under Payload, found 0");await Q(s);let u=r?.appIdentifierHint?.trim();if(u){let e=function(e,t){let i=t.toLowerCase(),a=e.filter(e=>e.bundleName.toLowerCase()===i);if(1===a.length)return a[0];if(a.length>1)throw new n("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()===i);if(1===t.length)return t[0]}}(s,u);if(e)return{installPath:e.installPath,cleanup:l};throw new n("INVALID_ARGS",`Invalid IPA: found ${s.length} .app bundles under Payload and none matched "${u}". Available bundles: ${s.map(X).join(", ")}`)}throw new n("INVALID_ARGS",`Invalid IPA: found ${s.length} .app bundles under Payload. Pass an app identifier or bundle name matching one of: ${s.map(X).join(", ")}`)}catch(e){throw await l(),e}}async function Q(e){await Promise.all(e.map(async e=>{if(e.bundleId&&e.appName)return;let t=await J(e.installPath);e.bundleId=e.bundleId??t.bundleId,e.appName=e.appName??t.appName}))}function X(e){let t=e.bundleId??e.appName;return t?`${e.bundleName}.app (${t})`:`${e.bundleName}.app`}let Y={settings:"com.apple.systempreferences"},ee=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/,et={platform:"macos",deviceId:"host",variant:"all"},ei=E();async function ea(e){let t=e.trim(),i=Y[t.toLowerCase()];if(i)return i;if(ee.test(t))return t;let a=ei.get(et,t);if(a)return a;let r=(await eu("all")).filter(e=>e.name.toLowerCase()===t.toLowerCase()),o=r[0];if(void 0!==o&&1===r.length)return ei.set(et,t,o.bundleId);if(r.length>1)throw new n("INVALID_ARGS",`Multiple apps matched "${e}"`,{matches:r});throw new n("APP_NOT_INSTALLED",`No app found matching "${e}"`)}async function er(e,t,i){let a=i?.url?.trim();if(a){if(!k(a))throw new n("INVALID_ARGS","open <app> <url> requires a valid URL target");let e=i?.appBundleId??await ea(t);await ec().openBundle(e,a);return}let r=t.trim();if(k(r))return void await ec().openTarget(r);let o=i?.appBundleId??await ea(r);await ec().openBundle(o)}async function en(e,t){let i=await ea(t),a=await _(i);if(a.running&&!a.terminated&&!a.forceTerminated)throw new n("COMMAND_FAILED",`Failed to close macOS app ${t}`,{bundleId:i,running:a.running,terminated:a.terminated,forceTerminated:a.forceTerminated})}async function eo(){return await ec().readClipboard()}async function el(e){await ec().writeClipboard(e)}async function es(){return await ec().readDarkMode()}async function ed(e){let t=P(e),i="toggle"===t?!await es():"dark"===t;await ec().setDarkMode(i)}async function eu(e){return await ec().listApps(e)}function ec(){let e=c().macosHost;if(!e)throw new n("UNSUPPORTED_OPERATION","macOS host provider is not available");return e}function ep(e){if(!(e instanceof n))return{reason:e instanceof Error?e.message:String(e)};let t=e.details??{},i=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:i}}let ef=["--time","9:41","--dataNetwork","wifi","--wifiMode","active","--wifiBars","3","--batteryState","charged","--batteryLevel","100"],ew={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"},em={1:"searching",2:"failed",3:"active"},eh={0:"notSupported",1:"searching",2:"failed",3:"active"};async function ey(e){let t=null,i=!1;try{t=await eI(e),i=!0}catch(t){e_(e,"snapshot_failed",t)}try{await eg(e),await ev(e,ef)}catch(t){e_(e,"prepare_failed",t)}return async()=>{await eA(e,i?t:null)}}async function eA(e,t){var i,a;let r;await eg(e),t&&await ev(e,(r=[],(i=t).dataNetwork&&r.push("--dataNetwork",i.dataNetwork),i.wifiMode&&r.push("--wifiMode",i.wifiMode),void 0!==i.wifiBars&&("wifi"===i.dataNetwork||i.wifiMode)&&r.push("--wifiBars",i.wifiBars),i.cellularMode&&r.push("--cellularMode",i.cellularMode),void 0!==i.cellularBars&&(i.cellularMode||(a=i.dataNetwork)&&"hide"!==a&&"wifi"!==a||void 0!==i.operatorName)&&r.push("--cellularBars",i.cellularBars),void 0!==i.operatorName&&r.push("--operatorName",i.operatorName),r))}async function eI(e){var t;let i=await (t=["status_bar",e.id,"list"],p(e,t,{allowFailure:!0}));if(0!==i.exitCode)throw new n("COMMAND_FAILED","Failed to read simulator status bar overrides",{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return function(e){let t={};for(let i 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(i);if(e){let i=Number(e[1]),a=ew[i];if(!a)throw new n("COMMAND_FAILED",`Unsupported simulator data network type: ${i}`);t.dataNetwork=a;continue}let a=/^WiFi Mode:\s+(\d+),\s+WiFi Bars:\s+(\d+)$/.exec(i);if(a){let e=em[Number(a[1])];e&&(t.wifiMode=e),t.wifiBars=a[2];continue}let r=/^Cell Mode:\s+(\d+),\s+Cell Bars:\s+(\d+)$/.exec(i);if(r){let e=Number(r[1]),i=eh[e];if(!i)throw new n("COMMAND_FAILED",`Unsupported simulator cellular mode: ${e}`);t.cellularMode=i,t.cellularBars=r[2];continue}let o=/^Operator Name:\s*(.*)$/.exec(i);if(o){t.operatorName=o[1]??"";continue}}return 0===Object.keys(t).length?null:t}(i.stdout)}async function eg(e){await p(e,["status_bar",e.id,"clear"],void 0)}async function ev(e,t){0!==t.length&&await p(e,["status_bar",e.id,"override",...t],void 0)}function e_(e,t,i){V({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...ep(i)}})}let eC={ensureBooted:b,prepareStatusBarForScreenshot:ey,captureWithRetry:eS,captureWithRunner:eL,shouldFallbackToRunner:eF};async function eb(e,t,i,a,r){if("macos"===e.platform)return void await eL(e,t,i,a,r);if("simulator"===e.kind)return void await eN(e,t,i,a,void 0,r);try{await A(["device","screenshot","--device",e.id,t],{action:"capture iOS screenshot",deviceId:e.id});return}catch(t){if(!function(e){if(!(e instanceof n)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},i="string"==typeof t.stdout?t.stdout:"",a="string"==typeof t.stderr?t.stderr:"",r=`${e.message}
2
+ ${i}
3
+ ${a}`.toLowerCase();return r.includes("unknown option '--device'")||r.includes("unknown subcommand")&&r.includes("screenshot")||r.includes("unrecognized subcommand")&&r.includes("screenshot")}(t))throw t;eP(e,"devicectl_screenshot",t)}await eL(e,t,i,a,r)}async function eN(e,t,i,a,r=eC,o){if("simulator"!==e.kind)throw new n("UNSUPPORTED_OPERATION","Simulator screenshot fallback flow supports only iOS simulators");let l="object"==typeof a&&null!==a?a:r;await l.ensureBooted(e);let s=async()=>{};try{s=await l.prepareStatusBarForScreenshot(e)}catch(t){ex(e,"prepare_failed",t)}try{try{await l.captureWithRetry(e,t);return}catch(t){if(!l.shouldFallbackToRunner(t))throw t;eP(e,"simctl_screenshot",t)}await l.captureWithRunner(e,t,i,"boolean"==typeof a?a:void 0,o)}finally{await s().catch(t=>ex(e,"restore_failed",t))}}async function eS(e,t){let i=G.fromTimeoutMs(2e4);await B(async({deadline:i})=>{var a;await (a=["io",e.id,"screenshot",t],p(e,a,{timeoutMs:Math.max(1e3,i?.remainingMs()??2e4)}))},{maxAttempts:5,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>eF(e)},{deadline:i,phase:"ios_simulator_screenshot"})}async function eL(e,i,a,r,o){let l=(await u(e,{command:"screenshot",appBundleId:a,fullscreen:r},o)).message;if(!l)throw new n("COMMAND_FAILED","Failed to capture iOS screenshot: runner returned no file path");"macos"===e.platform?await t.copyFile(l,i):"simulator"===e.kind?await eM(e,l,i):await eD(e,l,i)}async function eD(e,t,i){let a=G.fromTimeoutMs(2e4),r={exitCode:1,stdout:"",stderr:""};for(let n of l)if(0===(r=await o(["devicectl","device","copy","from","--device",e.id,"--source",t,"--destination",i,"--domain-type","appDataContainer","--domain-identifier",n],{allowFailure:!0,timeoutMs:eO(a,2e4,"runner screenshot copy")})).exitCode)return;let s=r.stderr.trim()||r.stdout.trim()||`devicectl exited with code ${r.exitCode}`;throw new n("COMMAND_FAILED",`Failed to capture iOS screenshot: ${s}`)}async function eM(e,i,r){let o=G.fromTimeoutMs(2e4),s="Unable to locate runner container for simulator screenshot";for(let n of l){var d;let l=await (d=["get_app_container",e.id,n,"data"],p(e,d,{allowFailure:!0,timeoutMs:eO(o,2e4,"runner screenshot container lookup")}));if(0!==l.exitCode){let e=l.stderr.trim();e&&(s=e);continue}let u=l.stdout.trim();if(!u){s="simctl get_app_container returned empty output";continue}for(let e of function(e,t){let i=a.resolve(e),r=t.trim();if(!r)return[];let n=[],o=new Set,l=e=>{let t=a.normalize(e);o.has(t)||(o.add(t),n.push(t))},s=r.replace(/^\/+/,""),d=s.replace(/\\/g,"/");if(s&&l(a.join(i,s)),a.isAbsolute(r)&&l(a.normalize(r)),d.startsWith("tmp/"))l(a.join(i,d));else{let e=d.lastIndexOf("/tmp/");if(e>=0){let t=d.slice(e+1);l(a.join(i,t))}}let u=a.basename(r);return u&&l(a.join(i,"tmp",u)),n}(u,i))try{await t.copyFile(e,r);return}catch(e){s=e instanceof Error?e.message:String(e)}}throw new n("COMMAND_FAILED",`Failed to capture iOS screenshot: ${s}`)}function eO(e,t,i){let a=e.remainingMs();if(a>0)return a;throw new n("COMMAND_FAILED",`iOS ${i} timed out after ${t}ms`,{timeoutMs:t,step:i})}function eP(e,t,i){let a=ep(i);V({level:"warn",phase:"ios_screenshot_fallback",data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:t,to:"runner",...a}})}function ex(e,t,i){V({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...ep(i)}})}function eF(e){if(!(e instanceof n)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},i="string"==typeof t.stdout?t.stdout:"",a="string"==typeof t.stderr?t.stderr:"",r=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):"",o=`${e.message}
4
+ ${i}
5
+ ${a}
6
+ ${r}`.toLowerCase();return o.includes("timeout waiting for screen surfaces")||o.includes("nsposixerrordomain")&&o.includes("code=60")&&o.includes("screenshot")||o.includes("timed out")&&o.includes("screenshot")}let eR={settings:"com.apple.Preferences"},e$=E(),eE=null;function ek(e){return{platform:"ios",deviceId:e.id,variant:e.kind}}function eT(e,t,i){return o(m(e,t),i)}function eU(e){return e.includes("not installed")||e.includes("not found")||e.includes("no such file")}async function eB(e,t){if("macos"===e.platform)return await ea(t);let i=t.trim();if(i.includes("."))return i;let a=eR[i.toLowerCase()];if(a)return a;let r=ek(e),o=e$.get(r,i);if(o)return o;let l=("simulator"===e.kind?await e2(e):await v(e,"all")).filter(e=>e.name.toLowerCase()===i.toLowerCase()),s=l[0];if(void 0!==s&&1===l.length)return e$.set(r,i,s.bundleId);if(l.length>1)throw new n("INVALID_ARGS",`Multiple apps matched "${t}"`,{matches:l});throw new n("APP_NOT_INSTALLED",`No app found matching "${t}"`)}async function eG(e,t){var i;let r;if("ios"!==e.platform||"simulator"!==e.kind)return;let n=(i=t,r=/^([A-Za-z][A-Za-z0-9+.-]*):/.exec(i.trim()),r?.[1]?.toLowerCase());if(!n)return;let o=await e3(e),l=[];for(let e of o)!e.bundleId.startsWith("com.callstack.agentdevice.runner")&&e.path&&(await e4(a.join(e.path,"Info.plist"))).has(n)&&l.push(e);let s=l.filter(e=>"User"===e.applicationType);return 1===s.length?s[0]?.bundleId:s.length>1?void 0:1===l.length?l[0]?.bundleId:void 0}async function eV(e,t,i){let a=i?.launchConsole?.trim(),r=i?.launchArgs;if(a&&("ios"!==e.platform||"simulator"!==e.kind))throw new n("UNSUPPORTED_OPERATION",S);if("macos"===e.platform){if(r&&r.length>0)throw new n("UNSUPPORTED_OPERATION","--launch-args is not supported on macOS; launch arguments are currently iOS-only.");await er(e,t,i);return}let o=i?.url?.trim();if(o){if(a)throw new n("INVALID_ARGS",d);if(!k(o))throw new n("INVALID_ARGS","open <app> <url> requires a valid URL target");if("simulator"===e.kind)return void await ej(e,o,r);let l=U(i?.appBundleId??await eB(e,t),o);if(!l)throw new n("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");return void await tr(e,l,{payloadUrl:o,launchArgs:r})}let l=t.trim();if(k(l)){if(a)throw new n("INVALID_ARGS",d);if("simulator"===e.kind)return void await ej(e,l,r);let t=U(i?.appBundleId,l);if(!t)throw new n("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");return void await tr(e,t,{payloadUrl:l,launchArgs:r})}let s=i?.appBundleId??await eB(e,t);"simulator"===e.kind?await tt(e,s,{...a?{launchConsole:a}:{},...r?{launchArgs:r}:{}}):await tr(e,s,{launchArgs:r})}async function ej(e,t,i){if(i&&i.length>0)throw new n("INVALID_ARGS","--launch-args is not supported with iOS simulator URL opens (simctl openurl ignores launch args). Launch the app first with --launch-args, then issue the URL open in a separate call.");await b(e),await eT(e,["openurl",e.id,t])}async function eW(e){"macos"===e.platform||"simulator"!==e.kind||"Booted"!==await L(e)&&await b(e)}async function eK(e,t){if("macos"===e.platform)return void await en(e,t);let i=await eB(e,t);if("simulator"===e.kind){await b(e);let t=m(e,["terminate",e.id,i]),a=await o(t,{allowFailure:!0});if(0!==a.exitCode){if(a.stderr.toLowerCase().includes("found nothing to terminate"))return;throw new n("COMMAND_FAILED",`xcrun exited with code ${a.exitCode}`,{cmd:"xcrun",args:t,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode})}return}await A(["device","process","terminate","--device",e.id,i],{action:"terminate iOS app",deviceId:e.id})}async function eH(e,i){if("ios"!==e.platform||"simulator"!==e.kind)throw new n("UNSUPPORTED_OPERATION","Clearing app state is currently supported only on iOS simulators.");let r=await eB(e,i);await b(e),await eK(e,r);let o=await eT(e,["get_app_container",e.id,r,"data"],{allowFailure:!0});if(0!==o.exitCode)throw new n("COMMAND_FAILED",`simctl get_app_container failed for ${r}`,{stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode});let l=o.stdout.trim();if(!l)throw new n("COMMAND_FAILED",`simctl get_app_container returned an empty data container path for ${r}`);let s=await t.readdir(l);return await Promise.all(s.map(e=>t.rm(a.join(l,e),{recursive:!0,force:!0}))),{bundleId:r,containerPath:l}}async function ez(e,t){return await e$.invalidateWhile(ek(e),async()=>{let i=await eB(e,t);if("simulator"!==e.kind){let t=["devicectl","device","uninstall","app","--device",e.id,i],a=await o(t,{allowFailure:!0,timeoutMs:2e4});if(0!==a.exitCode){let r=String(a.stdout??""),o=String(a.stderr??"");if(!eU(`${r}
7
+ ${o}`.toLowerCase()))throw new n("COMMAND_FAILED",`Failed to uninstall iOS app ${i}`,{cmd:"xcrun",args:t,exitCode:a.exitCode,stdout:r,stderr:o,deviceId:e.id,hint:s(r,o)??f})}return{bundleId:i}}await b(e);let a=await eT(e,["uninstall",e.id,i],{allowFailure:!0});if(0!==a.exitCode&&!eU(`${a.stdout}
8
+ ${a.stderr}`.toLowerCase()))throw new n("COMMAND_FAILED",`simctl uninstall failed for ${i}`,{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return{bundleId:i}})}async function eq(e,t,i){let a=await q({kind:"path",path:t},i);try{return await eZ(e,a.installablePath),{archivePath:a.archivePath,installablePath:a.installablePath,bundleId:a.bundleId,appName:a.appName,launchTarget:a.bundleId}}finally{await a.cleanup()}}async function eJ(e,t,i){return await e$.invalidateWhile(ek(e),async()=>{let{bundleId:a}=await ez(e,t);return await eq(e,i,{appIdentifierHint:t}),{bundleId:a}})}async function eZ(e,t){await e$.invalidateWhile(ek(e),async()=>{"simulator"!==e.kind?await A(["device","install","app","--device",e.id,t],{action:"install iOS app",deviceId:e.id}):(await b(e),await eT(e,["install",e.id,t]))})}async function eQ(e){if("macos"===e.platform)return await eo();w(e,"clipboard"),await b(e);let t=await eT(e,["pbpaste",e.id],{allowFailure:!0});if(0!==t.exitCode)throw new n("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 eX(e,t){if("macos"===e.platform)return void await el(t);w(e,"clipboard"),await b(e);let i=await eT(e,["pbcopy",e.id],{allowFailure:!0,stdin:t});if(0!==i.exitCode)throw new n("COMMAND_FAILED","Failed to write iOS simulator clipboard",{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode})}async function eY(e,r,n){w(e,"push"),await b(e);let o=await t.mkdtemp(a.join(i.tmpdir(),"agent-device-ios-push-")),l=a.join(o,"payload.apns");try{await t.writeFile(l,`${JSON.stringify(n)}
9
+ `,"utf8"),await eT(e,["push",e.id,r,l])}finally{await t.rm(o,{recursive:!0,force:!0})}}async function e0(e,t,i,a,r){if("macos"===e.platform){let e=t.toLowerCase();if("appearance"===e)return void await ed(i);if("permission"===e){let e=$(i);if("deny"===e)throw new n("INVALID_ARGS",W("permission"));let t=function(e){let t=e?.trim().toLowerCase();if("accessibility"===t||"screen-recording"===t||"input-monitoring"===t)return t;throw new n("INVALID_ARGS","Unsupported macOS permission target. Use accessibility|screen-recording|input-monitoring.")}(r?.permissionTarget);return await h(e,t)}throw new n("INVALID_ARGS",W(t))}w(e,"settings"),await b(e);let o=t.toLowerCase();switch(o){case"clear-app-state":{if("clear"!==i.toLowerCase())throw new n("INVALID_ARGS","settings clear-app-state only supports clear.");if(!a)throw new n("INVALID_ARGS","settings clear-app-state requires an app id or an active app session.");let t=await eH(e,a);return{bundleId:t.bundleId,containerPath:t.containerPath,cleared:!0}}case"wifi":{let t=F(i);await eT(e,["status_bar",e.id,"override","--wifiMode",t?"active":"failed"]);return}case"airplane":return void(F(i)?await eT(e,["status_bar",e.id,"override","--dataNetwork","hide","--wifiMode","failed","--wifiBars","0","--cellularMode","failed","--cellularBars","0","--operatorName",""]):await eT(e,["status_bar",e.id,"clear"]));case"location":{if("set"===i.toLowerCase()){let{latitude:t,longitude:i}=j(r);return await eT(e,["location",e.id,"set",`${t},${i}`]),{latitude:t,longitude:i}}let t=F(i);if(!a)throw new n("INVALID_ARGS","location setting requires an active app in session");await eT(e,["privacy",e.id,t?"grant":"revoke","location",a]);return}case"faceid":case"touchid":{let t=e9[o],a=function(e,t){let i=e.trim().toLowerCase();if("match"===i)return"match";if("nonmatch"===i)return"nonmatch";if("enroll"===i)return"enroll";if("unenroll"===i)return"unenroll";throw new n("INVALID_ARGS",`Invalid ${t} state: ${e}. Use match|nonmatch|enroll|unenroll.`)}(i,o);await te(e,a,{settingName:o,label:t.label,modalityAliases:t.modalityAliases});return}case"appearance":{let t=await e5(e,i);await eT(e,["ui",e.id,"appearance",t]);return}case"permission":{var l;if(!a)throw new n("INVALID_ARGS","permission setting requires an active app in session");let t="deny"===(l=$(i))?"revoke":l,o=function(e,t){let i=R(e);if("photos"!==i&&t?.trim())throw new n("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===i)return"camera";if("microphone"===i)return"microphone";if("contacts"===i)return"contacts";if("contacts-limited"===i)return"contacts-limited";if("notifications"===i)return"notifications";if("calendar"===i)return"calendar";if("location"===i)return"location";if("location-always"===i)return"location-always";if("media-library"===i)return"media-library";if("motion"===i)return"motion";if("reminders"===i)return"reminders";if("siri"===i)return"siri";if("photos"===i){let e=t?.trim().toLowerCase();if(!e||"full"===e)return"photos";if("limited"===e)return"photos-add";throw new n("INVALID_ARGS",`Invalid photos mode: ${t}. Use full|limited.`)}throw new n("INVALID_ARGS",`Unsupported permission target: ${e}. Use camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri.`)}(r?.permissionTarget,r?.permissionMode);await e8(e,t,o,a);return}default:throw new n("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function e1(e,t){return"macos"===e.platform?await eu(t):"simulator"===e.kind?I(await e2(e),t):await v(e,t)}async function e2(e){return(await e3(e)).map(e=>({bundleId:e.bundleId,name:e.name}))}async function e3(e){let t=(await eT(e,["listapps",e.id],{allowFailure:!0})).stdout.trim();if(!t)return[];let i=null;if(t.startsWith("{"))try{i=JSON.parse(t)}catch{i=null}if(!i&&t.startsWith("{"))try{let e=await g("plutil",["-convert","json","-o","-","-"],{allowFailure:!0,stdin:t});0===e.exitCode&&e.stdout.trim().startsWith("{")&&(i=JSON.parse(e.stdout))}catch{i=null}return i?Object.entries(i).map(([e,t])=>{let i=function(e){if(e.Path)return e.Path;if(e.Bundle)try{return r(e.Bundle)}catch{return}}(t);return{bundleId:e,name:t.CFBundleDisplayName??t.CFBundleName??e,...i?{path:i}:{},...t.ApplicationType?{applicationType:t.ApplicationType}:{}}}):[]}async function e4(e){let t=await g("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==t.exitCode)return new Set;try{let e=JSON.parse(t.stdout),i=new Set;for(let t of e.CFBundleURLTypes??[])if(Array.isArray(t.CFBundleURLSchemes))for(let e of t.CFBundleURLSchemes)"string"==typeof e&&e.trim()&&i.add(e.trim().toLowerCase());return i}catch{return new Set}}async function e5(e,t){let i=P(t);if("toggle"!==i)return i;let a=await eT(e,["ui",e.id,"appearance"],{allowFailure:!0});if(0!==a.exitCode)throw new n("COMMAND_FAILED","Failed to read current iOS appearance",{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});let r=function(e,t){let i=/\b(light|dark|unsupported|unknown)\b/i.exec(`${e}
10
+ ${t}`);if(!i)return null;let a=i[1]?.toLowerCase();return"dark"===a?"dark":"light"===a?"light":null}(a.stdout,a.stderr);if(!r)throw new n("COMMAND_FAILED","Unable to determine current iOS appearance for toggle",{stdout:a.stdout,stderr:a.stderr});return"dark"===r?"light":"dark"}let e9={faceid:{label:"Face ID",modalityAliases:["face"]},touchid:{label:"Touch ID",modalityAliases:["finger","touch"]}};async function e8(e,t,i,a){let r=await e7(e);if(!r.has(i))throw new n("UNSUPPORTED_OPERATION",`iOS simctl privacy does not support service "${i}" on this runtime.`,{deviceId:e.id,appBundleId:a,hint:`Supported services: ${Array.from(r).sort().join(", ")}`});let o=["privacy",e.id,t,i,a],l="notifications"===i;if(!("reset"===t&&l))try{await eT(e,o);return}catch(t){if(!(l&&e6(t)))throw t;throw new n("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 eT(e,o);return}catch(e){if(!e6(e))throw e}try{await eT(e,["privacy",e.id,"reset","all",a])}catch(t){throw new n("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 e6(e){if(!(e instanceof n)||"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 e7(t){let i=T(t.simulatorSetPath),a=`${process.env.PATH??""}::${i??""}`;if(eE&&e===a)return eE;let r=await eT(t,["privacy","help"],{allowFailure:!0}),o=function(e){let t=new Set,i=!1;for(let a of e.split("\n")){let e=a.trim();if(!e)continue;if("service"===e){i=!0;continue}if(!i)continue;if(e.startsWith("bundle identifier"))break;let r=/^([a-z-]+)\s+-\s+/.exec(e),n=r?.[1];void 0!==n&&t.add(n)}return t}(`${r.stdout}
11
+ ${r.stderr}`);if(0===o.size)throw new n("COMMAND_FAILED","Unable to determine supported simctl privacy services",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode,hint:"Run `xcrun simctl privacy help` manually to verify available services for this runtime."});return eE=o,e=a,o}async function te(e,t,i){let a=function(e,t,i){let a=i.length>0?i:["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,i.modalityAliases),r=[];for(let t of a){let i=m(e,t),a=await o(i,{allowFailure:!0});if(0===a.exitCode)return;r.push({args:i,stderr:a.stderr,stdout:a.stdout,exitCode:a.exitCode})}let l=x(r);if(r.length>0&&r.every(e=>{var t,i;let a;return t=e.stdout,i=e.stderr,(a=`${t}
12
+ ${i}`.toLowerCase()).includes("unrecognized subcommand")||a.includes("unknown subcommand")||a.includes("not supported")||a.includes("unavailable")||a.includes("biometric")&&a.includes("invalid")}))throw new n("UNSUPPORTED_OPERATION",`${i.label} simulation is not supported on this simulator runtime.`,{deviceId:e.id,action:t,setting:i.settingName,attempts:l});throw new n("COMMAND_FAILED",`Failed to simulate ${i.settingName}.`,{deviceId:e.id,action:t,setting:i.settingName,attempts:l})}async function tt(e,t,i){await b(e);let a=0,r=G.fromTimeoutMs(6e4);try{await B(async({deadline:a})=>{var r,l,s,d;let u;if(a?.isExpired())throw new n("COMMAND_FAILED","App launch deadline exceeded",{timeoutMs:6e4});let c=(l=e.id,s=t,d=i,u=["launch"],d?.launchConsole&&u.push("--console-pty"),u.push(l,s),d?.launchArgs&&d.launchArgs.length>0&&u.push(...d.launchArgs),r=u,m(e,r)),p=i?.launchConsole?await ti(c,i.launchConsole):await o(c,{allowFailure:!0});if(0!==p.exitCode)throw new n("COMMAND_FAILED",`xcrun exited with code ${p.exitCode}`,{cmd:"xcrun",args:c,stdout:p.stdout,stderr:p.stderr,exitCode:p.exitCode})},{maxAttempts:10,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>!!K(e)&&(a+=1)<3},{deadline:r})}catch(i){if(K(i)){var l;let a=(l=await H(e,t)).installed?!1===l.simulatorCompatible?"ARCH_MISMATCH":"PERSISTENT_LAUNCH_FAIL":"APP_NOT_INSTALLED";i.details={...i.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 i}}async function ti(e,i){await t.mkdir(a.dirname(i),{recursive:!0});try{let t=await o(e,{allowFailure:!0,timeoutMs:25e3});return await ta(i,t.stdout,t.stderr),t}catch(t){let e=(t instanceof n?t:void 0)?.details;if(e?.timeoutMs===25e3){let t="string"==typeof e.stdout?e.stdout:"",a="string"==typeof e.stderr?e.stderr:"";return await ta(i,t,a),V({level:"warn",phase:"ios_simulator_launch_console_capture_timeout",data:{timeoutMs:25e3,logPath:i,stdoutBytes:Buffer.byteLength(t),stderrBytes:Buffer.byteLength(a)}}),{stdout:t,stderr:a,exitCode:0}}throw t}}async function ta(e,i,a){var r,n;await t.writeFile(e,(r=i,n=a,!r||!n||r.endsWith("\n")||r.endsWith("\r")?`${r}${n}`:`${r}
13
+ ${n}`),"utf8")}async function tr(e,t,i){let a=["device","process","launch","--device",e.id,t];i?.payloadUrl&&a.push("--payload-url",i.payloadUrl),i?.launchArgs&&i.launchArgs.length>0&&a.push("--",...i.launchArgs),await A(a,{action:"launch iOS app",deviceId:e.id})}export{eK as closeIosApp,eq as installIosApp,eZ as installIosInstallablePath,e1 as listIosApps,eV as openIosApp,eW as openIosDevice,q as prepareIosInstallArtifact,eY as pushIosNotification,z as readInfoPlistString,eQ as readIosClipboardText,eJ as reinstallIosApp,eB as resolveIosApp,eG as resolveIosSimulatorDeepLinkBundleId,eb as screenshotIos,e0 as setIosSetting,eX as writeIosClipboardText};
@@ -0,0 +1,449 @@
1
+ import{listCliCommandNames as e}from"./5792.js";import{getCliCommandSchema as t,getCommandSchema as o,applyCommandDefaults as a,GLOBAL_FLAG_KEYS as s,getFlagDefinition as n,getFlagDefinitions as r}from"./1352.js";import{parseSourceValue as i,buildPrimaryEnvVarName as l}from"./1010.js";import{AppError as c}from"./9152.js";function d(e,t){for(let[o,a]of Object.entries(t))void 0!==a&&(e[o]=a);return e}let p=[{label:"help workflow",description:"Normal bootstrap, exploration, and validation loop"},{label:"help debugging",description:"Logs, network, alerts, diagnostics, and traces"},{label:"help react-native",description:"React Native app automation hazards, overlays, Metro, and routing"},{label:"help react-devtools",description:"React Native performance, profiling, component tree, and renders"},{label:"help remote",description:"Remote/cloud config, tenants, leases, and local service tunnels"},{label:"help macos",description:"Desktop, frontmost-app, and menu bar surfaces"},{label:"help dogfood",description:"Exploratory QA report workflow"}],u=["Default loop: devices/apps -> open -> snapshot -i -> press/fill/get/is/wait/find -> verify -> close.",'Use selectors or refs as positional targets: id="submit", label="Allow", or @e12 from snapshot -i.',"Plain snapshot reads state; snapshot -i refreshes current interactive refs only.","Default snapshot text is an agent-facing, token-efficient view for planning and targeting actions.","Read-only visible/state question: use snapshot/get/is/find; use snapshot -i only when refs are needed.","Anti-pattern: snapshot -i followed by snapshot -i | grep ...; prior refs stay valid until app state changes, and --force-full is the explicit full re-read.","Truncated text/input preview: expand first with snapshot -s @e12, not get text.","React Native apps: read help react-native for Metro, DevTools routing, and RN-specific blockers; use react-native dismiss-overlay for LogBox/RedBox overlays.","Android RN/Expo Metro: direct Android localhost URL opens with a port auto-configure host reachability.",'Expo Go/dev clients: use the provided URL when given; on iOS prefer open "Expo Go" <url>; Android URL opens infer the foreground package for logs/perf when possible.',"Install flows: install/install-from-source first, then open the installed id with --relaunch.",'Text: fill \'id="field-email"\' "qa@example.com" replaces; type appends after press.','Clearing text: do not use fill <target> ""; use a visible clear/reset control or report that clearing is unsupported.',"Android IME capture: if fill says input was captured by the keyboard/IME, inspect keyboard state and switch/disable handwriting before retrying; do not loop fill/type.","Run mutating commands serially against one session; parallelize only read-only commands or separate sessions.","Before taking over a shared device, run session list and reuse the active session name when one already owns the device.","Clipboard limits: iOS Allow Paste cannot be automated through XCUITest; prefill with clipboard write. Android non-ASCII should use fill/type, not raw adb input.","After mutation: refs are stale. If the next target is known, use its selector directly; otherwise refresh with snapshot -i, scoped with -s when a stable container is known.","Raw coordinates are fallback-only: use snapshot -i -c --json rects when iOS refs no-op or child refs are missing.",'Batch JSON steps use "command" and structured "input"; legacy "positionals"/"flags" steps still run in CLI but are deprecated until the next major version.',"Navigation: app-owned back uses back; system back uses back --system.","Verification commands must name the expected text/selector; bare screenshots/snapshots are not enough.","Debug evidence: logs clear --restart/mark/path; trace start ./path; trace stop ./path; network dump --include headers.","Use agent-device commands in final plans; raw platform tools, pseudo commands, and helper prose are wrong.","Full operating guide: agent-device help workflow. Exploratory QA: agent-device help dogfood."],f=["Default config files: ~/.agent-device/config.json, ./agent-device.json","Use --config <path> or AGENT_DEVICE_CONFIG to load one explicit config file."],h=[{label:"AGENT_DEVICE_SESSION",description:"Default session name"},{label:"AGENT_DEVICE_PLATFORM",description:"Default platform binding"},{label:"AGENT_DEVICE_SESSION_LOCK",description:"Bound-session conflict mode"},{label:"AGENT_DEVICE_DAEMON_BASE_URL",description:"Connect to remote daemon"},{label:"AGENT_DEVICE_DAEMON_AUTH_TOKEN",description:"Remote daemon service/API token"},{label:"AGENT_DEVICE_CLOUD_BASE_URL",description:"Bridge/control-plane API origin for cloud auth and /api-keys"}],g=["agent-device open Settings --platform ios","agent-device open TextEdit --platform macos","agent-device snapshot -i","agent-device react-devtools get tree --depth 3",'agent-device fill @e3 "test@example.com"',"agent-device replay ./session.ad","agent-device test ./suite --platform android"],m={workflow:{summary:"Normal agent-device bootstrap, exploration, and validation loop",body:`agent-device help workflow
2
+
3
+ Version-matched operating guide for normal agent-device work.
4
+
5
+ Core loop:
6
+ devices/apps -> open -> snapshot or snapshot -i -> get/is/find/wait or press/fill/scroll/back -> verify -> close
7
+
8
+ Command shape:
9
+ Plans should use agent-device commands, not raw platform tools, pseudo commands, package-manager aliases, or helper prose.
10
+ Put subcommand first, then positionals, then flags:
11
+ agent-device open com.example.app --session checkout --platform android --relaunch
12
+ agent-device record start ./checkout.mp4 --session checkout
13
+ Snapshot refs look like @e12. After snapshot -i, use the exact @eN ref from that output.
14
+ If the exact ref is not known yet, first output snapshot -i, then use a concrete example shape like press @e12 in the next command; do not write @<ref>, @ref, @Label_Name, or @eN placeholders.
15
+ Close means agent-device close. App-owned back means back; system back means back --system.
16
+ Taps are press or click. Gestures use swipe, longpress, or gesture <pan|fling|swipe|pinch|rotate|transform>. Use gesture swipe left|right for reliable in-page horizontal swipes, and gesture swipe right-edge for left-edge navigation/back gestures. Android pinch, rotate, and transform use provider-native touch injection when available, then the bundled multi-touch helper. iOS simulator transform uses private XCTest synthesis for a continuous two-finger pan/scale/rotation path; otherwise it reports UNSUPPORTED_OPERATION.
17
+
18
+ Bootstrap:
19
+ agent-device devices --platform ios
20
+ agent-device apps --platform android
21
+ agent-device open MyApp --platform ios --device "iPhone 17 Pro"
22
+ agent-device open <discovered-app-id> --session checkout --platform android
23
+ agent-device install com.example.app ./dist/app.apk --platform android
24
+ agent-device reinstall com.example.app ./build/MyApp.app --platform ios
25
+ agent-device install-from-source --github-actions-artifact org/repo:app-debug --platform android
26
+ agent-device open com.example.app --platform android --relaunch
27
+ If app id is unknown, plan devices, apps, then open <discovered-app-id>. Discovery is not enough when the task asks to open/start the app.
28
+ Install arguments are app/package id then artifact path. If the task says install, use install; use reinstall only when explicitly requested. Fresh runtime state is open --relaunch after install.
29
+ Do not open artifact paths or invent package ids. If apps lookup misses the target and no URL/artifact is provided, ask or stop.
30
+
31
+ Snapshots and refs:
32
+ snapshot reads visible state. snapshot -i gets current interactive refs only; it is the fast path when the next step is an interaction.
33
+ Default snapshot text is an agent-facing, token-efficient view for planning and targeting actions; use --raw or --json only when you need the full provider tree.
34
+ Snapshot legend:
35
+ @e12 [button] label="Add to cart" id="add-cart" enabled hittable -> press @e12 or press 'id="add-cart"'.
36
+ @e13 [textinput] label="Notes" preview="Leave at side..." truncated -> snapshot -s @e13 before reading.
37
+ @e14 [cell] label="Profiles" focused -> tvOS focus is currently on this row.
38
+ [off-screen below] 4 items: "Privacy", "About" -> scroll down, then snapshot -i; those are hints, not refs.
39
+ Re-snapshot after navigation, submit, typing/fill, modal/list/reload/dynamic changes when you need new refs.
40
+ Anti-pattern: snapshot -i followed by snapshot -i | grep ...
41
+ Refs from the first snapshot remain valid until you press, fill, type, scroll, go back, wait for async UI, or otherwise change app state.
42
+ After a mutation, prefer a known selector/label directly (for example press 'label="Send"') because interaction commands refresh interactive state internally. If you need to discover the new control, use snapshot -i, or snapshot -i -s "Composer" when a stable container label/id can scope the refresh.
43
+ For a targeted query, use find/get/is. If you truly need the full tree again, pass --force-full.
44
+ Off-screen summaries are scroll hints; use scroll, not swipe, then snapshot -i.
45
+ Missing target in a long list: use a short manual scroll + snapshot loop with a max attempt count. If a named target is summarized as off-screen below/above, use scroll down/up, then snapshot -i; do not use scroll bottom/top because the target may appear before the absolute list edge. Use scroll bottom/top only when the task explicitly asks for the list edge. Edge scrolls verify hidden content with snapshots and stop when no matching hidden content remains.
46
+ Truncated text/input previews: do not use get text first; expand with snapshot -s @ref (for example snapshot -s @e7), then read the scoped output.
47
+ Rare iOS accessibility gaps: if a row ref is shown disabled/hittable:false and press @ref reports success but no UI change, or a horizontal tab/filter bar is collapsed into one composite/seekbar with no child refs, run agent-device snapshot -i -c --json to read rects, compute the target center, press x y, then diff snapshot -i. Coordinates are fallback-only; document why you used them.
48
+
49
+ Selectors:
50
+ Use selectors as positional targets: id="field-email" or label="Allow".
51
+ Do not use CSS selectors, pseudo refs, --selector, --text, or raw x/y when refs/selectors exist.
52
+ agent-device fill 'id="catalog-search"' "tart" --delay-ms 80
53
+ agent-device press 'id="submit-order"'
54
+ agent-device is visible 'label="Online"'
55
+ agent-device get text 'id="quantity-value"'
56
+
57
+ Text entry:
58
+ fill replaces; type appends to focused field.
59
+ agent-device fill @e5 "qa@example.com"
60
+ agent-device fill 'id="field-email"' "qa@example.com"
61
+ agent-device press 'id="product-note"'
62
+ agent-device type "Handle with care" --delay-ms 80
63
+ Empty replacement is not a supported clear-field command: do not plan fill <target> "" or fill <target> ''. Prefer a visible clear/reset control; if the app exposes none, report the tool gap instead of inventing a clear command.
64
+ Debounced field with no result selector: agent-device wait 1000. Keyboard read-only: keyboard status/get. Blocked control: try keyboard dismiss when supported.
65
+ On iOS, prefer keyboard dismiss before manually pressing visible Done; the runner can use safe native keyboard controls and still reports unsupported layouts explicitly. If it returns UNSUPPORTED_OPERATION, prefer a visible app dismiss control, or use back --system only when system navigation is an acceptable side effect.
66
+ Search-as-you-type fields on iOS can drop characters when driven too fast; use --delay-ms on fill/type before trying clipboard paste.
67
+ iOS Allow Paste prompt cannot be exercised under XCUITest. To test paste-driven app behavior, prefill first with agent-device clipboard write "some text"; test the system prompt manually.
68
+ Android Gboard handwriting/stylus UI can capture text in an IME-owned input instead of the app field. If fill reports that input was captured by the keyboard/IME, use the diagnostic targetInput/actualInput details, inspect keyboard status/get if needed, and switch or disable handwriting outside the command plan before retrying. Do not keep retrying fill/type against the same field while the IME owns focus.
69
+ Android text entry is owned by agent-device: provider-native text injection when available, then chunk-safe ASCII shell input. Do not switch to raw adb, clipboard, or paste as an agent fallback. If non-ASCII is unsupported in the current backend, report the tool/device gap.
70
+
71
+ Session ordering:
72
+ Stateful commands against one --session must run serially. Do not run open/press/fill/type/scroll/back/alert/replay/batch/close commands in parallel against the same session.
73
+ It is fine to parallelize independent read-only collection or commands that use different sessions/devices.
74
+
75
+ Read-only and waits:
76
+ Read-only visible/state question: use snapshot/get/is/find.
77
+ agent-device snapshot
78
+ agent-device get text 'id="product-title"'
79
+ agent-device get attrs @e4
80
+ agent-device is visible 'label="Online"'
81
+ agent-device wait text "Refreshing metrics..." 3000
82
+ agent-device wait 'label="Ready"' 3000
83
+ agent-device find "Increment" press --json
84
+ For async/list text presence, prefer wait text over is visible when no interaction is needed.
85
+ Use snapshot -i only when refs are needed for an action or targeted query.
86
+ Ambiguous find: add --first or --last. If info is not visible/exposed, report that gap instead of typing/searching/navigating to reveal it.
87
+
88
+ Navigation and gestures:
89
+ Use scroll for lists; swipe for coordinate gestures/carousels; gesture pan for deliberate drags; gesture fling for fast directional throws.
90
+ For raw coordinate gestures, run snapshot -i first and choose a point near the center of the intended app-owned target. Avoid screen edges, tab bars, navigation bars, and home indicators because those areas can trigger system or app navigation instead of the gesture under test.
91
+ If app-owned back is ambiguous or has just misrouted, prefer a visible nav/back button ref, tab-bar ref, or deep link over repeated back/system back.
92
+ App-owned action sheets, menus, and camera/scan screens are normal UI. After opening one, run snapshot -i or wait for the option, press by label/ref, handle visible permission sheets through UI or platform-supported native alerts, then wait for a concrete result before returning to chat/form state.
93
+ Keep count/pause/pattern on one swipe; flags are --count, --pause-ms, --pattern ping-pong.
94
+ longpress accepts coordinates, @refs, or selectors. Prefer @ref/selector from snapshot -i; use coordinates only as a fallback when accessibility refs miss the exact target. Duration and gesture scale/center are positional:
95
+ agent-device longpress 300 500 800
96
+ agent-device longpress @e12 800
97
+ agent-device swipe 320 500 40 500 --count 8 --pause-ms 30 --pattern ping-pong
98
+ agent-device gesture pan 200 420 0 -80 500
99
+ agent-device gesture fling right 200 420 180
100
+ agent-device gesture pinch 0.5 200 400
101
+ agent-device gesture rotate 35 200 420
102
+ agent-device gesture transform 200 420 80 -40 2 35 700
103
+ iOS simulator transform uses private XCTest synthesis for a continuous two-finger pan/scale/rotation path; verify app metrics instead of assuming requested values map exactly to recognizer output.
104
+ Android transform injects a geometric two-finger path; app recognizers may report non-exact pan/scale/rotation. For Android combined transforms, verify qualitative state such as "pan changed yes" / "pinch changed yes" / "rotate changed yes" unless the app explicitly promises exact centroid metrics.
105
+ If Android needs exact app-state values, prefer isolated gesture pan, gesture pinch, or gesture rotate commands over one combined transform.
106
+
107
+ Validation and evidence:
108
+ Nearby mutation diff: agent-device diff snapshot -i.
109
+ Expected text/selector verification must include the exact text or selector via wait, is, get, or find; bare screenshots/snapshots are insufficient for named expectations.
110
+ Prefer provided testIDs/ids/selectors for verification; use visible text when no durable selector is provided.
111
+ If task says snapshot, use snapshot. If it asks visual evidence, use screenshot.
112
+ Icon/tappable visual proof: screenshot --overlay-refs. Flag is --overlay-refs.
113
+ Startup/frame health/CPU/memory: perf --json or metrics. Replay maintenance: replay -u ./flow.ad.
114
+ Recording: record start/stop. By default, stop burns touch overlays into the video; use record start --hide-touches for the fastest raw recording. Android adb screenrecord has a 180s platform limit, so longer Android recordings are returned as multiple MP4 chunks. For gesture-heavy iOS simulator proof videos, prefer --hide-touches because overlay timing depends on a stable runner session while gestures are executing. Tracing: trace start ./trace.log, trace stop ./trace.log. Paths are positional.
115
+ Stable known flow: batch ./steps.json, not workflow batch.
116
+ Inline batch JSON example:
117
+ agent-device batch --steps '[{"command":"open","input":{"app":"settings"}},{"command":"wait","input":{"kind":"duration","durationMs":100}}]'
118
+ Batch step keys are command, input, and optional runtime. Put command arguments inside input using the same fields as the MCP/Node command. CLI still accepts legacy positionals/flags steps with a deprecation warning until the next major version.
119
+ Never use args, step positionals, or flags for new batch JSON; put command inputs under input.
120
+ Android animations: settings animations off/on, not animations disable/restore.
121
+ Debug logs: logs clear --restart, logs mark, reproduce, then logs path; do not split clear/restart into separate stop/start commands.
122
+ Network headers: network dump --include headers; do not write network log headers.
123
+ Remote/cloud: connect to discover a cloud profile, or connect --remote-config ./remote-config.json for a local profile; then open, snapshot, disconnect.
124
+ macOS menu bar: open ... --platform macos --surface menubar; snapshot -i --platform macos --surface menubar.
125
+
126
+ React Native dev loop:
127
+ JS-only change with Metro connected:
128
+ agent-device metro reload
129
+ agent-device find "Home"
130
+ Do not use agent-device reload. Use open --relaunch for native startup reset.
131
+ React Native apps: use help react-native for Metro/Fast Refresh, DevTools routing, and RN-specific blockers; use react-native dismiss-overlay for LogBox/RedBox overlays.
132
+ Android RN/Expo Metro: direct Android URL opens to localhost/127.0.0.1/[::1] with a port auto-configure host reachability. Manual adb reverse tcp:<port> tcp:<port> is only needed for app/package launches or unsupported flows where the app cannot reach local Metro.
133
+ Expo Go is a host shell. Use a provided project URL instead of inventing a bundle id; if no URL is provided but a target/app name is provided, open that target and do not inspect project files to find one. On iOS, prefer host + URL when the host shell is known because direct URL open can report success while leaving the runner/shell focused; verify with snapshot -i after opening:
134
+ agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios
135
+ agent-device snapshot -i --platform ios
136
+ There is no open-url command; use open with the URL target or host + URL form.
137
+ Direct iOS URL open remains valid when no host shell is known, but verify that the app UI loaded:
138
+ agent-device open exp://127.0.0.1:8081 --platform ios
139
+ Android uses the URL target directly; do not write open <app> <url> there:
140
+ agent-device open exp://127.0.0.1:8081 --platform android
141
+ Android URL/deep-link opens infer the foreground package after launch when possible, so logs/perf can remain package-bound. If perf still says no package is associated, open the host package/app id first, then open the URL in the same session.
142
+ If apps lookup misses the project but shows Expo Go/dev-client and a project URL is available, open the URL/host shell; if no URL is available, ask instead of inventing an app id.
143
+ Expo Dev Client/development builds: open the installed dev-client app id/name; if a dev-client URL is provided, open that URL next. For Metro setup use metro prepare --kind expo.
144
+
145
+ Escalate:
146
+ help debugging logs, network, alerts, traces, flaky runtime failures
147
+ help react-devtools React Native performance, profiling, props/state/hooks, slow renders, rerenders
148
+ help react-native React Native app automation hazards, overlays, Metro, and routing
149
+ help remote remote/cloud config, tenant, lease, local service tunnels
150
+ help macos desktop, frontmost-app, menu bar surfaces
151
+ help dogfood exploratory QA report workflow`},debugging:{summary:"Targeted failure evidence without dumping stale context",body:`agent-device help debugging
152
+
153
+ Use this when behavior fails, hangs, times out, throws alerts, or needs runtime evidence.
154
+
155
+ Logs:
156
+ Keep log windows small. Prefer clear, mark, reproduce, then path.
157
+ agent-device logs clear --restart
158
+ agent-device logs mark "before diagnostics retry"
159
+ agent-device press 'id="load-diagnostics"'
160
+ agent-device logs path
161
+ Do not cat a full stale log into agent context. Open or grep only the relevant window when needed.
162
+ logs clear --restart is the compact command to clear old logs and start a fresh capture; do not split it into logs stop, logs clear, logs start.
163
+ On iOS simulators, logs scope by bundle id and resolved app executable, so use this instead of raw simctl log stream predicates.
164
+ For iOS simulator launch-time stdout/stderr, use --launch-console on the direct app launch:
165
+ agent-device open MyApp --platform ios --relaunch --launch-console ./artifacts/app.console.log
166
+ --launch-console is only for direct iOS simulator app launches, not URL opens.
167
+
168
+ Network:
169
+ Use network dump for recent session HTTP traffic parsed from app logs.
170
+ agent-device network dump --include headers
171
+ agent-device network dump 20 --include all
172
+ Use this instead of logs path when the question is request/response metadata.
173
+ network log is a supported alias, but network dump --include headers is the clearest plan form. Do not write network log headers.
174
+
175
+ Alerts:
176
+ Native and platform dialogs:
177
+ agent-device alert wait 3000
178
+ agent-device alert accept
179
+ agent-device alert dismiss
180
+ Android support is snapshot-derived for runtime permission prompts and native app dialogs. iOS support is runner-derived for XCTest alerts, app-owned modal popups with native blocking markers, and blocking system dialogs. Use cheap alert get for an immediate check; use alert wait <short-ms> only when a prompt may appear after async work.
181
+ If alert says no alert but a sheet is visibly on screen, treat it as app-owned UI:
182
+ agent-device snapshot -i
183
+ agent-device press 'label="Allow"'
184
+ Do not use settings permission to answer a dialog already on screen. Reserve settings permission for setup/resetting permission state before a flow.
185
+
186
+ Diagnostics and traces:
187
+ Use --debug for CLI/daemon diagnostic ids and log paths.
188
+ Use trace for low-level session diagnostics around one repro:
189
+ agent-device trace start ./traces/diagnostics.trace
190
+ agent-device press 'id="load-diagnostics"'
191
+ agent-device trace stop ./traces/diagnostics.trace
192
+ The trace path is positional. Do not use --path for trace start or trace stop.
193
+
194
+ Stabilizers:
195
+ Android animation-sensitive flows:
196
+ agent-device settings animations off
197
+ agent-device snapshot
198
+ agent-device settings animations on
199
+ Re-enable settings you changed before finishing.
200
+
201
+ React Native internals:
202
+ If the question is about React Native performance, profiling, props, state, hooks, render causes, slow components, or rerenders, use help react-devtools instead of inferring from screenshots or logs.`},"react-devtools":{summary:"React Native performance, profiling, and component internals",body:`agent-device help react-devtools
203
+
204
+ Use this for React Native performance/profiling and internals that the accessibility tree cannot expose: components, props, state, hooks, ownership, slow renders, and rerenders.
205
+
206
+ Core commands:
207
+ agent-device react-devtools start
208
+ agent-device react-devtools stop
209
+ agent-device react-devtools status
210
+ agent-device react-devtools wait --connected
211
+ agent-device react-devtools wait --component <ComponentName>
212
+ agent-device react-devtools count
213
+ agent-device react-devtools get tree --depth 3
214
+ agent-device react-devtools find <ComponentName>
215
+ agent-device react-devtools find <ComponentName> --exact
216
+ agent-device react-devtools get component @c5
217
+ agent-device react-devtools errors
218
+ agent-device react-devtools profile start
219
+ agent-device react-devtools profile stop
220
+ agent-device react-devtools profile slow --limit 5
221
+ agent-device react-devtools profile rerenders --limit 5
222
+ agent-device react-devtools profile report @c5
223
+ agent-device react-devtools profile timeline --limit 20
224
+ agent-device react-devtools profile export profile.json
225
+ agent-device react-devtools profile diff before.json after.json --limit 10
226
+
227
+ Profiling loop:
228
+ 1. Verify the app is connected: react-devtools status, then wait --connected if needed.
229
+ 2. If correlating with logs or network, run logs clear --restart before the first logs mark.
230
+ 3. Start profiling immediately before the interaction.
231
+ 4. Drive the interaction with normal agent-device commands and mark before/after the repro when timing matters.
232
+ 5. Stop profiling.
233
+ 6. Make one bounded first-pass survey: profile stop for the summary, profile slow --limit 5 once, profile rerenders --limit 5 once, and profile timeline --limit 20 only when commit timing matters.
234
+ 7. Use profile report @cN for targeted render causes and changed props/state/hooks; use get component @cN for current props/state/hooks.
235
+
236
+ Rules:
237
+ Every React DevTools command is an agent-device subcommand: agent-device react-devtools ...
238
+ Do not write agent-devtools, agent-react-devtools, or bare react-devtools commands in final command plans.
239
+ Start with get tree --depth 3 or find <name>; use find --exact when fuzzy results are noisy.
240
+ @c refs reset after reload/remount. After reload, wait --connected and inspect again.
241
+ Keep the profile window narrow; unrelated navigation makes render data noisy.
242
+ Do not repeatedly raise broad profile slow limits such as --limit 50, --limit 200, or --limit 500. Drill into a specific @c ref with profile report unless you have a specific target that needs more rows.
243
+ For network evidence, use agent-device network dump --include headers; headers is not a positional argument.
244
+ For cross-platform validation with explicit device selectors, prefer isolated --state-dir and restart react-devtools between platforms.
245
+ Remote Android and iOS bridge runs normally through agent-device react-devtools; the CLI keeps the needed local service tunnel alive until agent-device react-devtools stop or disconnect. Expo support depends on the SDK's bundled React Native runtime.
246
+ Remote iOS apps attempt the legacy React DevTools websocket during JavaScript startup. If the app was already open before react-devtools start, run open <bundle-id> --platform ios --relaunch, then wait --connected.
247
+
248
+ Example:
249
+ agent-device react-devtools status
250
+ agent-device react-devtools wait --connected
251
+ agent-device logs clear --restart
252
+ agent-device logs mark "before catalog search"
253
+ agent-device react-devtools profile start
254
+ agent-device fill 'id="catalog-search"' "tart" --delay-ms 80
255
+ agent-device logs mark "after catalog search"
256
+ agent-device react-devtools profile stop
257
+ agent-device react-devtools profile slow --limit 5
258
+ agent-device react-devtools profile rerenders --limit 5
259
+ agent-device react-devtools profile timeline --limit 20
260
+ agent-device react-devtools profile report @c5
261
+ agent-device network dump --include headers
262
+
263
+ Use snapshot, screenshot, logs, network, and perf for device/app runtime evidence. Use react-devtools only when component internals or React rendering behavior matters.`},"react-native":{summary:"React Native app automation hazards and routing",body:`agent-device help react-native
264
+
265
+ Use this when the target app is React Native, Expo, or a React Native dev client.
266
+ This topic covers React Native-specific automation hazards and routes deeper
267
+ questions to the owning help topic.
268
+
269
+ Choose the next help topic:
270
+ Generic navigation, selectors, refs, verification, serial commands: help workflow.
271
+ Logs, network, diagnostics, traces, permission dialogs, or runtime failures: help debugging.
272
+ Component tree, props/state/hooks, slow renders, rerenders, or render causes: help react-devtools.
273
+ Remote/cloud config, leases, and local service tunnels: help remote.
274
+
275
+ React Native dev loop:
276
+ For "start from screen X" flows, prefer open --relaunch before the first snapshot so the app does not reuse a prior in-progress navigation state.
277
+ JS-only change with Metro connected:
278
+ agent-device metro reload
279
+ agent-device find "Home"
280
+ Do not use agent-device reload. Use open --relaunch for native startup reset.
281
+ Android RN/Expo Metro: direct Android localhost URL opens with a port auto-configure host reachability. For app/package launches, use help react-native if the app cannot reach local Metro.
282
+ Verify Metro from the same host context that owns Metro. If a sandboxed shell cannot curl localhost:8081/status but an unrestricted host shell can, Metro is running and the sandbox probe is not authoritative.
283
+ adb reverse only affects Android device-to-host traffic. It does not prove host-to-Metro reachability, and it does not fix a redbox caused by a stale or wrong Metro/app state.
284
+ Expo Go/dev clients are host shells. Use provided project URLs, verify with snapshot -i after opening, and ask instead of inventing app ids or URLs. Help workflow owns the full Expo URL command shapes.
285
+
286
+ Overlays and busy RN UIs:
287
+ If snapshot reports a React Native warning/error overlay, handle it before interacting with the app: run agent-device react-native dismiss-overlay, then agent-device snapshot -i -c. Use refs from the new snapshot.
288
+ Do not manually press warning/error text bodies, collapsed banner bodies, full-screen warning parents, or broad LogBox/RedBox refs. The dismiss-overlay command owns the narrow LogBox/RedBox targeting policy.
289
+ Report the overlay in the final summary. Use screenshot --overlay-refs before dismissing only if visual evidence is required.
290
+ If snapshot times out because the UI never becomes idle, Android accessibility may be blocked by busy or continuously changing app UI. After that timeout, use screenshot as visual truth instead of repeatedly retrying snapshots.
291
+ Android runtime permission dialogs and native alerts are handled by alert wait/accept/dismiss. If alert reports no alert, treat the visible surface as app-owned UI and use snapshot -i plus press by label/ref.
292
+
293
+ React DevTools routing:
294
+ Keep the agent-device react-devtools prefix on every React DevTools command.
295
+ Use help react-devtools for status/wait, component trees, props/state/hooks, profile windows, slow renders, rerenders, and remote bridge rules.
296
+ If React DevTools cannot connect, report status and continue with logs, network, perf, screenshot, and trace evidence instead of blocking the whole flow.
297
+
298
+ Slow-flow investigation:
299
+ Keep one named session, start with session list, open, and snapshot -i.
300
+ Use help react-devtools for the narrow React profile window.
301
+ Use help debugging for logs clear --restart, logs mark, network dump --include headers, perf --json, traces, and runtime failure evidence.
302
+ For 15-20s async work, use wait with the exact expected text or selector instead of repeated snapshots.
303
+ Report React render offenders separately from network/backend waits and device frame/CPU/memory findings.`},remote:{summary:"Remote config, tenant, lease, and remote host flow",body:`agent-device help remote
304
+
305
+ Use remote config or the cloud connection profile when a profile owns daemon URL, auth, tenant, run, lease, device scope, and Metro hints. Do not restate those as individual flags unless overriding intentionally.
306
+
307
+ Cloud profile flow:
308
+ agent-device connect
309
+ agent-device open com.example.app
310
+ agent-device snapshot
311
+ agent-device disconnect
312
+
313
+ Local profile flow:
314
+ agent-device connect --remote-config ./remote-config.json
315
+ agent-device open com.example.app
316
+ agent-device snapshot
317
+ agent-device disconnect
318
+
319
+ Script flow, per-command config:
320
+ agent-device open com.example.app --remote-config ./remote-config.json
321
+ agent-device snapshot --remote-config ./remote-config.json
322
+ agent-device disconnect --remote-config ./remote-config.json
323
+
324
+ Rules:
325
+ connect and disconnect are top-level commands. Do not write agent-device remote connect or agent-device remote disconnect.
326
+ Use connect without --remote-config when the cloud control plane owns the connection profile.
327
+ Prefer --remote-config over --daemon-base-url, --tenant, --run-id, and --lease-id when using a local profile.
328
+ For self-contained scripts, pass the same --remote-config to every operational command, including disconnect; a preceding connect is optional but not required.
329
+ For remote artifact installs, use install-from-source <url> or install-from-source --github-actions-artifact org/repo:artifact; do not download CI artifacts locally first.
330
+ After connect, let the active remote connection supply runtime hints.
331
+ For remote Android and iOS bridge React DevTools, run agent-device react-devtools normally. The CLI opens the needed local service tunnel for the DevTools daemon and keeps it alive until agent-device react-devtools stop or disconnect.
332
+ Use --debug when remote connection or transport errors need diagnostic ids and remote log hints.`},macos:{summary:"macOS desktop, frontmost-app, and menu bar surfaces",body:`agent-device help macos
333
+
334
+ Use macOS only when the task targets desktop apps, desktop surfaces, or menu bar extras.
335
+
336
+ Open and inspect:
337
+ agent-device open TextEdit --platform macos
338
+ agent-device snapshot -i --platform macos
339
+
340
+ Surfaces:
341
+ --surface app normal app session
342
+ --surface frontmost-app inspect whichever app is frontmost
343
+ --surface desktop desktop-wide surface
344
+ --surface menubar menu bar extras and menu bar-only apps
345
+
346
+ Menu bar app example:
347
+ agent-device open "Agent Device Tester Menu" --platform macos --surface menubar
348
+ agent-device snapshot -i --platform macos --surface menubar
349
+
350
+ Context menu example:
351
+ agent-device click @e66 --button secondary --platform macos
352
+ agent-device snapshot -i --platform macos
353
+
354
+ Rules:
355
+ Use open and snapshot -i for menu bar inspection. Do not output inspect as a command.
356
+ Context menus are not ambient UI: secondary-click a visible target, then re-snapshot and use the new menu-item refs.
357
+ Do not let iOS simulator-set scoping hide macOS desktop targets.
358
+ Prefer refs/selectors over raw coordinates.
359
+ macOS snapshot rects are window-space; use current refs or overlay refs instead of guessing coordinates.`},dogfood:{summary:"Exploratory QA workflow with reproducible evidence",body:`agent-device help dogfood
360
+
361
+ Use this when asked to dogfood, exploratory test, bug hunt, QA, or find issues in an app.
362
+
363
+ Goal:
364
+ Find user-visible issues from runtime behavior. Do not read app source or invent findings from code.
365
+ Produce a concise report with severity, repro commands, expected/actual behavior, and evidence paths.
366
+
367
+ Loop:
368
+ 1. Identify target app/platform; ask only if missing.
369
+ 2. Create output dirs and open a named session. If auth or OTP is required, sign in or ask the user for the code.
370
+ 3. Capture baseline snapshot -i and screenshot.
371
+ 4. Map top-level navigation, then exercise primary flows and edge states.
372
+ 5. For each issue, capture evidence and write the finding immediately, then continue.
373
+ 6. Close the session and reconcile the report summary.
374
+ Keep stateful commands serial within the same session. Parallel runs can pollute text fields, focus, alerts, and navigation state.
375
+
376
+ Coverage:
377
+ Navigation, forms, empty/error/loading states, offline or retry behavior, permissions, settings, accessibility labels, orientation/keyboard, and obvious performance stalls.
378
+ React Native warning/error overlays can be real findings or test blockers. Capture them, use react-native dismiss-overlay if unrelated, re-snapshot, and report them.
379
+ Expo Go/dev-client shells: use the provided exp:// or dev-client URL and record whether the shell, project load, or app UI is being tested. On iOS dogfood, prefer agent-device open "Expo Go" <url> when Expo Go is the known shell, then snapshot -i to confirm the project UI rather than the runner splash.
380
+ Android RN/Expo Metro: direct Android localhost URL opens with a port auto-configure host reachability.
381
+ Categories: visual, functional, UX, content, performance, diagnostics, permissions, accessibility.
382
+ Severity: critical blocks a core flow/data/crashes; high breaks a major feature; medium has friction or workaround; low is polish.
383
+
384
+ Evidence commands:
385
+ mkdir -p ./dogfood-output/screenshots ./dogfood-output/videos ./dogfood-output/traces
386
+ agent-device --session qa open <app> --platform ios
387
+ agent-device --session qa snapshot -i
388
+ agent-device --session qa screenshot ./dogfood-output/screenshots/initial.png
389
+ agent-device --session qa screenshot ./dogfood-output/screenshots/issue-001.png --overlay-refs
390
+ agent-device --session qa logs clear --restart
391
+ agent-device --session qa logs mark "issue-001 repro"
392
+ agent-device --session qa logs path
393
+ agent-device --session qa record start ./dogfood-output/videos/issue-001.mp4
394
+ agent-device --session qa record start ./dogfood-output/videos/benchmark.mp4 --hide-touches
395
+ agent-device --session qa record stop
396
+ agent-device --session qa close
397
+
398
+ Evidence rules:
399
+ Interactive/behavioral issues need step screenshots and usually a repro video.
400
+ Static/on-load issues can use one screenshot; set repro video to N/A.
401
+ Use screenshot --overlay-refs when showing the tappable target or broken state helps repro.
402
+
403
+ Report shape:
404
+ ./dogfood-output/report.md
405
+ Include date, platform, target app, session, scope, severity counts, and issues.
406
+ For each finding: ID, severity, category, title, affected flow/screen, repro commands, expected, actual, evidence files, notes.
407
+ Target 5-10 well-evidenced issues when available. If no issues are found, report coverage completed and residual risk instead of claiming the app is bug-free.
408
+
409
+ Rules:
410
+ Findings must come from observed runtime behavior, not source reads.
411
+ Re-snapshot after each mutation.
412
+ Keep commands in the report reproducible; use selectors or refs from fresh snapshots, not guessed coordinates.
413
+ Prefer refs for exploration and selectors for deterministic replay.
414
+ Use logs, network, screenshot --overlay-refs, trace, perf, or react-devtools only when they add evidence to a specific issue.
415
+ Never delete screenshots, videos, traces, or report artifacts during a session.
416
+ Escalate to help debugging or help react-devtools when runtime symptoms require those tools.`}};function v(e){let t=e.endsWith("?"),o=t?e.slice(0,-1):e;return t?`[${o}]`:`<${o}>`}function w(e){return r().filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function b(e,t){return y(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function y(e,t){if(0===t.length)return`${e}
417
+ (none)`;let o=Math.max(...t.map(e=>e.label.length))+2,a=[e];for(let e of t)a.push(` ${e.label.padEnd(o)}${e.description}`);return a.join("\n")}function k(e,t){return 0===t.length?`${e}
418
+ (none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let x=new Set(["config","remoteConfig","help","version","batchSteps","githubActionsArtifact"]),R=new Set(["appsFilter","iosSimulatorDeviceSet","sessionLocked","sessionLockConflicts"]),A=function(){let o=new Map;for(let e of r()){let t=o.get(e.key);t?t.push(e):o.set(e.key,[e])}let a=new Map;for(let e of s)a.set(e,new Set(["*"]));for(let o of e())for(let e of t(o).allowedFlags??[]){let t=a.get(e);t&&t.has("*")||(t?t.add(o):a.set(e,new Set([o])))}return[...o.entries()].map(([e,t])=>({key:e,flagDefinitions:t,config:{enabled:!x.has(e),key:e},env:{names:R.has(e)?[]:[l(e)]},supportsCommand(t){let o=a.get(e);return!!o&&(!!o.has("*")||!!t&&o.has(t))}})).sort((e,t)=>e.key.localeCompare(t.key))}(),I=new Map(A.map(e=>[e.key,e]));function S(e){return I.get(e)}function U(e){return A.filter(t=>t.config.enabled&&t.supportsCommand(e))}function N(e,t){return S(e)?.supportsCommand(t)??!1}function D(e,t,o,a){return i(function(e){let t=e.flagDefinitions.find(e=>void 0===e.setValue);if(t)return t;let o=function(e){let t=e.flagDefinitions[0];if(!t)throw Error(`Missing flag definition for option ${e.key}`);return t}(e);if("enum"===o.type){let t=o.enumValues??e.flagDefinitions.map(e=>e.setValue).filter(e=>void 0!==e);return{...o,setValue:void 0,enumValues:t}}return o}(e),t,o,a)}function E(e){let t={json:!1,help:!1,version:!1},a=null,s=[],r=[],i=!0;for(let p=0;p<e.length;p+=1){var l,d;let u=e[p];if(i&&"--"===u){i=!1;continue}if(!i){a?s.push(u):a=T(u);continue}let f=u.startsWith("--"),h=u.startsWith("-")&&u.length>1;if(!f&&!h){a?s.push(u):a=T(u);continue}let[g,m]=f?O(u):[u,void 0],v=n(g);if(l=a,d=v,"react-devtools"===l&&(!d||!N(d.key,l))){s.push(u);continue}if(!v){if(function(e,t,a){var s;if(s=a,!/^-\d+(\.\d+)?$/.test(s)||!e)return!1;let n=o(e);if(!n||n.allowsExtraPositionals)return!0;let r=n.positionalArgs??[];return 0!==r.length&&(t.length<r.length||r.some(e=>e.includes("?")))}(a,s,u)){a?s.push(u):a=u;continue}throw new c("INVALID_ARGS",`Unknown flag: ${g}`)}let w=function(e,t,o,a){if(void 0!==e.setValue){if(void 0!==o)throw new c("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:e.setValue,consumeNext:!1}}if("boolean"===e.type){if(void 0!==o)throw new c("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:!0,consumeNext:!1}}if("booleanOrString"===e.type){if(void 0!==o){if(0===o.trim().length)throw new c("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:o,consumeNext:!1}}return void 0===a||_(a)||!function(e){let t=e.trim();return!(!t||/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t))&&!!(t.startsWith("./")||t.startsWith("../")||t.startsWith("~/")||t.startsWith("/")||t.includes("/")||t.includes("\\"))}(a)?{value:!0,consumeNext:!1}:{value:a,consumeNext:!0}}let s=o??a;if(void 0===s||void 0===o&&_(s))throw new c("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:s,consumeNext:void 0===o};if("enum"===e.type){if(!e.enumValues?.includes(s))throw new c("INVALID_ARGS",`Invalid ${L(t)}: ${s}`);return{value:s,consumeNext:void 0===o}}let n=Number(s);if(!Number.isFinite(n)||"number"==typeof e.min&&n<e.min||"number"==typeof e.max&&n>e.max)throw new c("INVALID_ARGS",`Invalid ${L(t)}: ${s}`);return{value:Math.floor(n),consumeNext:void 0===o}}(v,g,m,e[p+1]);w.consumeNext&&(p+=1);let b=t[v.key];if(v.multiple){let e=Array.isArray(b)?[...b,w.value]:void 0===b?[w.value]:[b,w.value];t[v.key]=e}else t[v.key]=w.value;r.push({key:v.key,token:g})}return{command:a,positionals:s,flags:t,warnings:[],providedFlags:r}}function C(e,t){let o=t?.strictFlags??!0,s=[...e.warnings],n=d({json:!1,help:!1,version:!1},t?.defaultFlags??{});d(n,e.flags);let r=e.providedFlags.filter(t=>!N(t.key,e.command));if(r.length>0){var i,l;let t=r.map(e=>e.token),a=(i=e.command,l=t,i?1===l.length?`Flag ${l[0]} is not supported for command ${i}.`:`Flags ${l.join(", ")} are not supported for command ${i}.`:1===l.length?`Flag ${l[0]} requires a command that supports it.`:`Flags ${l.join(", ")} require a command that supports them.`);if(o)throw new c("INVALID_ARGS",a);for(let e of(s.push(a),r))delete n[e.key]}for(let t of Object.keys(n))void 0!==n[t]&&(N(t,e.command)||delete n[t]);if(function(e){if("back"===e.command&&!(new Set(e.providedFlags.filter(e=>"backMode"===e.key).map(e=>e.token)).size<=1))throw new c("INVALID_ARGS","back accepts only one explicit mode flag: use either --in-app or --system.")}(e),a(e.command,n),"batch"===e.command&&1!=+!!n.steps+ +!!n.stepsFile)throw new c("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return function(e){if(e.flags.help)return e;if("snapshot"===e.command&&e.flags.snapshotDiff){let{snapshotDiff:t,...o}=e.flags;return{command:"diff",positionals:["snapshot",...e.positionals],flags:o,warnings:e.warnings}}return e}({command:e.command,positionals:e.positionals,flags:n,warnings:s})}function O(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function L(e){return e.replace(/^-+/,"")}function _(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?O(e):[e,void 0];return void 0!==n(t)}function M(){let o,a,n,r,i,l,c,d;return o=`agent-device <command> [args] [--json]
419
+
420
+ CLI to control iOS and Android devices for AI agents.
421
+ `,a=y("Commands:",e().map(e=>{let o=t(e);return{name:e,schema:o,usage:function(e,t){if(t.listUsageOverride)return t.listUsageOverride;let o=(t.positionalArgs??[]).map(o=>{var a,s,n;let r,i,l,c;return a=e,s=t,i=(r=(n=o).endsWith("?"))?n.slice(0,-1):n,c=(l=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(i))||void 0!==s.usageOverride&&s.usageOverride.startsWith(`${a} ${i}`),r?l?`[${i}]`:c?i:`[${i}]`:c?i:`<${i}>`});return[e,...o].join(" ")}(e,o)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),n=b("Flags:",w(s)),r=k("Agent Quickstart:",u),i=y("Agent Workflows:",p),l=k("Configuration:",f),c=y("Environment:",h),d=k("Examples:",g),`${o}
422
+ ${a}
423
+
424
+ ${n}
425
+
426
+ ${r}
427
+
428
+ ${i}
429
+
430
+ ${l}
431
+
432
+ ${c}
433
+
434
+ ${d}
435
+ `}function F(e){return function(e){var t,a;let n,i=(n=m[e])?`${n.body}
436
+
437
+ Related:
438
+ agent-device help command list and global flags
439
+ agent-device help <command> command-specific flags
440
+ agent-device help workflow normal app automation loop
441
+ `:null;if(i)return i;let l=o(e);if(!l)return null;let c=(t=e,(a=l).usageOverride?a.usageOverride:[t,...(a.positionalArgs??[]).map(v),...(a.allowedFlags??[]).flatMap(e=>{var t;return(t=e,r().filter(e=>e.key===t)).map(e=>e.usageLabel??e.names[0])}).map(e=>`[${e}]`)].join(" ")),d=w(new Set(l.allowedFlags??[])),p=w(s),u=[];return d.length>0&&u.push(b("Command flags:",d)),u.push(b("Global flags:",p)),`agent-device ${c}
442
+
443
+ ${l.helpDescription}
444
+
445
+ Usage:
446
+ agent-device ${c}
447
+
448
+ ${u.join("\n\n")}
449
+ `}(T(e))}function T(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}export{M as usage,C as finalizeParsedArgs,U as getConfigurableOptionSpecs,S as getOptionSpec,d as mergeDefinedFlags,D as parseOptionValueFromSource,E as parseRawArgs,F as usageForCommand};
package/dist/src/batch.js CHANGED
@@ -1 +1 @@
1
- export{BATCH_BLOCKED_COMMANDS,DEFAULT_BATCH_MAX_STEPS,INHERITED_PARENT_FLAG_KEYS,buildBatchStepFlags,runBatch,validateAndNormalizeBatchSteps}from"./1231.js";
1
+ var _=100;export{BATCH_BLOCKED_COMMANDS,INHERITED_PARENT_FLAG_KEYS,buildBatchStepFlags,runBatch,validateAndNormalizeBatchSteps}from"./1231.js";export{_ as DEFAULT_BATCH_MAX_STEPS};