agent-device 0.16.5 → 0.16.6

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.6.apk} +0 -0
  2. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.16.6.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.6.manifest.json} +4 -4
  4. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.6.apk +0 -0
  5. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.6.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.6.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 @@
1
+ fc975087b6d0ce63e25cb5d9475f896e828222ec4d7ed12d73e4045cb7cc6c5a agent-device-android-multitouch-helper-0.16.6.apk
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "android-multitouch-helper",
3
- "version": "0.16.5",
4
- "assetName": "agent-device-android-multitouch-helper-0.16.5.apk",
5
- "sha256": "e92fcfc48e860b6237b4679165baea3e78cc58c2c5c8fd67af29c3d86e9b859d",
3
+ "version": "0.16.6",
4
+ "assetName": "agent-device-android-multitouch-helper-0.16.6.apk",
5
+ "sha256": "fc975087b6d0ce63e25cb5d9475f896e828222ec4d7ed12d73e4045cb7cc6c5a",
6
6
  "packageName": "com.callstack.agentdevice.multitouchhelper",
7
- "versionCode": 16005,
7
+ "versionCode": 16006,
8
8
  "instrumentationRunner": "com.callstack.agentdevice.multitouchhelper/.MultiTouchInstrumentation",
9
9
  "statusProtocol": "android-multitouch-helper-v1"
10
10
  }
@@ -0,0 +1 @@
1
+ a6a8555dda194d1e882a930bc6ccf555ff48f1645faf92968a0832f864c91661 agent-device-android-snapshot-helper-0.16.6.apk
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "android-snapshot-helper",
3
- "version": "0.16.5",
4
- "releaseTag": "v0.16.5",
5
- "assetName": "agent-device-android-snapshot-helper-0.16.5.apk",
3
+ "version": "0.16.6",
4
+ "releaseTag": "v0.16.6",
5
+ "assetName": "agent-device-android-snapshot-helper-0.16.6.apk",
6
6
  "apkUrl": null,
7
- "sha256": "fc48a158031664b8bcf6cf301484433fc9ccd2a5494d4565571d7399bd63ab23",
8
- "checksumName": "agent-device-android-snapshot-helper-0.16.5.apk.sha256",
7
+ "sha256": "a6a8555dda194d1e882a930bc6ccf555ff48f1645faf92968a0832f864c91661",
8
+ "checksumName": "agent-device-android-snapshot-helper-0.16.6.apk.sha256",
9
9
  "packageName": "com.callstack.agentdevice.snapshothelper",
10
- "versionCode": 16005,
10
+ "versionCode": 16006,
11
11
  "instrumentationRunner": "com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation",
12
12
  "minSdk": 23,
13
13
  "targetSdk": 36,
@@ -0,0 +1 @@
1
+ import{AppError as e}from"./9152.js";let r=new Set(["1","true","yes","on"]),n=new Set(["0","false","no","off"]);function t(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`}function i(r,n,t,f){if(r.multiple)return(Array.isArray(n)?n:[n]).map(e=>i({...r,multiple:!1},e,t,f));if("boolean"===r.type){var a=n,u=t,l=f;if("boolean"==typeof a)return a;if("string"==typeof a){let e=o(a);if(void 0!==e)return e}throw new e("INVALID_ARGS",`Invalid value for "${l}" in ${u}. Expected boolean.`)}if("booleanOrString"===r.type){if("boolean"==typeof n)return n;if("string"==typeof n&&void 0!==o(n))return o(n);if("string"==typeof n&&n.trim().length>0)return n;throw new e("INVALID_ARGS",`Invalid value for "${f}" in ${t}. Expected boolean or non-empty string.`)}if("string"===r.type){if("string"==typeof n&&n.trim().length>0)return n;throw new e("INVALID_ARGS",`Invalid value for "${f}" in ${t}. Expected non-empty string.`)}if("enum"===r.type){if(void 0!==r.setValue){var p=r,m=n,s=t,I=f;let i=p.setValue;if(m===i)return i;if("string"==typeof m){let e=m.trim();if(""===e||"true"===e||"1"===e)return i;if("false"===e||"0"===e)return}if(!0===m)return i;if(!1!==m)throw new e("INVALID_ARGS",`Invalid value for "${I}" in ${s}. Expected boolean-like value for enum flag.`);return}if("string"!=typeof n||!r.enumValues?.includes(n))throw new e("INVALID_ARGS",`Invalid value for "${f}" in ${t}. Expected one of: ${r.enumValues?.join(", ")}.`);return n}let v="number"==typeof n?n:"string"==typeof n?Number(n):NaN;if(!Number.isFinite(v)||!Number.isInteger(v))throw new e("INVALID_ARGS",`Invalid value for "${f}" in ${t}. Expected integer.`);if("number"==typeof r.min&&v<r.min)throw new e("INVALID_ARGS",`Invalid value for "${f}" in ${t}. Must be >= ${r.min}.`);if("number"==typeof r.max&&v>r.max)throw new e("INVALID_ARGS",`Invalid value for "${f}" in ${t}. Must be <= ${r.max}.`);return v}function o(e){let t=e.trim().toLowerCase();return!!r.has(t)||!n.has(t)&&void 0}export{t as buildPrimaryEnvVarName,i as parseSourceValue};
package/dist/src/1231.js CHANGED
@@ -1 +1 @@
1
- import{asAppError as t,AppError as e}from"./9152.js";let r=100,a=new Set(["batch","replay"]),o=new Set(["command","positionals","flags","runtime"]),n=["platform","target","device","udid","serial","verbose","out"];async function s(e,a,o){let n=e.flags,s=n?.batchOnError??"stop";if("stop"!==s)return h("INVALID_ARGS",`Unsupported batch on-error mode: ${s}.`);let l=n?.batchMaxSteps??r;if(!Number.isInteger(l)||l<1||l>1e3)return h("INVALID_ARGS",`Invalid batch max-steps: ${String(n?.batchMaxSteps)}`);try{let t=i(n?.batchSteps,l),r=Date.now(),s=[];for(let[r,n]of t.entries()){let i=await m(e,a,n,o,r+1);if(!i.ok)return{ok:!1,error:{code:i.error.code,message:`Batch failed at step ${i.step} (${n.command}): ${i.error.message}`,hint:i.error.hint,diagnosticId:i.error.diagnosticId,logPath:i.error.logPath,details:{...i.error.details??{},step:i.step,command:n.command,positionals:n.positionals,executed:r,total:t.length,partialResults:s}}};s.push(i.result)}return{ok:!0,data:{total:t.length,executed:t.length,totalDurationMs:Date.now()-r,results:s}}}catch(r){let e=t(r);return h(e.code,e.message,e.details)}}function i(t,r){if(!Array.isArray(t)||0===t.length)throw new e("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(t.length>r)throw new e("INVALID_ARGS",`batch has ${t.length} steps; max allowed is ${r}.`);let n=[];for(let r=0;r<t.length;r+=1){let s=t[r];if(!s||"object"!=typeof s)throw new e("INVALID_ARGS",`Invalid batch step at index ${r}.`);let i=Object.keys(s).filter(t=>!o.has(t));if(i.length>0){let t=i.map(t=>`"${t}"`).join(", ");throw new e("INVALID_ARGS",`Batch step ${r+1} has unknown field(s): ${t}. Allowed fields: command, positionals, flags, runtime.`)}let l="string"==typeof s.command?s.command.trim().toLowerCase():"";if(!l)throw new e("INVALID_ARGS",`Batch step ${r+1} requires command.`);if(a.has(l))throw new e("INVALID_ARGS",`Batch step ${r+1} cannot run ${l}.`);if(void 0!==s.positionals&&!Array.isArray(s.positionals))throw new e("INVALID_ARGS",`Batch step ${r+1} positionals must be an array.`);let c=s.positionals??[];if(c.some(t=>"string"!=typeof t))throw new e("INVALID_ARGS",`Batch step ${r+1} positionals must contain only strings.`);if(void 0!==s.flags&&("object"!=typeof s.flags||Array.isArray(s.flags)||!s.flags))throw new e("INVALID_ARGS",`Batch step ${r+1} flags must be an object.`);if(void 0!==s.runtime&&("object"!=typeof s.runtime||Array.isArray(s.runtime)||!s.runtime))throw new e("INVALID_ARGS",`Batch step ${r+1} runtime must be an object.`);n.push({command:l,positionals:c,flags:s.flags??{},runtime:s.runtime})}return n}function l(t,e){let{batchSteps:r,batchOnError:a,batchMaxSteps:o,...n}=e??{};return c(t,n)}function c(t,e){let r=t??{};for(let t of n)void 0===e[t]&&void 0!==r[t]&&(e[t]=r[t]);return e}async function m(t,e,r,a,o){let n=Date.now(),s=l(t.flags,r.flags);void 0===s.session&&(s.session=e);let i=await a({token:t.token,session:e,command:r.command,positionals:r.positionals,flags:s,runtime:void 0===r.runtime?t.runtime:r.runtime,meta:t.meta}),c=Date.now()-n;return i.ok?{ok:!0,step:o,result:{step:o,command:r.command,ok:!0,data:i.data??{},durationMs:c}}:{ok:!1,step:o,error:i.error}}function h(t,e,r){return{ok:!1,error:{code:t,message:e,...r?{details:r}:{}}}}export{a as BATCH_BLOCKED_COMMANDS,r as DEFAULT_BATCH_MAX_STEPS,n as INHERITED_PARENT_FLAG_KEYS,l as buildBatchStepFlags,c as mergeParentFlags,s as runBatch,i as validateAndNormalizeBatchSteps};
1
+ import{asAppError as t,AppError as e}from"./9152.js";let r=new Set(["batch","replay"]),a=new Set(["command","positionals","flags","runtime"]),o=["platform","target","device","udid","serial","verbose","out"];async function n(e,r,a){let o=e.flags,n=o?.batchOnError??"stop";if("stop"!==n)return m("INVALID_ARGS",`Unsupported batch on-error mode: ${n}.`);let i=o?.batchMaxSteps??100;if(!Number.isInteger(i)||i<1||i>1e3)return m("INVALID_ARGS",`Invalid batch max-steps: ${String(o?.batchMaxSteps)}`);try{let t=s(o?.batchSteps,i),n=Date.now(),l=[];for(let[o,n]of t.entries()){let s=await c(e,r,n,a,o+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:o,total:t.length,partialResults:l}}};l.push(s.result)}return{ok:!0,data:{total:t.length,executed:t.length,totalDurationMs:Date.now()-n,results:l}}}catch(r){let e=t(r);return m(e.code,e.message,e.details)}}function s(t,o){if(!Array.isArray(t)||0===t.length)throw new e("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(t.length>o)throw new e("INVALID_ARGS",`batch has ${t.length} steps; max allowed is ${o}.`);let n=[];for(let o=0;o<t.length;o+=1){let s=t[o];if(!s||"object"!=typeof s)throw new e("INVALID_ARGS",`Invalid batch step at index ${o}.`);let i=Object.keys(s).filter(t=>!a.has(t));if(i.length>0){let t=i.map(t=>`"${t}"`).join(", ");throw new e("INVALID_ARGS",`Batch step ${o+1} has unknown field(s): ${t}. Allowed fields: command, positionals, flags, runtime.`)}let l="string"==typeof s.command?s.command.trim().toLowerCase():"";if(!l)throw new e("INVALID_ARGS",`Batch step ${o+1} requires command.`);if(r.has(l))throw new e("INVALID_ARGS",`Batch step ${o+1} cannot run ${l}.`);if(void 0!==s.positionals&&!Array.isArray(s.positionals))throw new e("INVALID_ARGS",`Batch step ${o+1} positionals must be an array.`);let c=s.positionals??[];if(c.some(t=>"string"!=typeof t))throw new e("INVALID_ARGS",`Batch step ${o+1} positionals must contain only strings.`);if(void 0!==s.flags&&("object"!=typeof s.flags||Array.isArray(s.flags)||!s.flags))throw new e("INVALID_ARGS",`Batch step ${o+1} flags must be an object.`);if(void 0!==s.runtime&&("object"!=typeof s.runtime||Array.isArray(s.runtime)||!s.runtime))throw new e("INVALID_ARGS",`Batch step ${o+1} runtime must be an object.`);n.push({command:l,positionals:c,flags:s.flags??{},runtime:s.runtime})}return n}function i(t,e){let{batchSteps:r,batchOnError:a,batchMaxSteps:o,...n}=e??{};return l(t,n)}function l(t,e){let r=t??{};for(let t of o)void 0===e[t]&&void 0!==r[t]&&(e[t]=r[t]);return e}async function c(t,e,r,a,o){let n=Date.now(),s=i(t.flags,r.flags);void 0===s.session&&(s.session=e);let l=await a({token:t.token,session:e,command:r.command,positionals:r.positionals,flags:s,runtime:void 0===r.runtime?t.runtime:r.runtime,meta:t.meta}),c=Date.now()-n;return l.ok?{ok:!0,step:o,result:{step:o,command:r.command,ok:!0,data:l.data??{},durationMs:c}}:{ok:!1,step:o,error:l.error}}function m(t,e,r){return{ok:!1,error:{code:t,message:e,...r?{details:r}:{}}}}export{r as BATCH_BLOCKED_COMMANDS,o as INHERITED_PARENT_FLAG_KEYS,i as buildBatchStepFlags,l as mergeParentFlags,n as runBatch,s as validateAndNormalizeBatchSteps};
@@ -0,0 +1 @@
1
+ var e;import{AppError as s}from"./9152.js";import{SCREENSHOT_SPECIFIC_FLAG_DEFINITIONS as t,SCREENSHOT_COMMAND_FLAG_KEYS as a}from"./5310.js";import{DEFAULT_APPS_FILTER as o}from"./1393.js";import{listCommandDescriptionMetadata as i}from"./5186.js";let r="<wifi|airplane|location> <on|off>",n="location set <lat> <lon>",l="animations <on|off>",p="appearance <light|dark|toggle>",u="faceid <match|nonmatch|enroll|unenroll>",c="touchid <match|nonmatch|enroll|unenroll>",d="fingerprint <match|nonmatch>",m="clear-app-state [app-id]",g="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",h="permission <grant|reset> <accessibility|screen-recording|input-monitoring>",y=`macOS supports only settings ${p} and settings ${h}. wifi|airplane|location|animations remain unsupported on macOS.`,b=`settings ${r} | settings ${n} | settings ${l} | settings ${p} | settings ${u} | settings ${c} | settings ${d} | settings ${m} | settings ${g} | settings ${h}`,f=`settings requires ${r}, ${n}, ${l}, ${p}, ${u}, ${c}, ${d}, ${m}, ${g}, or ${h}`;function k(e){let s=e.trim().toLowerCase();return"appearance"===s||"permission"===s}function v(e){return`Unsupported macOS setting: ${e}. ${y}`}let D=["app","frontmost-app","desktop","menubar"];function w(e){let t=e?.trim().toLowerCase();if("app"===t||"frontmost-app"===t||"desktop"===t||"menubar"===t)return t;throw new s("INVALID_ARGS",`Invalid surface: ${e}. Use ${D.join("|")}.`)}let L="https://github.com/callstackincubator/agent-device/issues/558",O="https://github.com/callstackincubator/agent-device/issues/new";function S(...e){return e}let x=S("snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"),A=S("snapshotDepth","snapshotScope","snapshotRaw"),M=S("metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"),E=S("metroHost","metroPort","bundleUrl"),R=S("count","intervalMs","holdMs","jitterPx","doubleTap"),U=S("replayUpdate","replayEnv"),F=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"leaseBackend",names:["--lease-backend"],type:"enum",enumValues:["ios-simulator","ios-instance","android-instance"],usageLabel:"--lease-backend ios-simulator|ios-instance|android-instance",usageDescription:"Lease backend for remote tenant connection admission"},{key:"force",names:["--force"],type:"boolean",usageLabel:"--force",usageDescription:"Force connection state replacement when reconnecting"},{key:"noLogin",names:["--no-login"],type:"boolean",usageLabel:"--no-login",usageDescription:"Connect: fail instead of starting implicit cloud login"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","linux","apple"],usageLabel:"--platform ios|macos|android|linux|apple",usageDescription:"Platform to target (`apple` aliases the Apple automation backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv","desktop"],usageLabel:"--target mobile|tv|desktop",usageDescription:"Device target class to match"},{key:"device",names:["--device"],type:"string",usageLabel:"--device <name>",usageDescription:"Device name to target"},{key:"udid",names:["--udid"],type:"string",usageLabel:"--udid <udid>",usageDescription:"iOS device UDID"},{key:"serial",names:["--serial"],type:"string",usageLabel:"--serial <serial>",usageDescription:"Android device serial"},{key:"surface",names:["--surface"],type:"enum",enumValues:D,usageLabel:"--surface app|frontmost-app|desktop|menubar",usageDescription:"macOS session surface for open (defaults to app)"},{key:"headless",names:["--headless"],type:"boolean",usageLabel:"--headless",usageDescription:"Boot: launch Android emulator without a GUI window"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"Session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"Session-scoped Metro/debug port hint"},{key:"metroProjectRoot",names:["--project-root"],type:"string",usageLabel:"--project-root <path>",usageDescription:"metro prepare: React Native project root (default: cwd)"},{key:"metroKind",names:["--kind"],type:"enum",enumValues:["auto","react-native","expo"],usageLabel:"--kind auto|react-native|expo",usageDescription:"metro prepare: detect or force the Metro launcher kind"},{key:"metroPublicBaseUrl",names:["--public-base-url"],type:"string",usageLabel:"--public-base-url <url>",usageDescription:"metro prepare: public base URL used for direct bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional bridge origin for remote Metro access"},{key:"metroBearerToken",names:["--bearer-token"],type:"string",usageLabel:"--bearer-token <token>",usageDescription:"metro prepare: host bridge bearer token (or AGENT_DEVICE_METRO_BEARER_TOKEN; falls back to AGENT_DEVICE_DAEMON_AUTH_TOKEN)"},{key:"metroPreparePort",names:["--port"],type:"int",min:1,max:65535,usageLabel:"--port <port>",usageDescription:"metro prepare: local Metro port (default: 8081)"},{key:"metroListenHost",names:["--listen-host"],type:"string",usageLabel:"--listen-host <host>",usageDescription:"metro prepare: host Metro listens on (default: 0.0.0.0)"},{key:"metroStatusHost",names:["--status-host"],type:"string",usageLabel:"--status-host <host>",usageDescription:"metro prepare: host used for local /status polling (default: 127.0.0.1)"},{key:"metroStartupTimeoutMs",names:["--startup-timeout-ms"],type:"int",min:1,usageLabel:"--startup-timeout-ms <ms>",usageDescription:"metro prepare: timeout while waiting for Metro to become ready"},{key:"metroProbeTimeoutMs",names:["--probe-timeout-ms"],type:"int",min:1,usageLabel:"--probe-timeout-ms <ms>",usageDescription:"metro prepare: timeout for /status and proxy bridge calls"},{key:"metroRuntimeFile",names:["--runtime-file"],type:"string",usageLabel:"--runtime-file <path>",usageDescription:"metro prepare: optional file path to persist the JSON result"},{key:"metroNoReuseExisting",names:["--no-reuse-existing"],type:"boolean",usageLabel:"--no-reuse-existing",usageDescription:"metro prepare: always start a fresh Metro process"},{key:"metroNoInstallDeps",names:["--no-install-deps"],type:"boolean",usageLabel:"--no-install-deps",usageDescription:"metro prepare: skip package-manager install when node_modules is missing"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"Session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"Session-scoped deep link / launch URL hint"},{key:"iosSimulatorDeviceSet",names:["--ios-simulator-device-set"],type:"string",usageLabel:"--ios-simulator-device-set <path>",usageDescription:"Scope iOS simulator discovery/commands to this simulator device set"},{key:"androidDeviceAllowlist",names:["--android-device-allowlist"],type:"string",usageLabel:"--android-device-allowlist <serials>",usageDescription:"Comma/space separated Android serial allowlist for discovery/selection"},{key:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"launchConsole",names:["--launch-console"],type:"string",usageLabel:"--launch-console <path>",usageDescription:"open: capture the initial iOS simulator launch console window to a file"},{key:"launchArgs",names:["--launch-args"],type:"string",multiple:!0,usageLabel:"--launch-args <arg>",usageDescription:"open: repeatable launch argument forwarded verbatim to the platform launch command (iOS app process args; Android adb shell am start args). Linux and macOS reject the flag."},{key:"header",names:["--header"],type:"string",multiple:!0,usageLabel:"--header <name:value>",usageDescription:"install-from-source: repeatable HTTP header for URL downloads"},{key:"githubActionsArtifact",names:["--github-actions-artifact"],type:"string",usageLabel:"--github-actions-artifact <owner/repo:artifact>",usageDescription:"install-from-source: GitHub Actions artifact resolved by a remote daemon"},{key:"installSource",names:[],type:"string"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"quality",names:["--quality"],type:"int",min:5,max:10,usageLabel:"--quality <5-10>",usageDescription:"Record: scale recording resolution from 5 (50%) through 10 (native resolution)"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: skip touch-overlay post-processing for faster raw benchmark videos"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"delayMs",names:["--delay-ms"],type:"int",min:0,max:1e4,usageLabel:"--delay-ms <ms>",usageDescription:"Delay between typed characters"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"pixels",names:["--pixels"],type:"int",min:1,max:1e5,usageLabel:"--pixels <n>",usageDescription:"Scroll: explicit gesture distance in pixels"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"backMode",names:["--in-app"],type:"enum",enumValues:["in-app","system"],setValue:"in-app",usageLabel:"--in-app",usageDescription:"Back: use app-provided back UI when available"},{key:"backMode",names:["--system"],type:"enum",enumValues:["in-app","system"],setValue:"system",usageLabel:"--system",usageDescription:"Back: use system back input or gesture when available"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"snapshotDiff",names:["--diff"],type:"boolean",usageLabel:"--diff",usageDescription:"Snapshot: show structural diff against the previous session baseline"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"networkInclude",names:["--include"],type:"enum",enumValues:["summary","headers","body","all"],usageLabel:"--include summary|headers|body|all",usageDescription:"Network: include headers, bodies, or both in output"},{key:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated simulator/emulator after ending session"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"retainPaths",names:["--retain-paths"],type:"boolean",usageLabel:"--retain-paths",usageDescription:"install-from-source: keep materialized artifact paths after install"},{key:"retentionMs",names:["--retention-ms"],type:"int",min:1,usageLabel:"--retention-ms <ms>",usageDescription:"install-from-source: retention TTL for materialized artifact paths"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"replayMaestro",names:["--maestro"],type:"boolean",usageLabel:"--maestro",usageDescription:`Replay: treat input as a Maestro YAML compatibility flow. Supported subset: ${(e=["app launch with Apple-platform launch arguments and Android/iOS simulator clearState","runFlow file/inline with when.platform, when.visible, when.notVisible, and limited when.true boolean/platform expressions","onFlowStart and onFlowComplete hooks","deterministic repeat.times","tapOn including optional, index, childOf, label, and absolute/percentage point taps","doubleTapOn and longPressOn","inputText, focused-field eraseText, and pasteText","openLink","visibility assertions and extendedWaitUntil","scroll and scrollUntilVisible","absolute/percentage swipe and swipe.label","screenshots","keyboard dismiss","basic pressKey, back, animation waits, and stopApp","ordered trusted runScript file/env scripts with http.post, json, and output variables"]).length>1?`${e.slice(0,-1).join(", ")}, and ${e.at(-1)}`:e[0]??""}. Unsupported syntax fails loudly with a link to ${L}`},{key:"replayEnv",names:["-e","--env"],type:"string",multiple:!0,usageLabel:"-e KEY=VALUE, --env KEY=VALUE",usageDescription:"Replay/Test: inject or override a ${KEY} variable for the script (repeatable)"},{key:"failFast",names:["--fail-fast"],type:"boolean",usageLabel:"--fail-fast",usageDescription:"Test: stop the suite after the first failing script"},{key:"timeoutMs",names:["--timeout"],type:"int",min:1,usageLabel:"--timeout <ms>",usageDescription:"Test: maximum wall-clock time per script attempt"},{key:"retries",names:["--retries"],type:"int",min:0,max:3,usageLabel:"--retries <n>",usageDescription:"Test: retry each failed script up to n additional times"},{key:"artifactsDir",names:["--artifacts-dir"],type:"string",usageLabel:"--artifacts-dir <path>",usageDescription:"Test: root directory for suite artifacts"},{key:"reportJunit",names:["--report-junit"],type:"string",usageLabel:"--report-junit <path>",usageDescription:"Test: write a JUnit XML report for the replay suite"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--all"],type:"enum",enumValues:["user-installed","all"],setValue:"all",usageLabel:"--all",usageDescription:"Apps: include system/OEM apps"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"snapshotForceFull",names:["--force-full"],type:"boolean",usageLabel:"--force-full",usageDescription:"Snapshot: re-emit the full tree even when unchanged"},{key:"findFirst",names:["--first"],type:"boolean",usageLabel:"--first",usageDescription:"Find: pick the first match when ambiguous"},{key:"findLast",names:["--last"],type:"boolean",usageLabel:"--last",usageDescription:"Find: pick the last match when ambiguous"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{key:"overlayRefs",names:["--overlay-refs"],type:"boolean",usageLabel:"--overlay-refs",usageDescription:"Screenshot: draw current snapshot refs and target rectangles onto the saved PNG; diff screenshot: also write a separate current-screen overlay guide"},...t,{key:"baseline",names:["--baseline","-b"],type:"string",usageLabel:"--baseline, -b <path>",usageDescription:"Diff screenshot: path to baseline image file"},{key:"threshold",names:["--threshold"],type:"string",usageLabel:"--threshold <0-1>",usageDescription:"Diff screenshot: color distance threshold (default 0.1)"}],P=new Set(["json","config","remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","leaseBackend","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),T=new Map;for(let e of F)for(let s of e.names)T.set(s,e);function _(e){return T.get(e)}function C(){return F}let I={auth:{usageOverride:"auth status|login|logout",listUsageOverride:"auth status|login|logout",helpDescription:"Manage cloud CLI authentication",summary:"Manage cloud authentication",positionalArgs:["status|login|logout"]},connect:{usageOverride:"connect [--remote-config <path>] [--tenant <id>] [--run-id <id>] [--lease-backend <backend>] [--force] [--no-login]",helpDescription:"Connect to a remote daemon, authenticate when needed, and save remote session state. AGENT_DEVICE_CLOUD_BASE_URL is the bridge/control-plane API origin; use AGENT_DEVICE_DAEMON_AUTH_TOKEN=adc_live_... for CI/service-token automation.",summary:"Connect to remote daemon",allowedFlags:["force","noLogin",...M,"launchUrl"]},connection:{usageOverride:"connection status",listUsageOverride:"connection status",helpDescription:"Inspect active remote connection state",summary:"Inspect remote connection",positionalArgs:["status"]},disconnect:{helpDescription:"Disconnect remote daemon state, stop owned Metro companion, and release lease",summary:"Disconnect remote daemon",allowedFlags:["shutdown"]},mcp:{helpDescription:"Start the official stdio MCP server. It exposes structured command tools backed by the agent-device client.",summary:"Start MCP server"},"react-devtools":{usageOverride:"react-devtools [...args]",listUsageOverride:"react-devtools [...args]",helpDescription:"Run pinned agent-react-devtools commands for React Native performance profiling, component trees, props/state/hooks, and render analysis",summary:"Profile React Native performance and component renders",positionalArgs:["args?"],allowsExtraPositionals:!0}},j={boot:{summary:"Boot target device/simulator",allowedFlags:["headless"]},open:{helpDescription:"Boot device/simulator; optionally launch app or deep link URL (macOS also supports --surface app|frontmost-app|desktop|menubar)",summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","launchConsole","launchArgs","saveScript","relaunch","surface"]},close:{positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{positionalArgs:["app","path"]},install:{positionalArgs:["app","path"]},"install-from-source":{usageOverride:"install-from-source <url> | install-from-source --github-actions-artifact <owner/repo:artifact>",listUsageOverride:"install-from-source <url> | install-from-source --github-actions-artifact",helpDescription:"Install app from a URL or remote-resolved source",summary:"Install app from a source",positionalArgs:["url?"],allowedFlags:["header","githubActionsArtifact","installSource","retainPaths","retentionMs"]},apps:{helpDescription:"List user-installed apps; use --all to include system/OEM apps",summary:"List installed apps",allowedFlags:["appsFilter"],defaults:{appsFilter:o}},push:{positionalArgs:["bundleOrPackage","payloadOrJson"]},snapshot:{usageOverride:"snapshot [--diff] [-i] [-c] [-d <depth>] [-s <scope>] [--raw] [--force-full]",helpDescription:"Capture accessibility tree or diff against the previous session baseline",allowedFlags:["snapshotDiff",...x,"snapshotForceFull"]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [current.png] [--out <diff.png>] [--threshold <0-1>] [--overlay-refs]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind","current?"],allowedFlags:[...x,"baseline","threshold","out","overlayRefs"]},screenshot:{helpDescription:"Capture screenshot (macOS app sessions default to the app window; use --fullscreen for full desktop, --max-size to downscale, --overlay-refs to annotate current refs, or --no-stabilize for low-latency Android capture loops)",positionalArgs:["path?"],allowedFlags:a},appstate:{helpDescription:"Show foreground app/activity"},metro:{usageOverride:"metro prepare (--public-base-url <url> | --proxy-base-url <url>) [--project-root <path>] [--port <port>] [--kind auto|react-native|expo]\n agent-device metro reload [--metro-host <host>] [--metro-port <port>] [--bundle-url <url>]",listUsageOverride:"metro prepare --public-base-url <url> | --proxy-base-url <url>; metro reload",helpDescription:"Prepare a local Metro runtime or ask Metro to reload connected React Native apps",summary:"Prepare Metro or reload apps",positionalArgs:["prepare|reload"],allowedFlags:[...E,...M]},clipboard:{usageOverride:"clipboard read | clipboard write <text>",listUsageOverride:"clipboard read | clipboard write <text>",helpDescription:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0},keyboard:{usageOverride:"keyboard [status|get|dismiss|enter|return]",helpDescription:"Inspect Android keyboard visibility/type or press/dismiss the device keyboard",summary:"Inspect, press, or dismiss the device keyboard",positionalArgs:["action?"]},back:{usageOverride:"back [--in-app|--system]",allowedFlags:["backMode"]},rotate:{usageOverride:"rotate <portrait|portrait-upside-down|landscape-left|landscape-right>",helpDescription:"Rotate device orientation on iOS and Android",positionalArgs:["orientation"]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...A]},get:{usageOverride:"get text|attrs <@ref|selector>",positionalArgs:["subcommand","target"],allowedFlags:[...A]},find:{usageOverride:"find <locator|text> <action> [value] [--first|--last]",helpDescription:"Find by text/label/value/role/id and run action",summary:"Find an element and act",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw","findFirst","findLast"]},is:{positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...A]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",positionalArgs:["action?","timeout?"]},click:{usageOverride:"click <x y|@ref|selector>",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:[...R,"clickButton",...A]},replay:{positionalArgs:["path"],allowedFlags:["replayMaestro",...U,"timeoutMs"]},test:{usageOverride:"test <path-or-glob>...",listUsageOverride:"test <path-or-glob>...",helpDescription:"Run one or more replay scripts as a serial test suite",summary:"Run replay test suites",positionalArgs:["pathOrGlob"],allowsExtraPositionals:!0,allowedFlags:["replayMaestro",...U,"failFast","timeoutMs","retries","artifactsDir","reportJunit"]},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",listUsageOverride:"batch --steps <json> | --steps-file <path>",helpDescription:"Execute multiple commands in one daemon request",summary:"Run multiple commands",allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"]},press:{usageOverride:"press <x y|@ref|selector>",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:[...R,...A]},longpress:{usageOverride:"longpress <x y|@ref|selector> [durationMs]",positionalArgs:["targetOrX","yOrDurationMs?","durationMs?"],allowsExtraPositionals:!0,allowedFlags:[...A]},swipe:{helpDescription:"Swipe coordinates with optional repeat pattern",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},gesture:{usageOverride:"gesture <pan|fling|swipe|pinch|rotate|transform> ...",listUsageOverride:"gesture <pan|fling|swipe|pinch|rotate|transform> ...",helpDescription:"Run touch gestures: pan <x> <y> <dx> <dy> [durationMs], fling <up|down|left|right> <x> <y> [distance] [durationMs], swipe <left|right|left-edge|right-edge> [durationMs], pinch <scale> [x] [y], rotate <degrees> [x] [y] [velocity], or transform <x> <y> <dx> <dy> <scale> <degrees> [durationMs]",summary:"Run pan, fling, swipe, pinch, rotate, or transform gestures",positionalArgs:["pan|fling|swipe|pinch|rotate|transform","args?"],allowsExtraPositionals:!0},focus:{positionalArgs:["x","y"]},type:{positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:["delayMs"]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...A,"delayMs"]},scroll:{usageOverride:"scroll <direction|top|bottom> [amount] [--pixels <n>]",helpDescription:"Scroll in direction, or verify hidden content and scroll toward top/bottom",summary:"Scroll in a direction or to an edge",positionalArgs:["directionOrEdge","amount?"],allowedFlags:["pixels"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",positionalArgs:["event","payloadJson?"]},record:{usageOverride:"record start [path] [--fps <n>] [--quality <5-10>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording; Android recordings longer than the 180s adb screenrecord limit are returned as multiple MP4 chunks",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","quality","hideTouches"]},"react-native":{usageOverride:"react-native dismiss-overlay",listUsageOverride:"react-native dismiss-overlay",positionalArgs:["dismiss-overlay"]},trace:{usageOverride:"trace start <path> | trace stop <path>",listUsageOverride:"trace start <path> | trace stop <path>",helpDescription:"Start/stop trace log capture; when an artifact path is requested, pass the same positional path to start and stop",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"]},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] [--include summary|headers|body|all] | network log [limit] [summary|headers|body|all] [--include summary|headers|body|all]",helpDescription:"Dump recent HTTP(s) traffic parsed from the session app log",summary:"Show recent HTTP traffic",positionalArgs:["dump|log","limit?","include?"],allowedFlags:["networkInclude"]},settings:{usageOverride:b,listUsageOverride:"settings [area] [options]",helpDescription:"Toggle OS settings, animation scales, appearance, and app permissions (macOS supports only settings appearance <light|dark|toggle> and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>; wifi|airplane|location|animations remain unsupported on macOS; mobile permission actions use the active session app)",summary:"Change OS settings and app permissions",positionalArgs:["setting","state","target?","mode?"]},session:{usageOverride:"session list",positionalArgs:["list?"]}},N=new Map(i().map(e=>[e.name,{helpDescription:e.description}]));function V(e){if(e)return B(e)}function $(e){let s=B(e);if(!s)throw Error(`Missing command schema for ${e}`);return s}function B(e){let s=Object.hasOwn(I,e)?I[e]:void 0;if(s)return s;let t=N.get(e),a=Object.hasOwn(j,e)?j[e]:void 0;if(t)return a?{...t,...a}:t}function K(e,s){let t=V(e);if(!t?.defaults)return!1;let a=!1;for(let[e,o]of Object.entries(t.defaults))void 0===s[e]&&(s[e]=o,a=!0);return a}export{P as GLOBAL_FLAG_KEYS,L as MAESTRO_COMPAT_TRACKER_URL,O as MAESTRO_NEW_ISSUE_URL,f as SETTINGS_INVALID_ARGS_MESSAGE,K as applyCommandDefaults,$ as getCliCommandSchema,V as getCommandSchema,_ as getFlagDefinition,C as getFlagDefinitions,v as getUnsupportedMacOsSettingMessage,k as isMacOsSettingSupported,w as parseSessionSurface};
@@ -0,0 +1 @@
1
+ import{AppError as t}from"./9152.js";function e(t){return t?{message:t}:{}}function r(t,e){return e?{...t,message:e}:t}function n(t){return"string"==typeof t?.message&&t.message.length>0?t.message:null}function i(e,r){if(void 0===e||""===e.trim())throw new t("INVALID_ARGS",`settings location set requires ${r}`);return o(Number(e),r)}function a(t){return{latitude:o(t?.latitude,"latitude"),longitude:o(t?.longitude,"longitude")}}function o(e,r){let n="latitude"===r?-90:-180,i="latitude"===r?90:180;if("number"!=typeof e||!Number.isFinite(e)||e<n||e>i)throw new t("INVALID_ARGS",`${r} must be a number from ${n} to ${i}`);return e}function s(e){if(void 0===e)throw new t("INVALID_ARGS","rotate requires an orientation argument. Use portrait|portrait-upside-down|landscape-left|landscape-right.");switch(e?.trim().toLowerCase()){case"portrait":return"portrait";case"portrait-upside-down":case"upside-down":return"portrait-upside-down";case"landscape-left":case"left":return"landscape-left";case"landscape-right":case"right":return"landscape-right";default:throw new t("INVALID_ARGS",`Invalid rotation: ${e}. Use portrait|portrait-upside-down|landscape-left|landscape-right.`)}}export{s as parseDeviceRotation,n as readCommandMessage,i as readLocationCoordinate,a as requireLocationCoordinates,e as successText,r as withSuccessText};
package/dist/src/208.js CHANGED
@@ -1 +1 @@
1
- import e from"node:fs";import t from"node:path";import{AppError as n}from"./9152.js";import{resolveUserPath as r}from"./3267.js";let o=new Set(["1","true","yes","on"]),i=new Set(["0","false","no","off"]);function a(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`}function s(e,t,r,o){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>s({...e,multiple:!1},t,r,o));if("boolean"===e.type){var i=t,a=r,u=o;if("boolean"==typeof i)return i;if("string"==typeof i){let e=l(i);if(void 0!==e)return e}throw new n("INVALID_ARGS",`Invalid value for "${u}" in ${a}. Expected boolean.`)}if("booleanOrString"===e.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==l(t))return l(t);if("string"==typeof t&&t.trim().length>0)return t;throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Expected boolean or non-empty string.`)}if("string"===e.type){if("string"==typeof t&&t.trim().length>0)return t;throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Expected non-empty string.`)}if("enum"===e.type){if(void 0!==e.setValue){var f=e,y=t,p=r,m=o;let i=f.setValue;if(y===i)return i;if("string"==typeof y){let e=y.trim();if(""===e||"true"===e||"1"===e)return i;if("false"===e||"0"===e)return}if(!0===y)return i;if(!1!==y)throw new n("INVALID_ARGS",`Invalid value for "${m}" in ${p}. Expected boolean-like value for enum flag.`);return}if("string"!=typeof t||!e.enumValues?.includes(t))throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Expected one of: ${e.enumValues?.join(", ")}.`);return t}let c="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(c)||!Number.isInteger(c))throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Expected integer.`);if("number"==typeof e.min&&c<e.min)throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Must be >= ${e.min}.`);if("number"==typeof e.max&&c>e.max)throw new n("INVALID_ARGS",`Invalid value for "${o}" in ${r}. Must be <= ${e.max}.`);return c}function l(e){let t=e.trim().toLowerCase();return!!o.has(t)||!i.has(t)&&void 0}let u=[{key:"stateDir",type:"string",path:!0},{key:"daemonBaseUrl",type:"string"},{key:"daemonAuthToken",type:"string"},{key:"daemonTransport",type:"enum",enumValues:["auto","socket","http"]},{key:"daemonServerMode",type:"enum",enumValues:["socket","http","dual"]},{key:"tenant",type:"string"},{key:"sessionIsolation",type:"enum",enumValues:["none","tenant"]},{key:"runId",type:"string"},{key:"leaseId",type:"string"},{key:"leaseBackend",type:"enum",enumValues:["ios-simulator","ios-instance","android-instance"]},{key:"platform",type:"enum",enumValues:["ios","macos","android","linux","apple"]},{key:"target",type:"enum",enumValues:["mobile","tv","desktop"]},{key:"device",type:"string"},{key:"udid",type:"string"},{key:"serial",type:"string"},{key:"iosSimulatorDeviceSet",type:"string",path:!0,env:!1},{key:"androidDeviceAllowlist",type:"string"},{key:"session",type:"string"},{key:"metroProjectRoot",type:"string",path:!0},{key:"metroKind",type:"enum",enumValues:["auto","react-native","expo"]},{key:"metroPublicBaseUrl",type:"string"},{key:"metroProxyBaseUrl",type:"string"},{key:"metroBearerToken",type:"string"},{key:"metroPreparePort",type:"int",min:1,max:65535},{key:"metroListenHost",type:"string"},{key:"metroStatusHost",type:"string"},{key:"metroStartupTimeoutMs",type:"int",min:1},{key:"metroProbeTimeoutMs",type:"int",min:1},{key:"metroRuntimeFile",type:"string",path:!0},{key:"metroNoReuseExisting",type:"boolean"},{key:"metroNoInstallDeps",type:"boolean"}],f=new Map(u.map(e=>[e.key,e]));function y(e){let t=e.env??process.env;return r(e.configPath,{cwd:e.cwd,env:t})}function p(o){let i=function(o){let i,a,l=o.env??process.env,u=y(o);if(!e.existsSync(u))throw new n("INVALID_ARGS",`Remote config file not found: ${u}`);try{i=e.readFileSync(u,"utf8")}catch(e){throw new n("INVALID_ARGS",`Failed to read remote config file: ${u}`,{cause:e instanceof Error?e.message:String(e)})}try{a=JSON.parse(i)}catch(e){throw new n("INVALID_ARGS",`Invalid JSON in remote config file: ${u}`,{cause:e instanceof Error?e.message:String(e)})}if(!a||"object"!=typeof a||Array.isArray(a))throw new n("INVALID_ARGS",`Remote config file must contain a JSON object: ${u}`);let p={},m=a,c=t.dirname(u);for(let[e,t]of Object.entries(m)){let o=f.get(e);if(!o)throw new n("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${u}.`);let i=s(o,t,`remote config file ${u}`,e);p[o.key]="string"==typeof i&&"path"in o&&o.path?r(i,{cwd:c,env:l}):i}return{resolvedPath:u,profile:p}}(o);return{resolvedPath:i.resolvedPath,profile:function(...e){let t={};for(let n of e)if(n)for(let e of u){let r=n[e.key];void 0!==r&&(t[e.key]=r)}return t}(function(e=process.env){let t={};for(let n of u){let r=(function(e){let t=f.get(e);return t?.env===!1?[]:[a(e)]})(n.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);r&&(t[n.key]=s(n,r.value,`environment variable ${r.name}`,r.name))}return t}(o.env),i.profile)}}export{u as REMOTE_CONFIG_FIELD_SPECS,a as buildPrimaryEnvVarName,s as parseSourceValue,y as resolveRemoteConfigPath,p as resolveRemoteConfigProfile};
1
+ import e from"node:fs";import t from"node:path";import{parseSourceValue as n,buildPrimaryEnvVarName as o}from"./1010.js";import{AppError as r}from"./9152.js";import{resolveUserPath as i}from"./3267.js";let s=[{key:"stateDir",type:"string",path:!0},{key:"daemonBaseUrl",type:"string"},{key:"daemonAuthToken",type:"string"},{key:"daemonTransport",type:"enum",enumValues:["auto","socket","http"]},{key:"daemonServerMode",type:"enum",enumValues:["socket","http","dual"]},{key:"tenant",type:"string"},{key:"sessionIsolation",type:"enum",enumValues:["none","tenant"]},{key:"runId",type:"string"},{key:"leaseId",type:"string"},{key:"leaseBackend",type:"enum",enumValues:["ios-simulator","ios-instance","android-instance"]},{key:"platform",type:"enum",enumValues:["ios","macos","android","linux","apple"]},{key:"target",type:"enum",enumValues:["mobile","tv","desktop"]},{key:"device",type:"string"},{key:"udid",type:"string"},{key:"serial",type:"string"},{key:"iosSimulatorDeviceSet",type:"string",path:!0,env:!1},{key:"androidDeviceAllowlist",type:"string"},{key:"session",type:"string"},{key:"metroProjectRoot",type:"string",path:!0},{key:"metroKind",type:"enum",enumValues:["auto","react-native","expo"]},{key:"metroPublicBaseUrl",type:"string"},{key:"metroProxyBaseUrl",type:"string"},{key:"metroBearerToken",type:"string"},{key:"metroPreparePort",type:"int",min:1,max:65535},{key:"metroListenHost",type:"string"},{key:"metroStatusHost",type:"string"},{key:"metroStartupTimeoutMs",type:"int",min:1},{key:"metroProbeTimeoutMs",type:"int",min:1},{key:"metroRuntimeFile",type:"string",path:!0},{key:"metroNoReuseExisting",type:"boolean"},{key:"metroNoInstallDeps",type:"boolean"}],a=new Map(s.map(e=>[e.key,e]));function y(e){let t=e.env??process.env;return i(e.configPath,{cwd:e.cwd,env:t})}function m(m){let p=function(o){let s,m,p=o.env??process.env,l=y(o);if(!e.existsSync(l))throw new r("INVALID_ARGS",`Remote config file not found: ${l}`);try{s=e.readFileSync(l,"utf8")}catch(e){throw new r("INVALID_ARGS",`Failed to read remote config file: ${l}`,{cause:e instanceof Error?e.message:String(e)})}try{m=JSON.parse(s)}catch(e){throw new r("INVALID_ARGS",`Invalid JSON in remote config file: ${l}`,{cause:e instanceof Error?e.message:String(e)})}if(!m||"object"!=typeof m||Array.isArray(m))throw new r("INVALID_ARGS",`Remote config file must contain a JSON object: ${l}`);let u={},f=m,c=t.dirname(l);for(let[e,t]of Object.entries(f)){let o=a.get(e);if(!o)throw new r("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${l}.`);let s=n(o,t,`remote config file ${l}`,e);u[o.key]="string"==typeof s&&"path"in o&&o.path?i(s,{cwd:c,env:p}):s}return{resolvedPath:l,profile:u}}(m);return{resolvedPath:p.resolvedPath,profile:function(...e){let t={};for(let n of e)if(n)for(let e of s){let o=n[e.key];void 0!==o&&(t[e.key]=o)}return t}(function(e=process.env){let t={};for(let r of s){let i=(function(e){let t=a.get(e);return t?.env===!1?[]:[o(e)]})(r.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);i&&(t[r.key]=n(r,i.value,`environment variable ${i.name}`,i.name))}return t}(m.env),p.profile)}}export{s as REMOTE_CONFIG_FIELD_SPECS,y as resolveRemoteConfigPath,m as resolveRemoteConfigProfile};
package/dist/src/221.js CHANGED
@@ -1,6 +1,6 @@
1
- import e from"node:crypto";import t from"node:fs";import r from"node:fs/promises";import n from"node:os";import o from"node:path";import i from"node:net";import{AppError as a}from"./9152.js";import{isScrollableType as s}from"./2842.js";import{emitDiagnostic as u}from"./7599.js";import{installAndroidAdbPackage as l}from"./9639.js";let d="android-snapshot-helper",c="com.callstack.agentdevice.snapshothelper",h="com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation",p="android-snapshot-helper-v1",f="uiautomator-xml",m={"-r":"replace","-t":"allowTestPackages","-d":"allowDowngrade","-g":"grantPermissions"};async function w(e){let t=await v(e.apkPath);if(t!==e.manifest.sha256)throw new a("COMMAND_FAILED","Android snapshot helper APK checksum mismatch",{apkPath:e.apkPath,expectedSha256:e.manifest.sha256,actualSha256:t})}async function A(e){let t=e.fetch??fetch,i=await t(e.manifestUrl);if(!i.ok)throw new a("COMMAND_FAILED","Failed to download Android snapshot helper manifest",{manifestUrl:e.manifestUrl,status:i.status,statusText:i.statusText});let s=M(JSON.parse((await g(i,65536,"Android snapshot helper manifest")).toString("utf8")));if(!s.apkUrl)throw new a("COMMAND_FAILED","Android snapshot helper manifest does not include apkUrl",{manifestUrl:e.manifestUrl});let u=e.cacheDir??o.join(n.tmpdir(),`agent-device-android-snapshot-helper-${s.version}`),l=!e.cacheDir;await r.mkdir(u,{recursive:!0});let d=s.assetName??`agent-device-android-snapshot-helper-${s.version}.apk`,c=o.join(u,d),h=await t(s.apkUrl);if(!h.ok)throw new a("COMMAND_FAILED","Failed to download Android snapshot helper APK",{apkUrl:s.apkUrl,status:h.status,statusText:h.statusText});await r.writeFile(c,await g(h,0x1400000,"Android snapshot helper APK"));let p={apkPath:c,manifest:s};return await w(p),{...p,cleanup:async()=>{await r.rm(l?u:c,{recursive:l,force:!0})}}}function M(e){var t,r;if(!e||"object"!=typeof e||Array.isArray(e))throw new a("INVALID_ARGS","Android snapshot helper manifest must be an object.");return{name:C(e.name,"name",d),version:I(e.version,"version"),releaseTag:D(e.releaseTag),assetName:D(e.assetName),apkUrl:(t=e.apkUrl,r="apkUrl",null===t?null:I(t,r)),sha256:function(e){let t=I(e,"sha256").trim().toLowerCase();if(64!==t.length||!function(e){for(let t of e){let e=t.charCodeAt(0),r=e>=48&&e<=57,n=e>=97&&e<=102;if(!r&&!n)return!1}return!0}(t))throw new a("INVALID_ARGS","Android snapshot helper manifest sha256 must be a 64-character hex string.");return t}(e.sha256),checksumName:D(e.checksumName),packageName:I(e.packageName,"packageName"),versionCode:x(e.versionCode,"versionCode"),instrumentationRunner:I(e.instrumentationRunner,"instrumentationRunner"),minSdk:x(e.minSdk,"minSdk"),targetSdk:void 0===e.targetSdk?void 0:x(e.targetSdk,"targetSdk"),outputFormat:C(e.outputFormat,"outputFormat",f),statusProtocol:C(e.statusProtocol,"statusProtocol",p),installArgs:N(e.installArgs)}}async function g(e,t,r){let n=e.headers.get("content-length");if(null!==n){let e=Number(n);if(Number.isFinite(e)&&e>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:e,maxBytes:t})}if(!e.body){let n=Buffer.from(await e.arrayBuffer());if(n.length>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:n.length,maxBytes:t});return n}let o=e.body.getReader(),i=[],s=0;try{for(;;){let{done:e,value:n}=await o.read();if(e)break;if((s+=n.byteLength)>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:s,maxBytes:t});i.push(Buffer.from(n))}}finally{o.releaseLock()}return Buffer.concat(i,s)}function N(e){let t=function(e,t){if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be a string array.`);return e}(e,"installArgs");if("install"!==t[0])throw new a("INVALID_ARGS",'Android snapshot helper manifest installArgs must start with "install".');if(t.some(e=>e.includes("\0")))throw new a("INVALID_ARGS","Android snapshot helper manifest installArgs must not contain null bytes.");let r=t.slice(1).find(e=>void 0===y(e));if(r)throw new a("INVALID_ARGS",`Android snapshot helper manifest installArgs contains unsupported install flag "${r}".`);return t}async function v(r){return await new Promise((n,o)=>{let i=e.createHash("sha256"),a=t.createReadStream(r);a.on("error",o),a.on("data",e=>i.update(e)),a.on("end",()=>n(i.digest("hex")))})}function I(e,t){if("string"!=typeof e||0===e.trim().length)throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} is required.`);return e}function D(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function x(e,t){if("number"!=typeof e||!Number.isInteger(e))throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be an integer.`);return e}function C(e,t,r){if(e!==r)throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be "${r}".`);return r}function y(e){if(Object.hasOwn(m,e))return m[e]}function*S(e){let t=/<node\b[^>]*>/g,r=t.exec(e);for(;r;)yield _(r[0]),r=t.exec(e)}function _(e){let t,r,n,o=(t=function(e){let t=new Map,r=e.indexOf(" "),n=e.lastIndexOf(">");if(r<0||n<=r)return t;let o=r;for(;o<n&&!((o=F(e,o,n))>=n);){var i;let r=e[o];if("/"===r||">"===r)break;let a=o;for(;o<n&&!("="===(i=e[o]??"")||"/"===i||">"===i||L(i));)o+=1;let s=e.slice(a,o);if(o=F(e,o,n),!s||"="!==e[o])break;o=F(e,o+1,n);let u=e[o];if('"'!==u&&"'"!==u)break;let l=o+=1;for(;o<n&&e[o]!==u;)o+=1;if(o>=n)break;t.set(s,function(e){let t="",r=0;for(;r<e.length;){let n=e.indexOf("&",r);if(n<0){t+=e.slice(r);break}t+=e.slice(r,n);let o=e.indexOf(";",n+1);if(o<0){t+=e.slice(n);break}t+=function(e){switch(e){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'";default:return function(e){if(!e.startsWith("#"))return;let t=e[1]?.toLowerCase()==="x"?16:10,r=16===t?e.slice(2):e.slice(1);if(!r||!function(e,t){for(let r of e){let e=r.charCodeAt(0),n=e>=48&&e<=57;if(10===t){if(!n)return!1;continue}let o=e>=65&&e<=70,i=e>=97&&e<=102;if(!n&&!o&&!i)return!1}return!0}(r,t))return;let n=Number.parseInt(r,t);if(Number.isFinite(n))try{return String.fromCodePoint(n)}catch{return}}(e)}}(e.slice(n+1,o))??e.slice(n,o+1),r=o+1}return t}(e.slice(l,o))),o+=1}return t}(e),r=e=>{let r=T(t,e);if(null!==r)return"true"===r},n=(e,t)=>{let n=r(t);return void 0===n?{}:{[e]:n}},{text:T(t,"text"),desc:T(t,"content-desc"),resourceId:T(t,"resource-id"),packageName:T(t,"package"),className:T(t,"class"),bounds:T(t,"bounds"),clickable:r("clickable"),enabled:r("enabled"),focusable:r("focusable"),focused:r("focused"),password:r("password"),...n("scrollable","scrollable"),...n("canScrollForward","can-scroll-forward"),...n("canScrollBackward","can-scroll-backward")}),i=function(e){if(!e)return;let t=/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/.exec(e);if(!t)return;let r=Number(t[1]),n=Number(t[2]);return{x:r,y:n,width:Math.max(0,Number(t[3])-r),height:Math.max(0,Number(t[4])-n)}}(o.bounds);return{...o,...i?{rect:i}:{}}}function b(e,t,r){let{sourceNodes:n,...o}=k(E(e),t,r);return o}function k(e,t,r){let n={nodes:[],sourceNodes:[],maxNodes:t,maxDepth:r.depth??1/0,options:r,analysis:function(e){let t=0,r=0,n=[...e.children];for(;n.length>0;){let e=n.pop();t+=1,r=Math.max(r,e.depth),n.push(...e.children)}return{rawNodeCount:t,maxDepth:r}}(e),interactiveDescendantMemo:new Map,truncated:!1},o=r.scope?function(e,t){let r=t.toLowerCase(),n=[...e.children],o=0;for(;o<n.length;){let e=n[o++],t=e.label?.toLowerCase()??"",i=e.value?.toLowerCase()??"",a=e.identifier?.toLowerCase()??"";if(t.includes(r)||i.includes(r)||a.includes(r))return e;n.push(...e.children)}return null}(e,r.scope):null;for(let t of o?[o]:e.children)if(function e(t,r,n,o,i=!1,a=!1){if(t.nodes.length>=t.maxNodes){t.truncated=!0;return}if(n>t.maxDepth)return;let u=t.options.raw||function(e,t,r,n,o){var i,a,u;let l=function(e){let t=O(e.type),r=!!(e.label&&e.label.trim().length>0),n=!!(e.identifier&&e.identifier.trim().length>0);return{type:t,hasMeaningfulText:r&&!P(e.label??""),hasMeaningfulId:n&&!P(e.identifier??""),isStructural:function(e){let t=e.split(".").pop()??e;return t.includes("layout")||"viewgroup"===t||"view"===t}(t),isVisual:"imageview"===t||"imagebutton"===t}}(e);return t.interactiveOnly?function(e,t,r,n,o){var i,a,u,l,d;return!((i=e).rect&&(i.rect.width<=0||i.rect.height<=0))&&(!!(e.hittable||s(t.type)&&n)||(a=t,u=r,l=n,d=o,(!!a.hasMeaningfulText||!!a.hasMeaningfulId)&&!a.isVisual&&(!a.isStructural||!!d)&&(u||l||d)))}(e,l,r,n,o):t.compact?l.hasMeaningfulText||l.hasMeaningfulId||!!e.hittable:!l.isStructural&&!l.isVisual||(i=e,a=l,u=n,!!i.hittable||!!a.hasMeaningfulText||!!a.hasMeaningfulId&&!!u||u)}(r,t.options,i,function e(t,r){let n=t.interactiveDescendantMemo.get(r);if(void 0!==n)return n;for(let n of r.children)if(n.hittable||e(t,n))return t.interactiveDescendantMemo.set(r,!0),!0;return t.interactiveDescendantMemo.set(r,!1),!1}(t,r),a)?function(e,t,r,n){let o=e.nodes.length;return e.sourceNodes.push(t),e.nodes.push({index:o,type:t.type??void 0,label:t.label??void 0,value:t.value??void 0,identifier:t.identifier??void 0,bundleId:t.packageName??void 0,rect:t.rect,enabled:t.enabled,hittable:t.hittable,depth:r,parentIndex:n,...t.hiddenContentAbove?{hiddenContentAbove:!0}:{},...t.hiddenContentBelow?{hiddenContentBelow:!0}:{}}),o}(t,r,n,o):o,l=i||!!r.hittable,d=a||function(e){if(!e)return!1;let t=O(e);return t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")}(r.type);for(let o of r.children)if(e(t,o,n+1,u,l,d),t.truncated)return}(n,t,0),n.truncated)break;let i={nodes:n.nodes,sourceNodes:n.sourceNodes,analysis:n.analysis};return n.truncated?{...i,truncated:!0}:i}function F(e,t,r){for(;t<r&&L(e[t]??"");)t+=1;return t}function L(e){return" "===e||"\n"===e||"\r"===e||" "===e}function T(e,t){return e.get(t)??null}function E(e){let t={type:null,label:null,value:null,identifier:null,packageName:null,depth:-1,children:[]},r=[t],n=/<node\b[^>]*>|<\/node>/g,o=n.exec(e);for(;o;){let t=o[0];if(t.startsWith("</node")){r.length>1&&r.pop(),o=n.exec(e);continue}let i=_(t),a=r[r.length-1],s={type:i.className,label:i.text||i.desc,value:i.text,identifier:i.resourceId,packageName:i.packageName,rect:i.rect,enabled:i.enabled,hittable:i.clickable??i.focusable,scrollable:i.scrollable,canScrollForward:i.canScrollForward,canScrollBackward:i.canScrollBackward,depth:a.depth+1,parentIndex:void 0,children:[]};a.children.push(s),t.endsWith("/>")||r.push(s),o=n.exec(e)}return function(e){let t=[...e.children];for(;t.length>0;){let e=t.pop();t.push(...e.children),function(e){if(!e.scrollable||!s(e.type)||`${e.type??""}`.toLowerCase().includes("horizontalscrollview"))return!1;let t=function(e){if(!e.rect||0===e.children.length)return null;let t=e.children.map(e=>e.rect).filter(e=>void 0!==e);if(0===t.length)return null;let r=Math.min(...t.map(e=>e.x)),n=Math.max(...t.map(e=>e.x+e.width)),o=Math.min(...t.map(e=>e.y)),i=Math.max(...t.map(e=>e.y+e.height));return{horizontal:Math.max(0,n-r-e.rect.width),vertical:Math.max(0,i-o-e.rect.height)}}(e);return!t||!(t.horizontal>t.vertical)||!(t.horizontal>16)}(e)&&(e.canScrollBackward&&(e.hiddenContentAbove=!0),e.canScrollForward&&(e.hiddenContentBelow=!0))}}(t),t}function O(e){return e?e.toLowerCase():""}function P(e){let t=e.trim();return!!t&&/^[\w.]+:id\/[\w.-]+$/i.test(t)}async function R(e){let t=$(e),r=await e.adb(H(t),{allowFailure:!0,timeoutMs:t.commandTimeoutMs}),{output:n,cleanupDone:o}=await V(e,t,r);if(t.outputPath&&!o&&await Q(e.adb,t.outputPath),0!==r.exitCode)throw new a("COMMAND_FAILED","Android snapshot helper failed",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode,helper:n.metadata});return n}function $(e){let t=U(e.timeoutMs,8e3),r=U(e.packageName,c);return{waitForIdleTimeoutMs:U(e.waitForIdleTimeoutMs,25),waitForIdleQuietMs:U(e.waitForIdleQuietMs,25),timeoutMs:t,commandTimeoutMs:U(e.commandTimeoutMs,t+5e3),maxDepth:U(e.maxDepth,128),maxNodes:U(e.maxNodes,5e3),packageName:r,runner:U(e.instrumentationRunner,`${r}/.SnapshotInstrumentation`),...e.outputPath?{outputPath:e.outputPath}:{},...void 0!==e.emitChunks?{emitChunks:e.emitChunks}:{}}}function U(e,t){return void 0===e?t:e}function H(e){return["shell","am","instrument","-w","-e","waitForIdleTimeoutMs",String(e.waitForIdleTimeoutMs),"-e","waitForIdleQuietMs",String(e.waitForIdleQuietMs),"-e","timeoutMs",String(e.timeoutMs),"-e","maxDepth",String(e.maxDepth),"-e","maxNodes",String(e.maxNodes),...e.outputPath?["-e","outputPath",e.outputPath]:[],...void 0!==e.emitChunks?["-e","emitChunks",String(e.emitChunks)]:[],e.runner]}async function V(e,t,r){try{return{output:W(`${r.stdout}
2
- ${r.stderr}`),cleanupDone:!1}}catch(n){return await B(e,t,r,n)}}async function B(e,t,r,n){if(n instanceof a&&0!==r.exitCode&&n.details?.helper)throw n;let o=await K(e,t,r);if(o)return{output:o,cleanupDone:!0};throw new a("COMMAND_FAILED",0===r.exitCode?"Android snapshot helper output could not be parsed":"Android snapshot helper failed before returning parseable output",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode},n)}async function K(e,t,r){if(0===r.exitCode&&t.outputPath){var n;return await G(e.adb,t.outputPath,function(e){try{let t=q(e);return j(z(t.results))}catch{return null}}(`${r.stdout}
3
- ${r.stderr}`)??{outputFormat:f,waitForIdleTimeoutMs:(n=t).waitForIdleTimeoutMs,waitForIdleQuietMs:n.waitForIdleQuietMs,timeoutMs:n.timeoutMs,maxDepth:n.maxDepth,maxNodes:n.maxNodes,transport:"instrumentation"})}}async function G(e,t,r){let n;try{var o;n=await e((o=t,["shell","sh","-c",'cat "$1"; status=$?; rm -f "$1"; exit "$status"',"agent-device-snapshot-helper-output",o]),{allowFailure:!0,timeoutMs:5e3})}catch{return}if(0!==n.exitCode)return;let i=n.stdout.trim();if(i.includes("<hierarchy")&&i.includes("</hierarchy>"))return{xml:i,metadata:r}}async function Q(e,t){try{await e(["shell","rm","-f",t],{allowFailure:!0,timeoutMs:5e3})}catch{}}function W(e){let t=q(e),r=z(t.results);return{xml:function(e,t){if(0===e.length)throw new a("COMMAND_FAILED","Android snapshot helper did not return XML chunks",{helper:t});let r=function(e){let t=e[0]?.count??e.length;if(t<1||e.length!==t||e.some(e=>e.count!==t))throw new a("COMMAND_FAILED","Android snapshot helper returned incomplete XML chunks",{expectedChunks:t,actualChunks:e.length});return t}(e),n=Buffer.concat(function(e,t){let r=[];for(let n=0;n<t;n+=1){let o=e.get(n);if(void 0===o)throw new a("COMMAND_FAILED","Android snapshot helper returned incomplete XML chunks",{missingChunkIndex:n,expectedChunks:t});r.push(Buffer.from(o,"base64"))}return r}(function(e,t){let r=new Map;for(let n of e){if(void 0===n.index||n.index<0||n.index>=t)throw new a("COMMAND_FAILED","Android snapshot helper returned invalid chunk index",{chunkIndex:n.index,expectedChunks:t});if(r.has(n.index))throw new a("COMMAND_FAILED","Android snapshot helper returned duplicate XML chunks",{chunkIndex:n.index});r.set(n.index,n.payloadBase64)}return r}(e,r),r)).toString("utf8");if(!n.includes("<hierarchy")||!n.includes("</hierarchy>"))throw new a("COMMAND_FAILED","Android snapshot helper output did not contain XML",{xml:n});return n}(function(e){let t=[];for(let r of e){if(r.agentDeviceProtocol!==p||r.outputFormat!==f)continue;let{payloadBase64:e}=r;void 0!==e&&t.push({index:er(r.chunkIndex),count:er(r.chunkCount),payloadBase64:e})}return t}(t.status),r),metadata:{...j(r),transport:"instrumentation"}}}function X(e,t={outputFormat:f},r={},n=800){return{...b(e,n,r),metadata:t}}function z(e){let t=e.find(e=>e.agentDeviceProtocol===p);if(!t)throw new a("COMMAND_FAILED","Android snapshot helper did not return a final result");if("true"!==t.ok){var r;throw new a("COMMAND_FAILED",(r=t).message&&"null"!==r.message?r.message:r.errorType||"Android snapshot helper returned an error",{errorType:t.errorType,helper:t})}return t}function j(e){var t;return{helperApiVersion:e.helperApiVersion,outputFormat:f,waitForIdleTimeoutMs:er(e.waitForIdleTimeoutMs),waitForIdleQuietMs:er(e.waitForIdleQuietMs),timeoutMs:er(e.timeoutMs),maxDepth:er(e.maxDepth),maxNodes:er(e.maxNodes),rootPresent:en(e.rootPresent),captureMode:"interactive-windows"===(t=e.captureMode)||"active-window"===t?t:void 0,windowCount:er(e.windowCount),nodeCount:er(e.nodeCount),truncated:en(e.truncated),elapsedMs:er(e.elapsedMs)}}function q(e){var t;let r={status:[],results:[],currentStatus:null,currentResult:null};for(let t of e.split(/\r?\n/))!function(e,t){if(e.startsWith("INSTRUMENTATION_STATUS: ")){t.currentStatus??={},Z(e.slice(24),t.currentStatus);return}if(e.startsWith("INSTRUMENTATION_STATUS_CODE: "))return J(t);if(e.startsWith("INSTRUMENTATION_RESULT: ")){t.currentResult??={},Z(e.slice(24),t.currentResult);return}e.startsWith("INSTRUMENTATION_CODE: ")&&Y(t)}(t,r);return J(t=r),Y(t),{status:r.status,results:r.results}}function J(e){e.currentStatus&&(e.status.push(e.currentStatus),e.currentStatus=null)}function Y(e){e.currentResult&&(e.results.push(e.currentResult),e.currentResult=null)}function Z(e,t){let r=e.indexOf("=");r<0||(t[e.slice(0,r)]=e.slice(r+1))}function ee(e){if(void 0===e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function et(e){return"true"===e||"false"!==e&&void 0}let er=ee,en=et,eo=new Map;async function ei(e){var t,r,n;let o;if(!(void 0===(o=process.env.AGENT_DEVICE_ANDROID_SNAPSHOT_HELPER_SESSION)||!/^(0|false|no|off)$/i.test(o))||!e.adbProvider?.spawn)return;let i=$(e),a=e.deviceKey??"android:default",s=(t=a,r=i,n=e,JSON.stringify({deviceKey:t,packageName:r.packageName,runner:r.runner,helperVersion:n.helperVersion,helperVersionCode:n.helperVersionCode,waitForIdleTimeoutMs:r.waitForIdleTimeoutMs,waitForIdleQuietMs:r.waitForIdleQuietMs,timeoutMs:r.timeoutMs,maxDepth:r.maxDepth,maxNodes:r.maxNodes})),u=eo.get(a);u&&u.identity!==s&&(await ea(a),u=void 0),u||(u=await es({deviceKey:a,identity:s,options:e,resolved:i}));try{let e=u.capturedCount>0,t=await eu(u,i);return u.capturedCount+=1,{xml:t.xml,metadata:{...t.metadata,transport:"persistent-session",sessionReused:e}}}catch(e){throw await ea(a),e}}async function ea(e){let t=eo.get(e);if(t){eo.delete(e);try{await el(t,`quit ${Date.now()}`,1e3)}catch{}try{await t.process.kill("SIGTERM")}catch{}try{await ed(t)}catch{}u({phase:"android_snapshot_helper_session_stop",data:{deviceKey:e,port:t.port,capturedCount:t.capturedCount,lifetimeMs:Date.now()-t.startedAtMs}})}}async function es(e){let t=await new Promise((e,t)=>{let r=i.createServer();r.unref(),r.on("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address();if(!n||"string"==typeof n)return void r.close(()=>t(Error("Failed to allocate a local TCP port")));let o=n.port;r.close(()=>e(o))})});await e.options.adb(["forward",`tcp:${t}`,`tcp:${t}`],{allowFailure:!1,timeoutMs:5e3});let r=H({...e.resolved,outputPath:void 0,emitChunks:!1}),n=r[r.length-1];if(!n)throw new a("INVALID_ARGS","Android snapshot helper runner was not resolved");let o=[...r.slice(0,-1),"-e","sessionPort",String(t),n],s=e.options.adbProvider.spawn(o,{allowFailure:!0,captureOutput:!1}),l={identity:e.identity,deviceKey:e.deviceKey,port:t,adb:e.options.adb,process:s,startedAtMs:Date.now(),capturedCount:0};try{var d;return await (d=s,new Promise((e,t)=>{let r="",n=setTimeout(()=>{t(new a("COMMAND_FAILED","Android snapshot helper session did not become ready",{output:r,timeoutMs:1e4}))},1e4),o=t=>{(r+=t.toString()).includes(`agentDeviceProtocol=${p}`)&&r.includes("sessionReady=true")&&(clearTimeout(n),e())};d.stdout?.on("data",o),d.stderr?.on("data",o),d.once("exit",(e,o)=>{clearTimeout(n),t(new a("COMMAND_FAILED","Android snapshot helper session exited before ready",{output:r,exitCode:e,signal:o}))}),d.on("error",e=>{clearTimeout(n),t(e)})})),eo.set(e.deviceKey,l),u({phase:"android_snapshot_helper_session_ready",data:{deviceKey:e.deviceKey,port:t,packageName:e.resolved.packageName,runner:e.resolved.runner}}),l}catch(e){await ed(l);try{s.kill("SIGTERM")}catch{}throw e}}async function eu(e,t){let r=`snapshot-${Date.now()}-${Math.random().toString(16).slice(2)}`,n=Math.max(t.timeoutMs+2e3,3e3);return function(e,t){var r;let{headers:n,xml:o}=function(e){let t=e.indexOf("\n\n");if(t<0)throw new a("COMMAND_FAILED","Android snapshot helper session returned malformed output",{response:e});return{headers:function(e){let t={};for(let r of e.split(/\r?\n/)){let e=r.indexOf("=");e<0||(t[r.slice(0,e)]=r.slice(e+1))}return t}(e.slice(0,t)),xml:e.slice(t+2)}}(e);return function(e,t){if(e.agentDeviceProtocol!==p)throw new a("COMMAND_FAILED","Android snapshot helper session returned wrong protocol",{headers:e});if(e.outputFormat!==f)throw new a("COMMAND_FAILED","Android snapshot helper session returned wrong output format",{headers:e});if(e.requestId!==t)throw new a("COMMAND_FAILED","Android snapshot helper session returned stale output",{headers:e,requestId:t});if("true"!==e.ok)throw new a("COMMAND_FAILED",e.message||e.errorType||"Android snapshot helper session returned an error",{helper:e})}(n,t),function(e,t){let r=ee(e.byteLength);if(void 0!==r&&Buffer.byteLength(t,"utf8")!==r)throw new a("COMMAND_FAILED","Android snapshot helper session returned truncated XML",{headers:e,actualByteLength:Buffer.byteLength(t,"utf8")});if(!t.includes("<hierarchy")||!t.includes("</hierarchy>"))throw new a("COMMAND_FAILED","Android snapshot helper session did not return XML",{headers:e,xml:t})}(n,o),{xml:o,metadata:{helperApiVersion:(r=n).helperApiVersion,outputFormat:f,waitForIdleTimeoutMs:ee(r.waitForIdleTimeoutMs),waitForIdleQuietMs:ee(r.waitForIdleQuietMs),timeoutMs:ee(r.timeoutMs),maxDepth:ee(r.maxDepth),maxNodes:ee(r.maxNodes),rootPresent:et(r.rootPresent),captureMode:"interactive-windows"===r.captureMode||"active-window"===r.captureMode?r.captureMode:void 0,windowCount:ee(r.windowCount),nodeCount:ee(r.nodeCount),truncated:et(r.truncated),elapsedMs:ee(r.elapsedMs)}}}(await el(e,`snapshot ${r}`,n),r)}function el(e,t,r){return new Promise((n,o)=>{let s=i.connect({host:"127.0.0.1",port:e.port}),u=[],l=setTimeout(()=>{s.destroy(),o(new a("COMMAND_FAILED","Android snapshot helper session request timed out",{command:t,timeoutMs:r,port:e.port}))},r);s.on("connect",()=>{s.write(`${t}
4
- `)}),s.on("data",e=>{u.push(Buffer.from(e))}),s.on("error",e=>{clearTimeout(l),o(e)}),s.on("close",()=>{clearTimeout(l),n(Buffer.concat(u).toString("utf8"))})})}async function ed(e){await e.process.stdin?.end(),await e.process.stdout?.destroy(),await e.process.stderr?.destroy(),await ec(e)}async function ec(e){await e.adb(["forward","--remove",`tcp:${e.port}`],{allowFailure:!0,timeoutMs:5e3})}let eh=new Map;function ep(e){em(ef(e.deviceKey,e.packageName,e.versionCode))}function ef(e,t,r){return e?`${e}\0${t}\0${r}`:void 0}function em(e){e&&eh.delete(e)}async function ew(e){var t,r,n;let{adb:o,artifact:i}=e,s=e.installPolicy??"missing-or-outdated",u=i.manifest.packageName,l=i.manifest.versionCode;if("never"===s)return{packageName:u,versionCode:l,installed:!1,reason:"skipped"};let d=ef(e.deviceKey,u,l),c=d?eh.get(d):void 0;if(d&&"always"!==s&&void 0!==c)return{packageName:u,versionCode:l,installedVersionCode:c,installed:!1,reason:"current"};let h=await eA(o,u,e.timeoutMs),p=(t=s,r=h,n=l,"never"===t?"skipped":"always"===t?"forced":void 0===r?"missing":r<n?"outdated":"current");if("current"===p){if(void 0===h)throw Error("Expected installed versionCode for current Android snapshot helper");return d&&eh.set(d,h),{packageName:u,versionCode:l,installedVersionCode:h,installed:!1,reason:p}}await w(i);let f=await eM(o,e.adbProvider??o,i.apkPath,function(e){let t={};for(let r of e.slice(1)){let e=y(r);if(!e)throw new a("INVALID_ARGS",`Android snapshot helper manifest installArgs contains unsupported install flag "${r}".`);t[e]=!0}return t}(N(i.manifest.installArgs)),{packageName:u,timeoutMs:e.timeoutMs});if(0!==f.exitCode)throw em(d),new a("COMMAND_FAILED","Failed to install Android snapshot helper",{packageName:u,versionCode:l,stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode});return d&&eh.set(d,l),{packageName:u,versionCode:l,installedVersionCode:h,installed:!0,reason:p}}async function eA(e,t,r){let n=await e(["shell","cmd","package","list","packages","--show-versioncode",t],{allowFailure:!0,timeoutMs:r});if(0===n.exitCode){var o=`${n.stdout}
5
- ${n.stderr}`,i=t;let e=`package:${i}`;for(let t of o.split(/\r?\n/)){if(!t.startsWith(e)||t.length>e.length&&!/\s/.test(t[e.length]??""))continue;let r=/(?:^|\s)versionCode:(\d+)(?:\s|$)/.exec(t);if(r)return Number(r[1])}return}}async function eM(e,t,r,n,o){var i;let a=async()=>await l(r,{allowFailure:!0,provider:t,...n,timeoutMs:o.timeoutMs}),s=await a();if(0===s.exitCode||(i=s,!`${i.stdout}
6
- ${i.stderr}`.includes("INSTALL_FAILED_UPDATE_INCOMPATIBLE")))return s;let u=await e(["uninstall",o.packageName],{allowFailure:!0,timeoutMs:o.timeoutMs}),d=await a();return 0===d.exitCode?d:{...d,stderr:[d.stderr,u.stderr?`Previous uninstall stderr after INSTALL_FAILED_UPDATE_INCOMPATIBLE: ${u.stderr}`:""].filter(Boolean).join("\n")}}export{d as ANDROID_SNAPSHOT_HELPER_NAME,f as ANDROID_SNAPSHOT_HELPER_OUTPUT_FORMAT,c as ANDROID_SNAPSHOT_HELPER_PACKAGE,p as ANDROID_SNAPSHOT_HELPER_PROTOCOL,h as ANDROID_SNAPSHOT_HELPER_RUNNER,S as androidUiNodes,k as buildUiHierarchySnapshot,R as captureAndroidSnapshotWithHelper,ei as captureAndroidSnapshotWithHelperSession,ew as ensureAndroidSnapshotHelper,ep as forgetAndroidSnapshotHelperInstall,M as parseAndroidSnapshotHelperManifest,W as parseAndroidSnapshotHelperOutput,X as parseAndroidSnapshotHelperXml,b as parseUiHierarchy,E as parseUiHierarchyTree,A as prepareAndroidSnapshotHelperArtifactFromManifestUrl,ea as stopAndroidSnapshotHelperSession,w as verifyAndroidSnapshotHelperArtifact};
1
+ import e from"node:crypto";import t from"node:fs";import r from"node:fs/promises";import n from"node:os";import i from"node:path";import o from"node:net";import{AppError as a}from"./9152.js";import{isScrollableType as s}from"./2842.js";import{emitDiagnostic as l}from"./7599.js";import{installAndroidAdbPackage as u}from"./9639.js";let d="android-snapshot-helper",c="com.callstack.agentdevice.snapshothelper",h="com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation",p="android-snapshot-helper-v1",f="uiautomator-xml",w={"-r":"replace","-t":"allowTestPackages","-d":"allowDowngrade","-g":"grantPermissions"};async function m(e){let t=await N(e.apkPath);if(t!==e.manifest.sha256)throw new a("COMMAND_FAILED","Android snapshot helper APK checksum mismatch",{apkPath:e.apkPath,expectedSha256:e.manifest.sha256,actualSha256:t})}async function A(e){let t=e.fetch??fetch,o=await t(e.manifestUrl);if(!o.ok)throw new a("COMMAND_FAILED","Failed to download Android snapshot helper manifest",{manifestUrl:e.manifestUrl,status:o.status,statusText:o.statusText});let s=M(JSON.parse((await g(o,65536,"Android snapshot helper manifest")).toString("utf8")));if(!s.apkUrl)throw new a("COMMAND_FAILED","Android snapshot helper manifest does not include apkUrl",{manifestUrl:e.manifestUrl});let l=e.cacheDir??i.join(n.tmpdir(),`agent-device-android-snapshot-helper-${s.version}`),u=!e.cacheDir;await r.mkdir(l,{recursive:!0});let d=s.assetName??`agent-device-android-snapshot-helper-${s.version}.apk`,c=i.join(l,d),h=await t(s.apkUrl);if(!h.ok)throw new a("COMMAND_FAILED","Failed to download Android snapshot helper APK",{apkUrl:s.apkUrl,status:h.status,statusText:h.statusText});await r.writeFile(c,await g(h,0x1400000,"Android snapshot helper APK"));let p={apkPath:c,manifest:s};return await m(p),{...p,cleanup:async()=>{await r.rm(u?l:c,{recursive:u,force:!0})}}}function M(e){var t,r;if(!e||"object"!=typeof e||Array.isArray(e))throw new a("INVALID_ARGS","Android snapshot helper manifest must be an object.");return{name:D(e.name,"name",d),version:y(e.version,"version"),releaseTag:x(e.releaseTag),assetName:x(e.assetName),apkUrl:(t=e.apkUrl,r="apkUrl",null===t?null:y(t,r)),sha256:function(e){let t=y(e,"sha256").trim().toLowerCase();if(64!==t.length||!function(e){for(let t of e){let e=t.charCodeAt(0),r=e>=48&&e<=57,n=e>=97&&e<=102;if(!r&&!n)return!1}return!0}(t))throw new a("INVALID_ARGS","Android snapshot helper manifest sha256 must be a 64-character hex string.");return t}(e.sha256),checksumName:x(e.checksumName),packageName:y(e.packageName,"packageName"),versionCode:I(e.versionCode,"versionCode"),instrumentationRunner:y(e.instrumentationRunner,"instrumentationRunner"),minSdk:I(e.minSdk,"minSdk"),targetSdk:void 0===e.targetSdk?void 0:I(e.targetSdk,"targetSdk"),outputFormat:D(e.outputFormat,"outputFormat",f),statusProtocol:D(e.statusProtocol,"statusProtocol",p),installArgs:v(e.installArgs)}}async function g(e,t,r){let n=e.headers.get("content-length");if(null!==n){let e=Number(n);if(Number.isFinite(e)&&e>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:e,maxBytes:t})}if(!e.body){let n=Buffer.from(await e.arrayBuffer());if(n.length>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:n.length,maxBytes:t});return n}let i=e.body.getReader(),o=[],s=0;try{for(;;){let{done:e,value:n}=await i.read();if(e)break;if((s+=n.byteLength)>t)throw new a("COMMAND_FAILED",`${r} download exceeds size limit`,{contentLength:s,maxBytes:t});o.push(Buffer.from(n))}}finally{i.releaseLock()}return Buffer.concat(o,s)}function v(e){let t=function(e,t){if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be a string array.`);return e}(e,"installArgs");if("install"!==t[0])throw new a("INVALID_ARGS",'Android snapshot helper manifest installArgs must start with "install".');if(t.some(e=>e.includes("\0")))throw new a("INVALID_ARGS","Android snapshot helper manifest installArgs must not contain null bytes.");let r=t.slice(1).find(e=>void 0===C(e));if(r)throw new a("INVALID_ARGS",`Android snapshot helper manifest installArgs contains unsupported install flag "${r}".`);return t}async function N(r){return await new Promise((n,i)=>{let o=e.createHash("sha256"),a=t.createReadStream(r);a.on("error",i),a.on("data",e=>o.update(e)),a.on("end",()=>n(o.digest("hex")))})}function y(e,t){if("string"!=typeof e||0===e.trim().length)throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} is required.`);return e}function x(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function I(e,t){if("number"!=typeof e||!Number.isInteger(e))throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be an integer.`);return e}function D(e,t,r){if(e!==r)throw new a("INVALID_ARGS",`Android snapshot helper manifest ${t} must be "${r}".`);return r}function C(e){if(Object.hasOwn(w,e))return w[e]}function*b(e){let t=/<node\b[^>]*>/g,r=t.exec(e);for(;r;)yield S(r[0]),r=t.exec(e)}function S(e){let t,r,n,i,o,a=(t=function(e){let t=new Map,r=e.indexOf(" "),n=e.lastIndexOf(">");if(r<0||n<=r)return t;let i=r;for(;i<n&&!((i=F(e,i,n))>=n);){var o;let r=e[i];if("/"===r||">"===r)break;let a=i;for(;i<n&&!("="===(o=e[i]??"")||"/"===o||">"===o||T(o));)i+=1;let s=e.slice(a,i);if(i=F(e,i,n),!s||"="!==e[i])break;i=F(e,i+1,n);let l=e[i];if('"'!==l&&"'"!==l)break;let u=i+=1;for(;i<n&&e[i]!==l;)i+=1;if(i>=n)break;t.set(s,function(e){let t="",r=0;for(;r<e.length;){let n=e.indexOf("&",r);if(n<0){t+=e.slice(r);break}t+=e.slice(r,n);let i=e.indexOf(";",n+1);if(i<0){t+=e.slice(n);break}t+=function(e){switch(e){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'";default:return function(e){if(!e.startsWith("#"))return;let t=e[1]?.toLowerCase()==="x"?16:10,r=16===t?e.slice(2):e.slice(1);if(!r||!function(e,t){for(let r of e){let e=r.charCodeAt(0),n=e>=48&&e<=57;if(10===t){if(!n)return!1;continue}let i=e>=65&&e<=70,o=e>=97&&e<=102;if(!n&&!i&&!o)return!1}return!0}(r,t))return;let n=Number.parseInt(r,t);if(Number.isFinite(n))try{return String.fromCodePoint(n)}catch{return}}(e)}}(e.slice(n+1,i))??e.slice(n,i+1),r=i+1}return t}(e.slice(u,i))),i+=1}return t}(e),r=e=>{let r=L(t,e);if(null!==r)return"true"===r},n=(e,r)=>{let n=(e=>{let r=L(t,e);if(null===r||""===r.trim())return;let n=Number(r);return Number.isFinite(n)?n:void 0})(r);return void 0===n?{}:{[e]:n}},i=(e,t)=>{let n=r(t);return void 0===n?{}:{[e]:n}},{text:L(t,"text"),desc:L(t,"content-desc"),resourceId:L(t,"resource-id"),packageName:L(t,"package"),className:L(t,"class"),bounds:L(t,"bounds"),clickable:r("clickable"),enabled:r("enabled"),focusable:r("focusable"),focused:r("focused"),password:r("password"),...i("visibleToUser","visible-to-user"),...i("scrollable","scrollable"),...i("canScrollForward","can-scroll-forward"),...i("canScrollBackward","can-scroll-backward"),...n("windowIndex","window-index"),...n("windowType","window-type"),...n("windowLayer","window-layer"),...i("windowActive","window-active"),...i("windowFocused","window-focused"),...void 0===(o=E(L(t,"window-bounds")))?{}:{windowRect:o}}),s=E(a.bounds);return{...a,...s?{rect:s}:{}}}function _(e,t,r){let{sourceNodes:n,...i}=k(O(e),t,r);return i}function k(e,t,r){let n={nodes:[],sourceNodes:[],maxNodes:t,maxDepth:r.depth??1/0,options:r,analysis:function(e){let t=0,r=0,n=[...e.children];for(;n.length>0;){let e=n.pop();t+=1,r=Math.max(r,e.depth),n.push(...e.children)}return{rawNodeCount:t,maxDepth:r}}(e),interactiveDescendantMemo:new Map,truncated:!1},i=r.scope?function(e,t){let r=t.toLowerCase(),n=[...e.children],i=0;for(;i<n.length;){let e=n[i++],t=e.label?.toLowerCase()??"",o=e.value?.toLowerCase()??"",a=e.identifier?.toLowerCase()??"";if(t.includes(r)||o.includes(r)||a.includes(r))return e;n.push(...e.children)}return null}(e,r.scope):null;for(let t of i?[i]:e.children)if(function e(t,r,n,i,o=!1,a=!1){if(t.nodes.length>=t.maxNodes){t.truncated=!0;return}if(n>t.maxDepth)return;let l=t.options.raw||function(e,t,r,n,i){var o,a,l;if(!1===e.visibleToUser)return!1;let u=function(e){let t=U(e.type),r=!!(e.label&&e.label.trim().length>0),n=!!(e.identifier&&e.identifier.trim().length>0);return{type:t,hasMeaningfulText:r&&!H(e.label??""),hasMeaningfulId:n&&!H(e.identifier??""),isStructural:function(e){let t=e.split(".").pop()??e;return t.includes("layout")||"viewgroup"===t||"view"===t}(t),isVisual:"imageview"===t||"imagebutton"===t}}(e);return t.interactiveOnly?function(e,t,r,n,i){var o,a,l,u,d;return!((o=e).rect&&(o.rect.width<=0||o.rect.height<=0))&&(!!(e.hittable||s(t.type)&&n)||(a=t,l=r,u=n,d=i,(!!a.hasMeaningfulText||!!a.hasMeaningfulId)&&!a.isVisual&&(!a.isStructural||!!d)&&(l||u||d)))}(e,u,r,n,i):t.compact?u.hasMeaningfulText||u.hasMeaningfulId||!!e.hittable:!u.isStructural&&!u.isVisual||(o=e,a=u,l=n,!!o.hittable||!!a.hasMeaningfulText||!!a.hasMeaningfulId&&!!l||l)}(r,t.options,o,function e(t,r){let n=t.interactiveDescendantMemo.get(r);if(void 0!==n)return n;for(let n of r.children)if(!1!==n.visibleToUser&&(n.hittable||e(t,n)))return t.interactiveDescendantMemo.set(r,!0),!0;return t.interactiveDescendantMemo.set(r,!1),!1}(t,r),a)?function(e,t,r,n){let i=e.nodes.length;return e.sourceNodes.push(t),e.nodes.push({index:i,type:t.type??void 0,label:t.label??void 0,value:t.value??void 0,identifier:t.identifier??void 0,bundleId:t.packageName??void 0,rect:t.rect,enabled:t.enabled,visibleToUser:t.visibleToUser,hittable:t.hittable,depth:r,parentIndex:n,...t.hiddenContentAbove?{hiddenContentAbove:!0}:{},...t.hiddenContentBelow?{hiddenContentBelow:!0}:{}}),i}(t,r,n,i):i,u=o||!!r.hittable,d=a||function(e){if(!e)return!1;let t=U(e);return t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")}(r.type);for(let i of r.children)if(e(t,i,n+1,l,u,d),t.truncated)return}(n,t,0),n.truncated)break;let o={nodes:n.nodes,sourceNodes:n.sourceNodes,analysis:n.analysis};return n.truncated?{...o,truncated:!0}:o}function F(e,t,r){for(;t<r&&T(e[t]??"");)t+=1;return t}function T(e){return" "===e||"\n"===e||"\r"===e||" "===e}function L(e,t){return e.get(t)??null}function E(e){if(!e)return;let t=/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/.exec(e);if(!t)return;let r=Number(t[1]),n=Number(t[2]);return{x:r,y:n,width:Math.max(0,Number(t[3])-r),height:Math.max(0,Number(t[4])-n)}}function O(e){let t={type:null,label:null,value:null,identifier:null,packageName:null,depth:-1,children:[]},r=[t],n=/<node\b[^>]*>|<\/node>/g,i=n.exec(e);for(;i;){let t=i[0];if(t.startsWith("</node")){r.length>1&&r.pop(),i=n.exec(e);continue}let o=S(t),a=r[r.length-1],s={type:o.className,label:o.text||o.desc,value:o.text,identifier:o.resourceId,packageName:o.packageName,rect:o.rect,enabled:o.enabled,visibleToUser:o.visibleToUser,hittable:o.clickable??o.focusable,scrollable:o.scrollable,canScrollForward:o.canScrollForward,canScrollBackward:o.canScrollBackward,windowIndex:o.windowIndex,windowType:o.windowType,windowLayer:o.windowLayer,windowActive:o.windowActive,windowFocused:o.windowFocused,windowRect:o.windowRect,depth:a.depth+1,parentIndex:void 0,children:[]};a.children.push(s),t.endsWith("/>")||r.push(s),i=n.exec(e)}return function(e){let t,r=e.children.filter(P);if(r.length<2)return;let n=r.filter(e=>R(e)&&$(e));if(0===n.length)return;let i=(t=n.map(e=>e.windowLayer).filter(e=>void 0!==e)).length>0?Math.max(...t):void 0;e.children=e.children.filter(e=>!R(e)||!!$(e)&&(void 0===i||e.windowLayer===i))}(t),function(e){let t=[...e.children];for(;t.length>0;){let e=t.pop();t.push(...e.children),function(e){if(!e.scrollable||!s(e.type)||`${e.type??""}`.toLowerCase().includes("horizontalscrollview"))return!1;let t=function(e){if(!e.rect||0===e.children.length)return null;let t=e.children.map(e=>e.rect).filter(e=>void 0!==e);if(0===t.length)return null;let r=Math.min(...t.map(e=>e.x)),n=Math.max(...t.map(e=>e.x+e.width)),i=Math.min(...t.map(e=>e.y)),o=Math.max(...t.map(e=>e.y+e.height));return{horizontal:Math.max(0,n-r-e.rect.width),vertical:Math.max(0,o-i-e.rect.height)}}(e);return!t||!(t.horizontal>t.vertical)||!(t.horizontal>16)}(e)&&(e.canScrollBackward&&(e.hiddenContentAbove=!0),e.canScrollForward&&(e.hiddenContentBelow=!0))}}(t),t}function P(e){return void 0!==e.windowIndex||void 0!==e.windowType}function R(e){return 1===e.windowType}function $(e){return!0===e.windowActive||!0===e.windowFocused}function U(e){return e?e.toLowerCase():""}function H(e){let t=e.trim();return!!t&&/^[\w.]+:id\/[\w.-]+$/i.test(t)}async function V(e){let t=B(e),r=await e.adb(G(t),{allowFailure:!0,timeoutMs:t.commandTimeoutMs}),{output:n,cleanupDone:i}=await Q(e,t,r);if(t.outputPath&&!i&&await j(e.adb,t.outputPath),0!==r.exitCode)throw new a("COMMAND_FAILED","Android snapshot helper failed",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode,helper:n.metadata});return n}function B(e){let t=K(e.timeoutMs,8e3),r=K(e.packageName,c);return{waitForIdleTimeoutMs:K(e.waitForIdleTimeoutMs,500),waitForIdleQuietMs:K(e.waitForIdleQuietMs,100),timeoutMs:t,commandTimeoutMs:K(e.commandTimeoutMs,t+5e3),maxDepth:K(e.maxDepth,128),maxNodes:K(e.maxNodes,5e3),packageName:r,runner:K(e.instrumentationRunner,`${r}/.SnapshotInstrumentation`),...e.outputPath?{outputPath:e.outputPath}:{},...void 0!==e.emitChunks?{emitChunks:e.emitChunks}:{}}}function K(e,t){return void 0===e?t:e}function G(e){return["shell","am","instrument","-w","-e","waitForIdleTimeoutMs",String(e.waitForIdleTimeoutMs),"-e","waitForIdleQuietMs",String(e.waitForIdleQuietMs),"-e","timeoutMs",String(e.timeoutMs),"-e","maxDepth",String(e.maxDepth),"-e","maxNodes",String(e.maxNodes),...e.outputPath?["-e","outputPath",e.outputPath]:[],...void 0!==e.emitChunks?["-e","emitChunks",String(e.emitChunks)]:[],e.runner]}async function Q(e,t,r){try{return{output:q(`${r.stdout}
2
+ ${r.stderr}`),cleanupDone:!1}}catch(n){return await W(e,t,r,n)}}async function W(e,t,r,n){if(n instanceof a&&0!==r.exitCode&&n.details?.helper)throw n;let i=await X(e,t,r);if(i)return{output:i,cleanupDone:!0};throw new a("COMMAND_FAILED",0===r.exitCode?"Android snapshot helper output could not be parsed":"Android snapshot helper failed before returning parseable output",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode},n)}async function X(e,t,r){if(0===r.exitCode&&t.outputPath){var n;return await z(e.adb,t.outputPath,function(e){try{let t=ee(e);return Z(Y(t.results))}catch{return null}}(`${r.stdout}
3
+ ${r.stderr}`)??{outputFormat:f,waitForIdleTimeoutMs:(n=t).waitForIdleTimeoutMs,waitForIdleQuietMs:n.waitForIdleQuietMs,timeoutMs:n.timeoutMs,maxDepth:n.maxDepth,maxNodes:n.maxNodes,transport:"instrumentation"})}}async function z(e,t,r){let n;try{var i;n=await e((i=t,["shell","sh","-c",'cat "$1"; status=$?; rm -f "$1"; exit "$status"',"agent-device-snapshot-helper-output",i]),{allowFailure:!0,timeoutMs:5e3})}catch{return}if(0!==n.exitCode)return;let o=n.stdout.trim();if(o.includes("<hierarchy")&&o.includes("</hierarchy>"))return{xml:o,metadata:r}}async function j(e,t){try{await e(["shell","rm","-f",t],{allowFailure:!0,timeoutMs:5e3})}catch{}}function q(e){let t=ee(e),r=Y(t.results);return{xml:function(e,t){if(0===e.length)throw new a("COMMAND_FAILED","Android snapshot helper did not return XML chunks",{helper:t});let r=function(e){let t=e[0]?.count??e.length;if(t<1||e.length!==t||e.some(e=>e.count!==t))throw new a("COMMAND_FAILED","Android snapshot helper returned incomplete XML chunks",{expectedChunks:t,actualChunks:e.length});return t}(e),n=Buffer.concat(function(e,t){let r=[];for(let n=0;n<t;n+=1){let i=e.get(n);if(void 0===i)throw new a("COMMAND_FAILED","Android snapshot helper returned incomplete XML chunks",{missingChunkIndex:n,expectedChunks:t});r.push(Buffer.from(i,"base64"))}return r}(function(e,t){let r=new Map;for(let n of e){if(void 0===n.index||n.index<0||n.index>=t)throw new a("COMMAND_FAILED","Android snapshot helper returned invalid chunk index",{chunkIndex:n.index,expectedChunks:t});if(r.has(n.index))throw new a("COMMAND_FAILED","Android snapshot helper returned duplicate XML chunks",{chunkIndex:n.index});r.set(n.index,n.payloadBase64)}return r}(e,r),r)).toString("utf8");if(!n.includes("<hierarchy")||!n.includes("</hierarchy>"))throw new a("COMMAND_FAILED","Android snapshot helper output did not contain XML",{xml:n});return n}(function(e){let t=[];for(let r of e){if(r.agentDeviceProtocol!==p||r.outputFormat!==f)continue;let{payloadBase64:e}=r;void 0!==e&&t.push({index:ea(r.chunkIndex),count:ea(r.chunkCount),payloadBase64:e})}return t}(t.status),r),metadata:{...Z(r),transport:"instrumentation"}}}function J(e,t={outputFormat:f},r={},n=800){return{..._(e,n,r),metadata:t}}function Y(e){let t=e.find(e=>e.agentDeviceProtocol===p);if(!t)throw new a("COMMAND_FAILED","Android snapshot helper did not return a final result");if("true"!==t.ok){var r;throw new a("COMMAND_FAILED",(r=t).message&&"null"!==r.message?r.message:r.errorType||"Android snapshot helper returned an error",{errorType:t.errorType,helper:t})}return t}function Z(e){var t;return{helperApiVersion:e.helperApiVersion,outputFormat:f,waitForIdleTimeoutMs:ea(e.waitForIdleTimeoutMs),waitForIdleQuietMs:ea(e.waitForIdleQuietMs),timeoutMs:ea(e.timeoutMs),maxDepth:ea(e.maxDepth),maxNodes:ea(e.maxNodes),rootPresent:es(e.rootPresent),captureMode:"interactive-windows"===(t=e.captureMode)||"active-window"===t?t:void 0,windowCount:ea(e.windowCount),nodeCount:ea(e.nodeCount),truncated:es(e.truncated),elapsedMs:ea(e.elapsedMs)}}function ee(e){var t;let r={status:[],results:[],currentStatus:null,currentResult:null};for(let t of e.split(/\r?\n/))!function(e,t){if(e.startsWith("INSTRUMENTATION_STATUS: ")){t.currentStatus??={},en(e.slice(24),t.currentStatus);return}if(e.startsWith("INSTRUMENTATION_STATUS_CODE: "))return et(t);if(e.startsWith("INSTRUMENTATION_RESULT: ")){t.currentResult??={},en(e.slice(24),t.currentResult);return}e.startsWith("INSTRUMENTATION_CODE: ")&&er(t)}(t,r);return et(t=r),er(t),{status:r.status,results:r.results}}function et(e){e.currentStatus&&(e.status.push(e.currentStatus),e.currentStatus=null)}function er(e){e.currentResult&&(e.results.push(e.currentResult),e.currentResult=null)}function en(e,t){let r=e.indexOf("=");r<0||(t[e.slice(0,r)]=e.slice(r+1))}function ei(e){if(void 0===e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function eo(e){return"true"===e||"false"!==e&&void 0}let ea=ei,es=eo,el=new Map,eu=new Map;async function ed(e){var t,r,n;let i;if(!(void 0===(i=process.env.AGENT_DEVICE_ANDROID_SNAPSHOT_HELPER_SESSION)||!/^(0|false|no|off)$/i.test(i))||!e.adbProvider?.spawn)return;let o=B(e),a=e.deviceKey??"android:default",s=(t=a,r=o,n=e,JSON.stringify({deviceKey:t,packageName:r.packageName,runner:r.runner,helperVersion:n.helperVersion,helperVersionCode:n.helperVersionCode,waitForIdleTimeoutMs:r.waitForIdleTimeoutMs,waitForIdleQuietMs:r.waitForIdleQuietMs,timeoutMs:r.timeoutMs,maxDepth:r.maxDepth,maxNodes:r.maxNodes}));if(eu.get(a)===s)return;let u=el.get(a);if(u&&u.identity!==s&&(await ec(a),u=void 0),!u)try{u=await eh({deviceKey:a,identity:s,options:e,resolved:o})}catch(e){eu.set(a,s),l({level:"warn",phase:"android_snapshot_helper_session_disabled",data:{deviceKey:a,reason:e instanceof Error?e.message:String(e)}});return}try{let e=u.capturedCount>0,t=await ef(u,o);return u.capturedCount+=1,{xml:t.xml,metadata:{...t.metadata,transport:"persistent-session",sessionReused:e}}}catch(e){throw await ec(a),e}}async function ec(e){let t=el.get(e);if(t){el.delete(e);try{await ew(t,`quit ${Date.now()}`,1e3)}catch{}try{await t.process.kill("SIGTERM")}catch{}await ep(t.process,2e3);try{await em(t)}catch{}l({phase:"android_snapshot_helper_session_stop",data:{deviceKey:e,port:t.port,capturedCount:t.capturedCount,lifetimeMs:Date.now()-t.startedAtMs}})}}async function eh(e){let t=await new Promise((e,t)=>{let r=o.createServer();r.unref(),r.on("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address();if(!n||"string"==typeof n)return void r.close(()=>t(Error("Failed to allocate a local TCP port")));let i=n.port;r.close(()=>e(i))})});await e.options.adb(["forward",`tcp:${t}`,`tcp:${t}`],{allowFailure:!1,timeoutMs:5e3});let r=G({...e.resolved,outputPath:void 0,emitChunks:!1}),n=r[r.length-1];if(!n)throw new a("INVALID_ARGS","Android snapshot helper runner was not resolved");let i=[...r.slice(0,-1),"-e","sessionPort",String(t),n],s=e.options.adbProvider.spawn(i,{allowFailure:!0,captureOutput:!1}),u={identity:e.identity,deviceKey:e.deviceKey,port:t,adb:e.options.adb,process:s,startedAtMs:Date.now(),capturedCount:0};try{var d;return await (d=s,new Promise((e,t)=>{let r="",n=setTimeout(()=>{t(new a("COMMAND_FAILED","Android snapshot helper session did not become ready",{output:r,timeoutMs:1e4}))},1e4),i=t=>{(r+=t.toString()).includes(`agentDeviceProtocol=${p}`)&&r.includes("sessionReady=true")&&(clearTimeout(n),e())};d.stdout?.on("data",i),d.stderr?.on("data",i),d.once("exit",(e,i)=>{clearTimeout(n),t(new a("COMMAND_FAILED","Android snapshot helper session exited before ready",{output:r,exitCode:e,signal:i}))}),d.on("error",e=>{clearTimeout(n),t(e)})})),el.set(e.deviceKey,u),l({phase:"android_snapshot_helper_session_ready",data:{deviceKey:e.deviceKey,port:t,packageName:e.resolved.packageName,runner:e.resolved.runner}}),u}catch(e){await em(u);try{s.kill("SIGTERM")}catch{}throw await ep(s,2e3),e}}function ep(e,t){return new Promise(r=>{let n=setTimeout(r,t);e.once("close",()=>{clearTimeout(n),r()}),e.once("exit",()=>{clearTimeout(n),r()})})}async function ef(e,t){let r=`snapshot-${Date.now()}-${Math.random().toString(16).slice(2)}`,n=Math.max(t.timeoutMs+2e3,3e3);return function(e,t){var r;let{headers:n,xml:i}=function(e){let t=e.indexOf("\n\n");if(t<0)throw new a("COMMAND_FAILED","Android snapshot helper session returned malformed output",{response:e});return{headers:function(e){let t={};for(let r of e.split(/\r?\n/)){let e=r.indexOf("=");e<0||(t[r.slice(0,e)]=r.slice(e+1))}return t}(e.slice(0,t)),xml:e.slice(t+2)}}(e);return function(e,t){if(e.agentDeviceProtocol!==p)throw new a("COMMAND_FAILED","Android snapshot helper session returned wrong protocol",{headers:e});if(e.outputFormat!==f)throw new a("COMMAND_FAILED","Android snapshot helper session returned wrong output format",{headers:e});if(e.requestId!==t)throw new a("COMMAND_FAILED","Android snapshot helper session returned stale output",{headers:e,requestId:t});if("true"!==e.ok)throw new a("COMMAND_FAILED",e.message||e.errorType||"Android snapshot helper session returned an error",{helper:e})}(n,t),function(e,t){let r=ei(e.byteLength);if(void 0!==r&&Buffer.byteLength(t,"utf8")!==r)throw new a("COMMAND_FAILED","Android snapshot helper session returned truncated XML",{headers:e,actualByteLength:Buffer.byteLength(t,"utf8")});if(!t.includes("<hierarchy")||!t.includes("</hierarchy>"))throw new a("COMMAND_FAILED","Android snapshot helper session did not return XML",{headers:e,xml:t})}(n,i),{xml:i,metadata:{helperApiVersion:(r=n).helperApiVersion,outputFormat:f,waitForIdleTimeoutMs:ei(r.waitForIdleTimeoutMs),waitForIdleQuietMs:ei(r.waitForIdleQuietMs),timeoutMs:ei(r.timeoutMs),maxDepth:ei(r.maxDepth),maxNodes:ei(r.maxNodes),rootPresent:eo(r.rootPresent),captureMode:"interactive-windows"===r.captureMode||"active-window"===r.captureMode?r.captureMode:void 0,windowCount:ei(r.windowCount),nodeCount:ei(r.nodeCount),truncated:eo(r.truncated),elapsedMs:ei(r.elapsedMs)}}}(await ew(e,`snapshot ${r}`,n),r)}function ew(e,t,r){return new Promise((n,i)=>{let s=o.connect({host:"127.0.0.1",port:e.port}),l=[],u=setTimeout(()=>{s.destroy(),i(new a("COMMAND_FAILED","Android snapshot helper session request timed out",{command:t,timeoutMs:r,port:e.port}))},r);s.on("connect",()=>{s.write(`${t}
4
+ `)}),s.on("data",e=>{l.push(Buffer.from(e))}),s.on("error",e=>{clearTimeout(u),i(e)}),s.on("close",()=>{clearTimeout(u),n(Buffer.concat(l).toString("utf8"))})})}async function em(e){await e.process.stdin?.end(),await e.process.stdout?.destroy(),await e.process.stderr?.destroy(),await eA(e)}async function eA(e){await e.adb(["forward","--remove",`tcp:${e.port}`],{allowFailure:!0,timeoutMs:5e3})}let eM=new Map;function eg(e){eN(ev(e.deviceKey,e.packageName,e.versionCode))}function ev(e,t,r){return e?`${e}\0${t}\0${r}`:void 0}function eN(e){e&&eM.delete(e)}async function ey(e){var t,r,n;let{adb:i,artifact:o}=e,s=e.installPolicy??"missing-or-outdated",l=o.manifest.packageName,u=o.manifest.versionCode;if("never"===s)return{packageName:l,versionCode:u,installed:!1,reason:"skipped"};let d=ev(e.deviceKey,l,u),c=d?eM.get(d):void 0;if(d&&"always"!==s&&void 0!==c)return{packageName:l,versionCode:u,installedVersionCode:c,installed:!1,reason:"current"};let h=await ex(i,l,e.timeoutMs),p=(t=s,r=h,n=u,"never"===t?"skipped":"always"===t?"forced":void 0===r?"missing":r<n?"outdated":"current");if("current"===p){if(void 0===h)throw Error("Expected installed versionCode for current Android snapshot helper");return d&&eM.set(d,h),{packageName:l,versionCode:u,installedVersionCode:h,installed:!1,reason:p}}await m(o);let f=await eI(i,e.adbProvider??i,o.apkPath,function(e){let t={};for(let r of e.slice(1)){let e=C(r);if(!e)throw new a("INVALID_ARGS",`Android snapshot helper manifest installArgs contains unsupported install flag "${r}".`);t[e]=!0}return t}(v(o.manifest.installArgs)),{packageName:l,timeoutMs:e.timeoutMs});if(0!==f.exitCode)throw eN(d),new a("COMMAND_FAILED","Failed to install Android snapshot helper",{packageName:l,versionCode:u,stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode});return d&&eM.set(d,u),{packageName:l,versionCode:u,installedVersionCode:h,installed:!0,reason:p}}async function ex(e,t,r){let n=await e(["shell","cmd","package","list","packages","--show-versioncode",t],{allowFailure:!0,timeoutMs:r});if(0===n.exitCode){var i=`${n.stdout}
5
+ ${n.stderr}`,o=t;let e=`package:${o}`;for(let t of i.split(/\r?\n/)){if(!t.startsWith(e)||t.length>e.length&&!/\s/.test(t[e.length]??""))continue;let r=/(?:^|\s)versionCode:(\d+)(?:\s|$)/.exec(t);if(r)return Number(r[1])}return}}async function eI(e,t,r,n,i){var o;let a=async()=>await u(r,{allowFailure:!0,provider:t,...n,timeoutMs:i.timeoutMs}),s=await a();if(0===s.exitCode||(o=s,!`${o.stdout}
6
+ ${o.stderr}`.includes("INSTALL_FAILED_UPDATE_INCOMPATIBLE")))return s;let l=await e(["uninstall",i.packageName],{allowFailure:!0,timeoutMs:i.timeoutMs}),d=await a();return 0===d.exitCode?d:{...d,stderr:[d.stderr,l.stderr?`Previous uninstall stderr after INSTALL_FAILED_UPDATE_INCOMPATIBLE: ${l.stderr}`:""].filter(Boolean).join("\n")}}export{d as ANDROID_SNAPSHOT_HELPER_NAME,f as ANDROID_SNAPSHOT_HELPER_OUTPUT_FORMAT,c as ANDROID_SNAPSHOT_HELPER_PACKAGE,p as ANDROID_SNAPSHOT_HELPER_PROTOCOL,h as ANDROID_SNAPSHOT_HELPER_RUNNER,b as androidUiNodes,k as buildUiHierarchySnapshot,V as captureAndroidSnapshotWithHelper,ed as captureAndroidSnapshotWithHelperSession,ey as ensureAndroidSnapshotHelper,eg as forgetAndroidSnapshotHelperInstall,M as parseAndroidSnapshotHelperManifest,q as parseAndroidSnapshotHelperOutput,J as parseAndroidSnapshotHelperXml,_ as parseUiHierarchy,O as parseUiHierarchyTree,A as prepareAndroidSnapshotHelperArtifactFromManifestUrl,ec as stopAndroidSnapshotHelperSession,m as verifyAndroidSnapshotHelperArtifact};